context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Diagnostics; using System.Linq.Expressions; using FluentAssertions.Execution; namespace FluentAssertions.Primitives { /// <summary> /// Contains a number of methods to assert that a reference type object is in the expected state. /// </summary> [DebuggerNonUserCode] public abstract class ReferenceTypeAssertions<TSubject, TAssertions> where TAssertions : ReferenceTypeAssertions<TSubject, TAssertions> { /// <summary> /// Gets the object which value is being asserted. /// </summary> public TSubject Subject { get; protected set; } /// <summary> /// Asserts that the current object has not been initialized yet. /// </summary> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <see cref="because" />. /// </param> public AndConstraint<TAssertions> BeNull(string because = "", params object[] becauseArgs) { Execute.Assertion .ForCondition(ReferenceEquals(Subject, null)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:" + Context + "} to be <null>{reason}, but found {0}.", Subject); return new AndConstraint<TAssertions>((TAssertions)this); } /// <summary> /// Asserts that the current object has been initialized. /// </summary> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <see cref="because" />. /// </param> public AndConstraint<TAssertions> NotBeNull(string because = "", params object[] becauseArgs) { Execute.Assertion .ForCondition(!ReferenceEquals(Subject, null)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:" + Context + "} not to be <null>{reason}."); return new AndConstraint<TAssertions>((TAssertions)this); } /// <summary> /// Asserts that an object reference refers to the exact same object as another object reference. /// </summary> /// <param name="expected">The expected object</param> /// <param name="because"> /// A formatted phrase explaining why the assertion should be satisfied. If the phrase does not /// start with the word <i>because</i>, it is prepended to the message. /// </param> /// <param name="becauseArgs"> /// Zero or more values to use for filling in any <see cref="string.Format(string,object[])" /> compatible placeholders. /// </param> public AndConstraint<TAssertions> BeSameAs(TSubject expected, string because = "", params object[] becauseArgs) { Execute.Assertion .UsingLineBreaks .ForCondition(ReferenceEquals(Subject, expected)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:" + Context + "} to refer to {0}{reason}, but found {1}.", expected, Subject); return new AndConstraint<TAssertions>((TAssertions)this); } /// <summary> /// Asserts that an object reference refers to a different object than another object reference refers to. /// </summary> /// <param name="unexpected">The unexpected object</param> /// <param name="because"> /// A formatted phrase explaining why the assertion should be satisfied. If the phrase does not /// start with the word <i>because</i>, it is prepended to the message. /// </param> /// <param name="becauseArgs"> /// Zero or more values to use for filling in any <see cref="string.Format(string,object[])" /> compatible placeholders. /// </param> public AndConstraint<TAssertions> NotBeSameAs(TSubject unexpected, string because = "", params object[] becauseArgs) { Execute.Assertion .UsingLineBreaks .ForCondition(!ReferenceEquals(Subject, unexpected)) .BecauseOf(because, becauseArgs) .FailWith("Did not expect reference to object {0}{reason}.", unexpected); return new AndConstraint<TAssertions>((TAssertions)this); } /// <summary> /// Asserts that the object is of the specified type <typeparamref name="T"/>. /// </summary> /// <typeparam name="T">The expected type of the object.</typeparam> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <see cref="because" />. /// </param> public AndWhichConstraint<TAssertions, T> BeOfType<T>(string because = "", params object[] becauseArgs) { BeOfType(typeof(T), because, becauseArgs); return new AndWhichConstraint<TAssertions, T>((TAssertions)this, (T)(object)Subject); } /// <summary> /// Asserts that the object is not of the specified type <typeparamref name="T"/>. /// </summary> /// <typeparam name="T">The type that the subject is not supposed to be of.</typeparam> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <see cref="because" />. /// </param> public AndWhichConstraint<TAssertions, T> NotBeOfType<T>(string because = "", params object[] becauseArgs) { NotBeOfType(typeof(T), because, becauseArgs); return new AndWhichConstraint<TAssertions, T>((TAssertions)this, (T)(object)Subject); } /// <summary> /// Asserts that the object is of the specified type <paramref name="expectedType"/>. /// </summary> /// <param name="expectedType"> /// The type that the subject is supposed to be of. /// </param> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <see cref="because" />. /// </param> public AndConstraint<TAssertions> BeOfType(Type expectedType, string because = "", params object[] becauseArgs) { Execute.Assertion .ForCondition(!ReferenceEquals(Subject, null)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:type} to be {0}{reason}, but found <null>.", expectedType); Subject.GetType().Should().Be(expectedType, because, becauseArgs); return new AndConstraint<TAssertions>((TAssertions)this); } /// <summary> /// Asserts that the object is not of the specified type <paramref name="expectedType"/>. /// </summary> /// <param name="expectedType"> /// The type that the subject is not supposed to be of. /// </param> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <see cref="because" />. /// </param> public AndConstraint<TAssertions> NotBeOfType(Type expectedType, string because = "", params object[] becauseArgs) { Execute.Assertion .ForCondition(!ReferenceEquals(Subject, null)) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:type} not to be {0}{reason}, but found <null>.", expectedType); Subject.GetType().Should().NotBe(expectedType, because, becauseArgs); return new AndConstraint<TAssertions>((TAssertions)this); } /// <summary> /// Asserts that the object is assignable to a variable of type <typeparamref name="T"/>. /// </summary> /// <typeparam name="T">The type to which the object should be assignable.</typeparam> /// <param name="because">The reason why the object should be assignable to the type.</param> /// <param name="becauseArgs">The parameters used when formatting the <paramref name="because"/>.</param> /// <returns>An <see cref="AndWhichConstraint{TAssertions, T}"/> which can be used to chain assertions.</returns> public AndWhichConstraint<TAssertions, T> BeAssignableTo<T>(string because = "", params object[] becauseArgs) { Execute.Assertion .ForCondition(Subject is T) .BecauseOf(because, becauseArgs) .FailWith("Expected {context:" + Context + "} to be assignable to {0}{reason}, but {1} is not", typeof(T), Subject.GetType()); return new AndWhichConstraint<TAssertions, T>((TAssertions)this, (T)((object)Subject)); } /// <summary> /// Asserts that the <paramref name="predicate" /> is satisfied. /// </summary> /// <param name="predicate">The predicate which must be satisfied by the <typeparamref name="TSubject" />.</param> /// <param name="because">The reason why the predicate should be satisfied.</param> /// <param name="becauseArgs">The parameters used when formatting the <paramref name="because" />.</param> /// <returns>An <see cref="AndConstraint{T}" /> which can be used to chain assertions.</returns> public AndConstraint<TAssertions> Match(Expression<Func<TSubject, bool>> predicate, string because = "", params object[] becauseArgs) { return Match<TSubject>(predicate, because, becauseArgs); } /// <summary> /// Asserts that the <paramref name="predicate" /> is satisfied. /// </summary> /// <param name="predicate">The predicate which must be satisfied by the <typeparamref name="TSubject" />.</param> /// <param name="because">The reason why the predicate should be satisfied.</param> /// <param name="becauseArgs">The parameters used when formatting the <paramref name="because" />.</param> /// <returns>An <see cref="AndConstraint{T}" /> which can be used to chain assertions.</returns> public AndConstraint<TAssertions> Match<T>(Expression<Func<T, bool>> predicate, string because = "", params object[] becauseArgs) where T : TSubject { if (predicate == null) { throw new NullReferenceException("Cannot match an object against a <null> predicate."); } Execute.Assertion .ForCondition(predicate.Compile()((T)Subject)) .BecauseOf(because, becauseArgs) .FailWith("Expected {0} to match {1}{reason}.", Subject, predicate.Body); return new AndConstraint<TAssertions>((TAssertions)this); } /// <summary> /// Returns the type of the subject the assertion applies on. /// </summary> protected abstract string Context { get; } } }
/* Copyright (C) 2013-2015 MetaMorph Software, Inc Permission is hereby granted, free of charge, to any person obtaining a copy of this data, including any software or models in source or binary form, as well as any drawings, specifications, and documentation (collectively "the Data"), to deal in the Data without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Data, and to permit persons to whom the Data 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 Data. THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA. ======================= This version of the META tools is a fork of an original version produced by Vanderbilt University's Institute for Software Integrated Systems (ISIS). Their license statement: Copyright (C) 2011-2014 Vanderbilt University Developed with the sponsorship of the Defense Advanced Research Projects Agency (DARPA) and delivered to the U.S. Government with Unlimited Rights as defined in DFARS 252.227-7013. Permission is hereby granted, free of charge, to any person obtaining a copy of this data, including any software or models in source or binary form, as well as any drawings, specifications, and documentation (collectively "the Data"), to deal in the Data without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Data, and to permit persons to whom the Data 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 Data. THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA. */ using System; using System.Collections.Generic; using System.Collections; using System.Text; using System.Runtime.InteropServices; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Diagnostics; using System.Collections.Concurrent; using System.Threading; using System.Xml.Serialization; using GME.CSharp; using GME.MGA; using GME.MGA.Meta; using GME; using GME.MGA.Core; using CyPhyML = ISIS.GME.Dsml.CyPhyML.Interfaces; using CyPhyMLClasses = ISIS.GME.Dsml.CyPhyML.Classes; using ProtoBuf; using edu.vanderbilt.isis.meta; using MetaLinkProtobuf = edu.vanderbilt.isis.meta; using System.Security; using Newtonsoft.Json; using System.Reflection; using System.Xml; using System.Xml.XPath; using META; namespace CyPhyMetaLink { /// <summary> /// This file contains functionality related to business logic handling incoming messages (from Creo) /// </summary> [Guid(ComponentConfig_Addon.guid), ProgId(ComponentConfig_Addon.progID), ClassInterface(ClassInterfaceType.AutoDual)] [ComVisible(true)] public partial class CyPhyMetaLinkAddon : IMgaComponentEx, IGMEVersionInfo, IMgaEventSink { private readonly String CadAssemblyOrigin = "creo parameteric create assembly"; private readonly String GMEOrigin = "GME"; private readonly CreoStartupDialog StartupDialog = new CreoStartupDialog(); public static readonly String CadAssemblyTopic = "ISIS.METALINK.CADASSEMBLY"; public static readonly String ResyncTopic = "ISIS.METALINK.RESYNC"; public static readonly String ConnectTopic = "ISIS.METALINK.CADASSEMBLY.CONNECT"; public static readonly String ComponentUpdateTopic = "ISIS.METALINK.COMPONENT.UPDATE"; public static readonly String ComponentAnalysisPointTopic = "ISIS.METALINK.COMPONENT.UPDATE.ANALYSISPOINTS"; public static readonly String ComponentManifestTopic = "ISIS.METALINK.COMPONENT.MANIFEST"; public static readonly String ComponentCreateTopic = "ISIS.METALINK.COMPONENT.CREATE"; public static readonly String ComponentInfoTopic = "ISIS.METALINK.COMPONENT.INFO"; public static readonly String CadPassiveTopic = "ISIS.METALINK.CAD.PASSIVE"; public static readonly String SearchPathStr = "SearchPath"; private Dictionary<string, int> interests = new Dictionary<string, int>(); private Dictionary<string, int> InstanceIDToConstraint_Table = new Dictionary<string, int>(); readonly HashSet<string> datumKinds = new HashSet<string>() { "Datum", // abstract "Axis", "CoordinateSystem", "Point", "Surface" }; readonly Dictionary<string, string> datumKindsMap = new Dictionary<string, string>() { { "Datum", "DATUM" }, { "Axis", "AXIS" }, { "CoordinateSystem", "CSYS" }, { "Point", "POINT" }, { "Surface", "SURFACE" }, }; private void ProcessEditMessage(MetaLinkProtobuf.Edit message) { if (GMEConsole == null) { GMEConsole = GMEConsole.CreateFromProject(addon.Project); } // This is the first message from Creo, hide the Startup Dialog if (StartupDialog.Visible && message.origin.Contains(CadAssemblyOrigin) && message.editMode == Edit.EditMode.INTEREST && message.topic.Count == 2 && message.topic[1] == LastStartedGuid) { ShowStartupDialog(false); } // Drop a warning message to the console if it's a suspicious response if (message.actions.Count > 0) { foreach (var action in message.actions) { foreach (var notice in action.notices) { if (notice.noticeMode == Notice.NoticeMode.DONE) { GMEConsole.Info.WriteLine("Done response from Meta-Link: " + notice.msg); } else if (notice.noticeMode == Notice.NoticeMode.ACK) { GMEConsole.Info.WriteLine("Ack response from Meta-Link: " + notice.msg); } else if (notice.noticeMode == Notice.NoticeMode.WARN) { GMEConsole.Warning.WriteLine("Warn response from Meta-Link: " + notice.msg); } } } } if (message.mode.SequenceEqual(new Edit.EditMode[] { Edit.EditMode.INTEREST, MetaLinkProtobuf.Edit.EditMode.NOTICE })) { // Start Creo in design editing mode if (message.topic.Count == 2 && message.topic[0] == CadAssemblyTopic && message.notices.Count == 1 && message.notices[0].noticeMode == Notice.NoticeMode.ACK) { // message.topic[1] is the assembly GUID string assemblyGuid = Guid.Parse(message.topic[1]).ToString(); string exeparams = ""; addon.Project.BeginTransactionInNewTerr(); try { exeparams = GetStartupParams(assemblyGuid); } finally { addon.Project.AbortTransaction(); } StartAssemblyExe(CreoOpenMode.OPEN_COMPONENT, assemblyGuid, true, exeparams); } // Start Creo in AVM component editing mode if (message.topic.Count >= 2 && message.topic[0] == ComponentUpdateTopic && message.notices.Count == 1 && message.notices[0].noticeMode == Notice.NoticeMode.ACK) { Action<MetaLinkProtobuf.Edit> action; if (noticeActions.TryGetValue(message.guid, out action)) { noticeActions.Remove(message.guid); action(message); } } } if (message.mode.Count > 0 && message.mode.Last() == MetaLinkProtobuf.Edit.EditMode.NOTICE) { foreach (var notice in message.actions.SelectMany(a => a.notices) .Where(n => n.noticeMode == Notice.NoticeMode.FAULT || n.noticeMode == Notice.NoticeMode.FAIL || n.noticeMode == Notice.NoticeMode.REJECT)) { GMEConsole.Error.WriteLine("Meta-Link error: " + notice.msg); } } if (message.origin.Contains(GMEOrigin)) // ignore messages from ourselves return; // DISINTEREST: The user closed Creo (component) if (message.topic.Count == 2 && (message.topic[0] == ComponentUpdateTopic || message.topic[0] == CadPassiveTopic) && message.mode.SequenceEqual(new Edit.EditMode[] { Edit.EditMode.DISINTEREST })) { if (message.topic[0] == ComponentUpdateTopic) { String componentAVMID = message.topic[1]; //componentEditMessages.Remove(componentAVMID); syncedComponents.Remove(componentAVMID); SendDisinterest(ComponentUpdateTopic, componentAVMID); addon.Project.BeginTransactionInNewTerr(); try { var component = CyphyMetaLinkUtils.GetComponentByAvmId(addon.Project, componentAVMID); if (component != null) { HighlightInTree(component, 0); } } finally { addon.Project.AbortTransaction(); } } else { syncedComponents.Remove(""); // CAD has been started in an empty mode } } // DISINTEREST: The user closed Creo (design) if (message.topic.Count == 2 && message.topic[0] == CadAssemblyTopic && message.mode.SequenceEqual(new Edit.EditMode[] { Edit.EditMode.DISINTEREST })) { Guid componentAssemblyID = Guid.Parse(message.topic[1]); /*try{ Directory.Delete(syncedComponents[componentAssemblyID.ToString()].WorkingDir); } catch (Exception e) { GMEConsole.Warning.WriteLine("Unable to delete working directory: " + e.Message); }*/ syncedComponents.Remove(componentAssemblyID.ToString()); SendDisinterest(CadAssemblyTopic, message.topic[1]); addon.Project.BeginTransactionInNewTerr(); try { CyPhyML.ComponentAssembly assembly = CyphyMetaLinkUtils.GetComponentAssemblyByGuid(addon.Project, AssemblyID); if (assembly != null) { HighlightInTree(assembly, 0); } } finally { addon.Project.AbortTransaction(); } AssemblyID = null; } if (message.topic.Count == 2 && message.topic[0] == ComponentAnalysisPointTopic && message.mode.SequenceEqual(new Edit.EditMode[] { Edit.EditMode.POST })) { foreach (var action in message.actions) { ProcessAnalysisPointMessage(message.topic[1], action); } } // Design edit message (insert/select/discard) if (message.topic.Count == 2 && message.topic[0] == CadAssemblyTopic && message.mode.SequenceEqual(new Edit.EditMode[] { Edit.EditMode.POST })) { foreach (var action in message.actions) { if (action.actionMode == MetaLinkProtobuf.Action.ActionMode.INSERT && action.payload != null) { // Add an AVM component ProcessEditInsert(message.topic[1], action); } if (action.actionMode == MetaLinkProtobuf.Action.ActionMode.SELECT && action.payload != null) { // Select a component ref ProcessEditSelect(message.topic[1], action); } if (action.actionMode == MetaLinkProtobuf.Action.ActionMode.DISCARD) { // Remove a component ref ProcessEditDiscard(message.topic[1], action); } } } // Re-sync if (message.topic.Count == 2 && message.topic[0] == ResyncTopic && message.mode.SequenceEqual(new Edit.EditMode[] { Edit.EditMode.POST })) { ProcessResync(message.topic[1]); } if (message.topic.Count == 2 && message.topic[0] == CadAssemblyTopic && message.mode.SequenceEqual(new Edit.EditMode[] { Edit.EditMode.INTEREST })) { string designId = message.topic[1]; string xml; if (designIdToCadAssemblyXml.TryGetValue(designId, out xml)) { addon.Project.BeginTransactionInNewTerr(); try { SendCadAssemblyXml(xml, designId, false); SaveCadAssemblyXml(xml, designId); } finally { addon.Project.AbortTransaction(); } } else { GMEConsole.Warning.WriteLine("MetaLink: unknown assembly " + designId); } } // Request component list message from Creo if (message.topic.Count > 0 && message.topic[0] == ComponentManifestTopic && message.mode.SequenceEqual(new Edit.EditMode[] { Edit.EditMode.INTEREST })) { addon.Project.BeginTransactionInNewTerr(); try { SendComponentManifest(); } finally { addon.Project.AbortTransaction(); } } // Update AVM Component with the information from Creo if (message.mode.SequenceEqual(new Edit.EditMode[] { Edit.EditMode.POST }) && message.topic.Count >= 2 && message.topic[0] == ComponentUpdateTopic && message.actions.Count == 1 && message.actions[0].alien != null && message.actions[0].alien.encodingMode == Alien.EncodingMode.XML) { string componentId = message.topic[1]; string component_xml = Encoding.UTF8.GetString(message.actions[0].alien.encoded); ProcessAVMComponentUpdate(componentId, component_xml); } // Some type of AVM component update (INSERT, DISCARD, etc.) if (message.mode.SequenceEqual(new Edit.EditMode[] { Edit.EditMode.POST }) && message.topic.Count >= 2 && message.topic[0] == ComponentUpdateTopic && message.actions.Count >= 1) { string componentId = message.topic[1]; foreach (var action in message.actions) { if (action.actionMode == MetaLinkProtobuf.Action.ActionMode.INSERT && action.payload != null) { ProcessAVMComponentInsert(message.topic[1], action); } } } // Create new AVM component if (message.mode.SequenceEqual(new Edit.EditMode[] { Edit.EditMode.POST }) && message.topic.Count <= 2 && message.topic[0] == ComponentCreateTopic && message.actions.Count == 1 && message.actions[0].alien != null && message.actions[0].alien.encodingMode == Alien.EncodingMode.XML) { string component_xml = Encoding.UTF8.GetString(message.actions[0].alien.encoded); ProcessAVMComponentCreate(component_xml, message.topic.Count>1?message.topic[1]:null); } // Connect component within a design if (message.mode.SequenceEqual(new Edit.EditMode[] { Edit.EditMode.POST }) && message.topic.Count >= 1 && message.topic[0] == ConnectTopic) { try { string conn1 = message.actions[0].payload.components[1].ComponentID.Substring(0, message.actions[0].payload.components[1].ComponentID.IndexOf('_')); string ref1 = message.actions[0].payload.components[1].ComponentID.Substring(message.actions[0].payload.components[1].ComponentID.IndexOf('_')+1); string conn2 = message.actions[0].payload.components[2].ComponentID.Substring(0, message.actions[0].payload.components[2].ComponentID.IndexOf('_')); string ref2 = message.actions[0].payload.components[2].ComponentID.Substring(message.actions[0].payload.components[2].ComponentID.IndexOf('_') + 1); ProcessConnect(message.actions[0].payload.components[0].ComponentID, conn1, ref1, conn2, ref2); } catch (Exception ex) { GMEConsole.Warning.WriteLine("Error during processing " + ConnectTopic + " message: " + ex.Message); } } // Send AVM component update to Creo if (message.mode.SequenceEqual(new Edit.EditMode[] { Edit.EditMode.INTEREST }) && message.topic.Count >= 2 && message.topic[0] == ComponentUpdateTopic) { addon.Project.BeginTransactionInNewTerr(); try { CyPhyML.Component avmcomp = CyphyMetaLinkUtils.FindAVMComponent(addon.Project, message.topic[1], null); if (avmcomp == null) throw new Exception(String.Format("Can't find AVM component to open with id {0}.", message.topic[1])); var outmessage = CreateComponentEditMessage(avmcomp, CyphyMetaLinkUtils.FindCADModelObject(avmcomp)); if (outmessage != null) { SendInterest(null, ResyncTopic, message.topic[1]); bridgeClient.SendToMetaLinkBridge(outmessage); } else { GMEConsole.Warning.WriteLine("MetaLink: don't know about component " + message.topic[1]); } // This is a recently created component if (!syncedComponents.ContainsKey(avmcomp.Attributes.AVMID)) { SyncedComponentData syncedCompData = new SyncedComponentData() { Type = SyncedComponentData.EditType.Component }; syncedComponents.Add(avmcomp.Attributes.AVMID, syncedCompData); HighlightInTree(avmcomp, 1); } } finally { addon.Project.AbortTransaction(); } } } private void ProcessAnalysisPointMessage(string avmid, MetaLinkProtobuf.Action action) { addon.Project.BeginTransactionInNewTerr(); CyPhyML.Component component = CyphyMetaLinkUtils.GetComponentByAvmId(addon.Project, avmid); if (component == null) { GMEConsole.Error.WriteLine("Create connector: can't find component with AVMID " + avmid); addon.Project.AbortTransaction(); } else { try { CyPhyML.CADModel cadmodel = CyphyMetaLinkUtils.FindCADModelObject(component); if (cadmodel == null) { GMEConsole.Error.WriteLine("Can't find CADModel in component: " + component.ToHyperLink()); addon.Project.AbortTransaction(); return; } foreach (var datum in action.payload.datums) { CyPhyML.Point point = CyPhyMLClasses.Point.Create(component); point.Name = datum.name; point.Attributes.ID = datum.name; var connectdatum = cadmodel.Children.PointCollection.Where(p => p.ID == datum.name); CyPhyML.Point datumPoint = null; if (!connectdatum.Any()) { datumPoint = CyPhyMLClasses.Point.Create(cadmodel); datumPoint.Name = datumPoint.Attributes.DatumName = datum.name; } else { datumPoint = connectdatum.First(); } CyPhyMLClasses.PortComposition.Connect(point, datumPoint, parent: component); } } catch (Exception ex) { GMEConsole.Error.WriteLine("Error during creating analysis points: " + ex.Message); addon.Project.AbortTransaction(); return; } addon.Project.CommitTransaction(); } } private string GetStartupParams(string assemblyGUID) { CyPhyML.ComponentAssembly asm = CyphyMetaLinkUtils.GetComponentAssemblyByGuid(addon.Project, assemblyGUID); if (asm == null) return ""; var param = asm.Children.ParameterCollection.Where(p => p.Name.ToUpper() == "CADEXEPARAMS"); if (!param.Any()) return ""; return param.First().Attributes.Value; } private void ProcessResync(string id) { try { addon.Project.BeginTransactionInNewTerr(); CyPhyML.ComponentAssembly assembly = CyphyMetaLinkUtils.GetComponentAssemblyByGuid(addon.Project, id); if (assembly == null) { CyPhyML.Component comp = CyphyMetaLinkUtils.GetComponentByAvmId(addon.Project, id); if (comp == null) { GMEConsole.Error.WriteLine("Resync: Can't find design/component for id: " + id); addon.Project.AbortTransaction(); return; } else { var cadModel = CyphyMetaLinkUtils.FindCADModelObject(comp); var message = CreateComponentEditMessage(comp, cadModel); bridgeClient.SendToMetaLinkBridge(message); } } RestartAssemblySyncAtEndOfTransaction(assembly); addon.Project.AbortTransaction(); } catch (Exception ex) { GMEConsole.Error.WriteLine("Resync failed with exception: " + ex.Message); addon.Project.AbortTransaction(); } } private void StartComponentEditAction(MetaLinkProtobuf.Edit message) { // message.topic[1] is the component AVMID String avmid = message.topic[1]; StartComponentEdit(avmid); } private void StartComponentEdit(string avmid, bool transaction = true) { string componentCADDirectory = null; CyPhyML.Component component = null; if (transaction) addon.Project.BeginTransactionInNewTerr(); try { component = CyphyMetaLinkUtils.GetComponentByAvmId(addon.Project, avmid); componentCADDirectory = Path.GetDirectoryName(GetCadModelPath(component)); } finally { if (transaction) addon.Project.CommitTransaction(); } if (componentCADDirectory != null) // If this is not a newly created component { StartAssemblyExe(CreoOpenMode.OPEN_COMPONENT, avmid, false, "", workingDir: componentCADDirectory); } else { GMEConsole.Error.WriteLine("Can't find directory for CAD components. Maybe there isn't any in the model?"); LastStartedGuid = avmid; ExeStartupFailed(); } } private void CreateOrUpdateConnector(CyPhyML.Component component, List<CyPhyML.CADDatum> datumList, List<string> datumNames, List<ConnectorDatumType.AlignType> datumAligns, CyPhyML.Connector connector = null, String connectorName = null) { if (connector == null) { connector = CyPhyMLClasses.Connector.Create(component); if (connector == null) { throw new Exception("Unable to create connector."); } connector.Name = connectorName; } int i = 0; foreach (var datum in datumList) { MgaFCO copy = ((MgaModel)connector.Impl).CopyFCODisp((MgaFCO)datum.Impl, ((MgaMetaModel)connector.Impl.MetaBase).GetRoleByNameDisp(datum.Kind)); CyPhyML.CADDatum dscopy = CyPhyMLClasses.CADDatum.Cast(copy); dscopy.Name = datumNames[i]; if (dscopy.Kind == "Surface") { CyPhyMLClasses.Surface.Cast(dscopy.Impl).Attributes.Alignment = datumAligns[i] == ConnectorDatumType.AlignType.ALIGN ? CyPhyMLClasses.Surface.AttributesClass.Alignment_enum.ALIGN : CyPhyMLClasses.Surface.AttributesClass.Alignment_enum.MATE; } ((MgaModel)connector.Impl).MoveFCODisp((MgaFCO)dscopy.Impl, ((MgaMetaModel)connector.Impl.MetaBase).GetRoleByNameDisp(dscopy.Kind)); CyPhyMLClasses.PortComposition.Connect(datum, dscopy, parent: (CyPhyML.DesignElement)null); i++; } } private void ProcessAVMComponentInsert(string avmid, MetaLinkProtobuf.Action action) { try { addon.Project.BeginTransactionInNewTerr(); CyPhyML.Component component = CyphyMetaLinkUtils.GetComponentByAvmId(addon.Project, avmid); if (component == null) { GMEConsole.Error.WriteLine("Create connector: can't find component with AVMID " + avmid); addon.Project.AbortTransaction(); } else { CyPhyML.CADModel cadModel = CyphyMetaLinkUtils.FindCADModelObject(component); if (cadModel == null) { GMEConsole.Warning.WriteLine("Create connector: can't find cadmodel within component " + component.Name + " , skipping..."); addon.Project.AbortTransaction(); } else { // Insert new connectors foreach (ConnectorType actionConnector in action.payload.connectors) { CyPhyML.Connector connector = null; if (!String.IsNullOrEmpty(actionConnector.ID)) { connector = CyphyMetaLinkUtils.FindConnector(component, actionConnector.ID); if (connector == null) { GMEConsole.Warning.WriteLine("Create connector: can't find connector with id " + actionConnector.ID + " , skipping..."); continue; } } List<CyPhyML.CADDatum> datumList = new List<CyPhyML.CADDatum>(); List<string> datumNamesList = new List<string>(); List<ConnectorDatumType.AlignType> datumAlignList = new List<ConnectorDatumType.AlignType>(); bool success = true; foreach (var datum in actionConnector.Datums) { CyPhyML.CADDatum cadDatum = CyphyMetaLinkUtils.FindDatum(cadModel, datum.ID); if (cadDatum == null) { GMEConsole.Warning.WriteLine("Create connector: can't find datum with name: " + datum.ID + " , skipping..."); success = false; break; } datumList.Add(cadDatum); datumNamesList.Add(datum.DisplayName); datumAlignList.Add(datum.Alignment); } if (!success) continue; CreateOrUpdateConnector(component, datumList, datumNamesList, datumAlignList, connector, connector==null?actionConnector.DisplayName:null); } addon.Project.CommitTransaction(); } } } catch (Exception ex) { addon.Project.AbortTransaction(); GMEConsole.Error.WriteLine("AVM Component Insert, exception caught: " + ex.Message); } } private void ProcessConnect(string assemblyguid, string connectorguid1, string comprefguid1, string connectorguid2, string comprefguid2) { addon.Project.BeginTransactionInNewTerr(); CyPhyML.ComponentAssembly assembly = null; try { assembly = CyphyMetaLinkUtils.GetComponentAssemblyByGuid(addon.Project, AssemblyID); if (assembly == null) { throw new Exception(); } } catch (Exception) { GMEConsole.Error.WriteLine("ProcessConnect: Unable to find assembly for guid: " + assemblyguid); addon.Project.AbortTransaction(); return; } CyPhyML.ComponentRef ref1 = CyphyMetaLinkUtils.GetComponentRefInAssemblyById(assembly, comprefguid1); CyPhyML.Connector conn1 = CyphyMetaLinkUtils.FindConnector(ref1, connectorguid1); if (conn1 == null) { GMEConsole.Error.WriteLine("ProcessConnect: Unable to find connector (guid {0}) for assembly {1}", connectorguid1, assembly.Name); addon.Project.AbortTransaction(); return; } CyPhyML.ComponentRef ref2 = CyphyMetaLinkUtils.GetComponentRefInAssemblyById(assembly, comprefguid2); if (ref2 == null) { GMEConsole.Error.WriteLine("ProcessConnect: Unable to find component ref (guid {0}) for assembly {1}", comprefguid2, assembly.Name); addon.Project.AbortTransaction(); return; } CyPhyML.Connector conn2 = CyphyMetaLinkUtils.FindConnector(ref2, connectorguid2); if (conn2 == null) { GMEConsole.Error.WriteLine("ProcessConnect: Unable to find connector (guid {0}) for assembly {1}", connectorguid2, assembly.Name); addon.Project.AbortTransaction(); return; } try { // FIXME this will fail if ref1 and ref2 are across hierarchies CyPhyMLClasses.ConnectorComposition.Connect(conn1, conn2, ref1, ref2, parent: (CyPhyML.DesignElement)null); } catch (Exception ex) { GMEConsole.Warning.WriteLine("Unable to connect connector {0} <{1}> in {2} <{3}> to {4} <{5}> in {6} <{7}>, error is: {8}", conn1.Name, conn1.Guid, ref1.Name, ref1.Guid, conn2.Name, conn2.Guid, ref2.Name, ref2.Guid, ex.Message); addon.Project.AbortTransaction(); return; } addon.Project.CommitTransaction(); } private void ProcessEditDiscard(string assemblyId, MetaLinkProtobuf.Action action) { try { handleEvents = false; addon.Project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED); CyPhyML.ComponentAssembly assembly = CyphyMetaLinkUtils.GetComponentAssemblyByGuid(addon.Project, assemblyId); foreach (var component in action.payload.components) { CyPhyML.ComponentRef cref = CyphyMetaLinkUtils.GetComponentRefInAssemblyById(assembly, component.ComponentID); if (cref == null) { GMEConsole.Warning.WriteLine("Remove component: Can't find component ref with id: " + component.ComponentID); } else { cref.Delete(); } } RestartAssemblySyncAtEndOfTransaction(assembly); addon.Project.CommitTransaction(); handleEvents = true; } catch (Exception ex) { GMEConsole.Warning.WriteLine("Remove component: An exception happened while processing the request: " + ex.Message); addon.Project.AbortTransaction(); handleEvents = true; } } private void ProcessEditSelect(string assemblyId, MetaLinkProtobuf.Action action) { CyPhyML.ComponentRef compRef = null; if (action.payload.components.Count > 0 && String.IsNullOrEmpty(action.payload.components[0].ComponentID) == false) { addon.Project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED); try { CyPhyML.ComponentAssembly assembly = CyphyMetaLinkUtils.GetComponentAssemblyByGuid(addon.Project, assemblyId); if (assembly != null) { compRef = CyphyMetaLinkUtils.GetComponentRefInAssemblyById(assembly, action.payload.components[0].ComponentID); } } finally { addon.Project.CommitTransaction(); } } if (compRef != null) { GMEConsole.gme.ShowFCO((MgaFCO)compRef.Impl, true); } } private string GetProjectDir() { string workingDir = Path.GetTempPath(); if (addon.Project.ProjectConnStr.StartsWith("MGA=")) { workingDir = Path.GetDirectoryName(addon.Project.ProjectConnStr.Substring("MGA=".Length)); } return workingDir; } private void ProcessEditInsert(string componentAssemblyGuid, MetaLinkProtobuf.Action action) { addon.Project.BeginTransactionInNewTerr(); try { CyPhyML.ComponentAssembly topicAssembly = CyphyMetaLinkUtils.GetComponentAssemblyByGuid(addon.Project, componentAssemblyGuid); foreach (var messageComponent in action.payload.components) { CyPhyML.Component referencedComponent = CyphyMetaLinkUtils.FindAVMComponent(addon.Project, messageComponent.AvmComponentID, null); if (referencedComponent == null) { GMEConsole.Warning.WriteLine("Add component: can't find AVM component with id: " + messageComponent.AvmComponentID); } else if (topicAssembly != null) // TODO: log unknown component { //MgaFCO newcompfco = ((MgaModel)assembly.Impl).DeriveChildObject((MgaFCO)referencedComponent.Impl, ((MgaMetaModel)assembly.Impl.MetaBase).RoleByName["Component"], true); // MgaFCO newcompfco = ((MgaModel)assembly.Impl).CopyFCODisp((MgaFCO)referencedComponent.Impl, ((MgaMetaModel)assembly.Impl.MetaBase).RoleByName["Component"]); var newcomp = CyPhyMLClasses.ComponentRef.Create(topicAssembly); newcomp.Referred.Component = referencedComponent; newcomp.Attributes.InstanceGUID = newcomp.Guid.ToString("D"); if (String.IsNullOrEmpty(messageComponent.Name)) { newcomp.Name = referencedComponent.Name; } else { newcomp.Name = messageComponent.Name; } } else { GMEConsole.Warning.WriteLine("Add component: can't find design assembly with id: " + componentAssemblyGuid); } } addon.Project.CommitTransaction(); } catch (Exception e) { addon.Project.AbortTransaction(); GMEConsole.Out.WriteLine("Add component: Exception during inserting new component: {0}", System.Security.SecurityElement.Escape(e.ToString())); } } // Event handlers for addons #region MgaEventSink members public void GlobalEvent(globalevent_enum @event) { if (@event == globalevent_enum.GLOBALEVENT_CLOSE_PROJECT) { bridgeClient.CloseConnection(); // clear the queue. no more messages are coming, since the receive thread is dead Edit _; while (queuedMessages.TryDequeue(out _)) ; if (GMEConsole != null) { if (GMEConsole.gme != null) { Marshal.FinalReleaseComObject(GMEConsole.gme); } GMEConsole = null; } Marshal.FinalReleaseComObject(addon); // potential race: SyncControl.BeginInvoke was called before the receive thread was killed but after CLOSE_PROJECT SyncControl.BeginInvoke((System.Action)delegate { SyncControl.Dispose(); SyncControl = null; }); addon = null; metalinkBridge = null; } if (@event == globalevent_enum.APPEVENT_XML_IMPORT_BEGIN) { handleEvents = false; addon.EventMask = 0; } else if (@event == globalevent_enum.APPEVENT_XML_IMPORT_END) { unchecked { addon.EventMask = (uint)ComponentConfig_Addon.eventMask; } handleEvents = true; } else if (@event == globalevent_enum.APPEVENT_LIB_ATTACH_BEGIN) { addon.EventMask = 0; handleEvents = false; } else if (@event == globalevent_enum.APPEVENT_LIB_ATTACH_END) { unchecked { addon.EventMask = (uint)ComponentConfig_Addon.eventMask; } handleEvents = true; } else if (@event == globalevent_enum.GLOBALEVENT_COMMIT_TRANSACTION || @event == globalevent_enum.GLOBALEVENT_ABORT_TRANSACTION) { if (GMEConsole == null) { GMEConsole = GMEConsole.CreateFromProject(addon.Project); } RestartAssemblySync(); // n.b. MgaProject is in tx now, post a message so we can start our own SyncControl.BeginInvoke((System.Action)delegate { if (addon != null) { if ((addon.Project.ProjectStatus & 8) != 0) // in tx { } else { ProcessQueuedEditMessages(); } } }); } if (!componentEnabled) { return; } // TODO: Handle global events // MessageBox.Show(@event.ToString()); } private HashSet<CyPhyML.ComponentAssembly> assembliesToRestart = new HashSet<CyPhyML.ComponentAssembly>(); private void RestartAssemblySyncAtEndOfTransaction(CyPhyML.ComponentAssembly design) { if (design != null) { assembliesToRestart.Add(design); } } private void RestartAssemblySync() { foreach (var design in assembliesToRestart) { SyncControl.BeginInvoke((System.Action)delegate { if ((addon.Project.ProjectStatus & 8) != 0) // in tx { return; } addon.Project.BeginTransactionInNewTerr(); try { try { handleEvents = false; GenerateCADAssemblyXml(addon.Project, (MgaFCO)design.Impl, 0); SendCadAssemblyXml(design.Guid.ToString(), true); } catch (Exception ex) { AssemblyID = null; GMEConsole.Error.WriteLine("Unable to generate model. Error: " + ex.Message); } } finally { addon.Project.AbortTransaction(); handleEvents = true; } }); } assembliesToRestart.Clear(); } #endregion public bool SendInterest(Action<MetaLinkProtobuf.Edit> noticeaction, params string[] topic) { MetaLinkProtobuf.Edit message = new MetaLinkProtobuf.Edit { editMode = MetaLinkProtobuf.Edit.EditMode.INTEREST, guid = Guid.NewGuid().ToString(), //sequence = 0, }; message.origin.Add(GMEOrigin); message.topic.AddRange(topic.ToList()); if (noticeaction != null) { noticeActions.Add(message.guid, noticeaction); } string topicstr = String.Join("_", topic); // MetaLink will send us the same message multiple times if we express interest multiple times if (!interests.ContainsKey(topicstr)) { interests.Add(topicstr, 1); bridgeClient.SendToMetaLinkBridge(message); return true; } else { interests[topicstr]++; } return false; } public bool SendDisinterest(params string[] topic) { MetaLinkProtobuf.Edit message = new MetaLinkProtobuf.Edit { editMode = MetaLinkProtobuf.Edit.EditMode.DISINTEREST, guid = Guid.NewGuid().ToString(), //sequence = 0, }; message.origin.Add(GMEOrigin); message.topic.AddRange(topic.ToList()); string topicstr = String.Join("_", topic); if (interests.ContainsKey(topicstr)) { interests[topicstr]--; if (interests[topicstr] == 0) { interests.Remove(topicstr); bridgeClient.SendToMetaLinkBridge(message); return true; } } else { GMEConsole.Warning.WriteLine("Sending disinterest for topic without interest entry"); bridgeClient.SendToMetaLinkBridge(message); } return false; } public void SendManifestInterest() { SendInterest(null, ComponentManifestTopic); } public void SendComponentManifest() { MetaLinkProtobuf.Edit manifestMessage = new MetaLinkProtobuf.Edit { editMode = Edit.EditMode.POST, }; manifestMessage.topic.Add(ComponentManifestTopic); var manifestAction = new MetaLinkProtobuf.Action(); manifestMessage.actions.Add(manifestAction); manifestAction.actionMode = MetaLinkProtobuf.Action.ActionMode.INSERT; var rf = CyPhyMLClasses.RootFolder.GetRootFolder(addon.Project); Queue<CyPhyML.Components> componentsQueue = new Queue<CyPhyML.Components>(); foreach (var childComponents in rf.Children.ComponentsCollection) { componentsQueue.Enqueue(childComponents); } while (componentsQueue.Count > 0) { var components = componentsQueue.Dequeue(); manifestAction.manifest.Add(new ComponentManifestNode() { nodeMode = ComponentManifestNode.NodeMode.FOLDER, guid = components.Guid.ToString("D"), name = components.Name }); foreach (var childComponents in components.Children.ComponentsCollection) { componentsQueue.Enqueue(childComponents); } foreach (var component in components.Children.ComponentCollection) { manifestAction.manifest.Add(new ComponentManifestNode() { nodeMode = ComponentManifestNode.NodeMode.COMPONENT, guid = component.Attributes.AVMID, cyphyParentId = components.Guid.ToString("D"), name = component.Name }); } } bridgeClient.SendToMetaLinkBridge(manifestMessage); } public void SaveCadAssemblyXml(string xml, string assemblyGuid) { try { File.WriteAllText(Path.Combine(Path.GetTempPath(), "CyPhyMLPropagate_" + assemblyGuid + ".log"), xml); } catch (IOException) { } designIdToCadAssemblyXml[assemblyGuid] = xml; } public void SendCadAssemblyXml(string assemblyGuid, bool clear) { SendCadAssemblyXml(designIdToCadAssemblyXml[assemblyGuid], assemblyGuid, clear); } public void SendCadAssemblyXml(string xml, string assemblyGuid, bool clear) { MetaLinkProtobuf.Edit message = new MetaLinkProtobuf.Edit { editMode = Edit.EditMode.POST, }; message.topic.Add(CadAssemblyTopic); message.topic.Add(assemblyGuid); if (clear) { message.actions.Add(new edu.vanderbilt.isis.meta.Action() { actionMode = MetaLinkProtobuf.Action.ActionMode.CLEAR }); } var action = new MetaLinkProtobuf.Action(); message.actions.Add(action); action.actionMode = MetaLinkProtobuf.Action.ActionMode.INSERT; MetaLinkProtobuf.Alien alien = new MetaLinkProtobuf.Alien(); action.alien = alien; alien.encoded = Encoding.UTF8.GetBytes(xml); alien.encodingMode = Alien.EncodingMode.XML; CyPhyML.ComponentAssembly targetAssembly = CyphyMetaLinkUtils.GetComponentAssemblyByGuid(addon.Project, assemblyGuid); if (targetAssembly != null) { var filter = targetAssembly.Impl.Project.CreateFilter(); filter.Kind = "ComponentRef"; try { var env = new MetaLinkProtobuf.Environment { name = SearchPathStr, }; foreach (var component in CyphyMetaLinkUtils.CollectComponentsRecursive(targetAssembly)) { if (component is CyPhyML.Component) AddSearchPathToEnvironment(component as CyPhyML.Component, env); } if (env.value.Count > 0) { action.environment.Add(env); } } catch (IOException) { // XXX } } bridgeClient.SendToMetaLinkBridge(message); } private void ProcessAVMComponentUpdate(string componentId, string component_xml) { try { File.WriteAllText(Path.Combine(Path.GetTempPath(), "CyPhyMLPropagate.log"), component_xml); } catch (IOException) { } addon.Project.BeginTransactionInNewTerr(); try { CyPhyML.Component cyPhyComponent = CyphyMetaLinkUtils.GetComponentByAvmId(addon.Project, componentId); if (!cyPhyComponent.Children.CADModelCollection.Any()) throw new Exception(String.Format("No CADModel found inside component under update: {1}" + cyPhyComponent.ToHyperLink())); string absModelPath = Path.Combine(GetProjectDir(), Path.GetDirectoryName(GetCadModelPath(cyPhyComponent))); XmlDocument doc = new XmlDocument(); doc.LoadXml(component_xml); XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable); manager.AddNamespace("avm", "avm"); manager.AddNamespace("cad", "cad"); manager.AddNamespace("modelica", "modelica"); manager.AddNamespace("cyber", "cyber"); manager.AddNamespace("manufacturing", "manufacturing"); List<string> notcopied = new List<string>(); string cadmodelpath = Path.GetDirectoryName(GetCadModelPath(cyPhyComponent)); CopyResources(cadmodelpath, doc, manager, notcopied, true); avm.Component component = CyPhyComponentImporter.CyPhyComponentImporterInterpreter.DeserializeAvmComponentXml(new StringReader(doc.OuterXml)); avm.Component oldComponent = CyPhy2ComponentModel.Convert.CyPhyML2AVMComponent(cyPhyComponent); // find replace corresponding DomainModels in oldComponent, and find the corresponding CyPhy CADModels Dictionary<avm.DomainModel, CyPhyML.CADModel> avmDomainModelToCyPhyCADModel = new Dictionary<avm.DomainModel, CyPhyML.CADModel>(); var cadmodel = cyPhyComponent.Children.CADModelCollection.Where(cadModel => cadModel.Attributes.FileFormat == CyPhyMLClasses.CADModel.AttributesClass.FileFormat_enum.Creo).First(); // FIXME possible out-of-bounds access avmDomainModelToCyPhyCADModel.Add(component.DomainModel[0], cadmodel); /*foreach (var cadModel in ) { string cadModelRelativePath; if (cadModel.TryGetResourcePath(out cadModelRelativePath)) { foreach (var domainModel in component.DomainModel) { var dependency = oldComponent.ResourceDependency.Where(rd => rd.ID == domainModel.UsesResource).FirstOrDefault(); if (dependency != null) { if (CyphyMetaLinkUtils.CleanPath(dependency.Path) == CyphyMetaLinkUtils.CleanPath(cadModelRelativePath)) { avmDomainModelToCyPhyCADModel[domainModel] = cadModel; } foreach (var oldCadModel in oldComponent.DomainModel.Where(dm => dm.UsesResource == domainModel.UsesResource).ToList()) { oldComponent.DomainModel.Remove(oldCadModel); oldComponent.DomainModel.Add(domainModel); // TODO: need to hook anything up? } } else { GMEConsole.Warning.WriteLine(string.Format("Could not find ResourceDependency '{0}' for DomainModel", domainModel.UsesResource)); } } } }*/ foreach (var models in avmDomainModelToCyPhyCADModel) { var builder = new AVM2CyPhyML.CyPhyMLComponentBuilder(CyPhyMLClasses.RootFolder.GetRootFolder(models.Value.Impl.Project)); var newCADModel = builder.process((avm.cad.CADModel)models.Key, cyPhyComponent); newCADModel.Attributes.FileType = models.Value.Attributes.FileType; // META-1680 this is not set by the Component Importer. Assume it hasn't changed // wire new Datums to CyPhy model, delete old CADModel Func<MgaFCO, string> mapping = x => { if (datumKinds.Contains(x.MetaBase.Name)) { return CyPhyMLClasses.CADDatum.Cast(x).Attributes.DatumName.ToUpper() + "__ __" + x.Meta.Name; } return x.Name.ToUpper() + "__ __" + x.Meta.Name; }; Dictionary<string, MgaFCO> nameMap = ((MgaModel)newCADModel.Impl).ChildFCOs.Cast<MgaFCO>().ToDictionary(mapping, fco => fco); foreach (var connPoint in models.Value.Impl.ChildObjects.Cast<MgaFCO>() .SelectMany(child => child.PartOfConns.Cast<MgaConnPoint>().Where(cp => cp.Owner.ParentModel.ID == cyPhyComponent.ID))) { MgaFCO mappedFCO; if (nameMap.TryGetValue(mapping.Invoke(connPoint.Target), out mappedFCO)) { if (connPoint.ConnRole == "dst") { ((MgaSimpleConnection)connPoint.Owner).SetDst(connPoint.References, mappedFCO); } else { ((MgaSimpleConnection)connPoint.Owner).SetSrc(connPoint.References, mappedFCO); } } else { GMEConsole.Warning.WriteLine("Could not find connection target " + connPoint.Target.Meta.Name + " '" + connPoint.Target.Name + "'. Existing connection will be removed from model."); connPoint.Owner.DestroyObject(); } } foreach (MgaConnPoint connPoint in ((MgaFCO)models.Value.Impl).PartOfConns) { if (connPoint.ConnRole == "dst") { ((MgaSimpleConnection)connPoint.Owner).SetDst(connPoint.References, (MgaFCO)newCADModel.Impl); } else { ((MgaSimpleConnection)connPoint.Owner).SetSrc(connPoint.References, (MgaFCO)newCADModel.Impl); } } foreach (MgaPart part in ((MgaFCO)newCADModel.Impl).Parts) { string icon; int x, y; ((MgaFCO)models.Value.Impl).PartByMetaPart[part.Meta].GetGmeAttrs(out icon, out x, out y); part.SetGmeAttrs(icon, x, y); } List<string> existing = new List<string>(); // Refresh resources List<CyPhyML.Resource> removeList = new List<CyPhyML.Resource>(); foreach (CyPhyML.Resource res in cyPhyComponent.Children.ResourceCollection) { if (CyphyMetaLinkUtils.IsCADResource(res)) { if (!notcopied.Where(s => res.Attributes.Path.ToLower().EndsWith(s.ToLower())).Any()) { removeList.Add(res); } else { existing.Add(res.Attributes.Path); } } } foreach (CyPhyML.Resource res in removeList) { res.Delete(); } foreach (var res in component.ResourceDependency) { if (!existing.Where(s => s.ToLower().EndsWith(res.Name.ToLower())).Any()) { CyPhyML.Resource newRes = CyPhyMLClasses.Resource.Create(cyPhyComponent); newRes.Attributes.ID = res.ID; newRes.Name = res.Name; string cmpath = cadmodelpath.Substring(cyPhyComponent.GetDirectoryPath(ComponentLibraryManager.PathConvention.ABSOLUTE).Length); cmpath = cmpath.Trim(new char[] { '\\', '/' }); newRes.Attributes.Path = Path.Combine(cmpath, res.Name); } } CyPhyML.Resource usesRes = null; try { usesRes = cyPhyComponent.Children.ResourceCollection.Where(res => res.Attributes.ID.Equals(models.Key.UsesResource)).First(); if (!usesRes.SrcConnections.UsesResourceCollection.Any()) { CyPhyMLClasses.UsesResource.Connect(newCADModel, usesRes, null, null, cyPhyComponent); } } catch (Exception) { GMEConsole.Warning.WriteLine(String.Format("Unable to set main resource for CADModel: {0}", newCADModel.ToHyperLink())); } try { string mainResourcePath = component.ResourceDependency.Where(resdep => resdep.ID == component.DomainModel[0].UsesResource).First().Path; // Handle manufacturing files string manufacturingPath = Path.Combine(Path.GetDirectoryName(mainResourcePath), "..", "Manufacturing"); RefreshManufacturingResources(cyPhyComponent, manufacturingPath); } catch (Exception) { GMEConsole.Warning.WriteLine(String.Format("Error during adding manufacturing resources to Component: {0}", cyPhyComponent.ToHyperLink())); } GMEConsole.Out.WriteLine(String.Format("Updated CADModel definition for <a href=\"mga:{0}\">{1}</a>", newCADModel.ID, SecurityElement.Escape(newCADModel.ParentContainer.Name + "/" + newCADModel.Name))); models.Value.Delete(); } CyPhy2ComponentModel.CyPhyComponentAutoLayout.LayoutComponent(cyPhyComponent); string acmPath; if (ComponentLibraryManager.TryGetOriginalACMFilePath(cyPhyComponent, out acmPath, ComponentLibraryManager.PathConvention.ABSOLUTE)) { avm.Component newComponent = CyPhy2ComponentModel.Convert.CyPhyML2AVMComponent(cyPhyComponent); CyPhyComponentExporter.CyPhyComponentExporterInterpreter.SerializeAvmComponent(oldComponent, acmPath); } } finally { addon.Project.CommitTransaction(); } } private void CopyResources(string cadResourcesAbsPath, XmlDocument doc, XmlNamespaceManager manager, List<string> notcopied, bool update) { XPathNavigator navigator = doc.CreateNavigator(); var resourceDependencies = navigator.Select("/avm:Component/avm:ResourceDependency", manager).Cast<XPathNavigator>() // KMS: some XML contains <ResourceDependency ... xmlns="" /> which I think is an error, but we'll try to be robust .Concat(navigator.Select("/avm:Component/ResourceDependency", manager).Cast<XPathNavigator>()); foreach (XPathNavigator node in resourceDependencies) { string path = node.GetAttribute("Path", "avm"); if (String.IsNullOrWhiteSpace(path)) { path = node.GetAttribute("Path", ""); } string resname = node.GetAttribute("Name", "avm"); if (String.IsNullOrWhiteSpace(resname)) { resname = node.GetAttribute("Name", ""); } try { // Add the drive to the path is it's not present path = Path.GetFullPath(path); // Since this function is used in update as well, skip resources which are already in the // component path if (!path.StartsWith(cadResourcesAbsPath)) { Directory.CreateDirectory(cadResourcesAbsPath); if (String.IsNullOrWhiteSpace(path) == false) { // Path may be absolute or relative to ProjectDir if (Path.IsPathRooted(path) == false) { path = Path.Combine(GetProjectDir(), path); } if (File.Exists(path)) { try { File.Copy(path, Path.Combine(cadResourcesAbsPath,Path.GetFileName(path)) , true); } catch (Exception ex) { GMEConsole.Warning.WriteLine(String.Format("Error during copying resource file {0} to {1}: {2}", path, cadResourcesAbsPath, ex.Message)); } } else if (Directory.Exists(Path.GetDirectoryName(path))) { // CAD files end in .1 .2 etc. Pick the latest ones IEnumerable<string> allFiles = Directory.EnumerateFiles(Path.GetDirectoryName(path), resname + ".*"); var latestFile = allFiles.Select(Path.GetFileName) .Select(filename => new { basename = filename.Substring(0, filename.LastIndexOf('.')), version = filename.Substring(filename.LastIndexOf('.') + 1) }) .Where(p => { int val = 0; return Int32.TryParse(p.version, out val); }) .OrderByDescending(p => Int32.Parse(p.version)).ToArray(); // If there's no versioned version of the filename (e.g. XY.PRT.1, try the unversioned one e.g. XY.PRT) if (!latestFile.Any()) { allFiles = Directory.EnumerateFiles(Path.GetDirectoryName(path), resname); latestFile = allFiles.Select(Path.GetFileName).Select(filename => new { basename = filename, version = "0" }).ToArray(); } foreach (var basename in latestFile.Select(p => p.basename).Distinct()) { var latest = latestFile.Where(p => p.basename == basename).FirstOrDefault(); if (latest != null) { string latestFilename = latest.basename + ((latest.version != "0") ? ("." + latest.version) : ""); string source = Path.Combine(Path.GetDirectoryName(path), latestFilename); string dest = Path.Combine(cadResourcesAbsPath, latestFilename); try { File.Copy(source, dest, true); } catch (Exception ex) { GMEConsole.Warning.WriteLine(String.Format("Error during copying resource file {0} to {1}: {2}", source, dest, ex.Message)); } } } } else { GMEConsole.Warning.WriteLine("Could not find component directory '" + path + "'"); } } } else { notcopied.Add(resname); } } catch (PathTooLongException ex) { throw new Exception(String.Format("Error processing component resource, resource: {0}, path: {1}, message: {2}", resname, path, ex.Message)); } } } private void RefreshManufacturingResources(CyPhyML.Component component, string path) { List<CyPhyML.Resource> newResources = new List<CyPhyML.Resource>(); CyPhyML.ManufacturingModel mmodel = null; if (Directory.Exists(path)) { var allFiles = Directory.EnumerateFiles(path, "*.xml") .Select(Path.GetFileName); foreach (var res in allFiles) { if (mmodel == null) { if (!component.Children.ManufacturingModelCollection.Any()) { mmodel = CyPhyMLClasses.ManufacturingModel.Create(component); } else { mmodel = component.Children.ManufacturingModelCollection.First(); } } if (!component.Children.ResourceCollection.Where(resource => resource.Attributes.Path.Equals(Path.Combine("Manufacturing", res))).Any()) { CyPhyML.Resource newRes = CyPhyMLClasses.Resource.Create(component); newRes.Name = res; newRes.Attributes.Path = Path.Combine("Manufacturing", res); newResources.Add(newRes); CyPhyMLClasses.UsesResource.Connect(mmodel, newRes, null, null, component); } } } } private void ProcessAVMComponentCreate(string component_xml, string topic) { try { File.WriteAllText(Path.Combine(Path.GetTempPath(), "CyPhyMetaLink_ComponentCreate.xml"), component_xml); } catch (IOException) { } XmlDocument doc = new XmlDocument(); doc.LoadXml(component_xml); XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable); manager.AddNamespace("avm", "avm"); manager.AddNamespace("cad", "cad"); avm.Component component = CyPhyComponentImporter.CyPhyComponentImporterInterpreter.DeserializeAvmComponentXml(new StringReader(doc.OuterXml)); addon.Project.BeginTransactionInNewTerr(); CyPhyML.Component createdComp = null; string createdavmid = null; try { var rf = CyPhyMLClasses.RootFolder.GetRootFolder(addon.Project); CyPhyML.Components importedComponents = CyphyMetaLinkUtils.GetImportedComponentsFolder(addon.Project); if (importedComponents == null) { importedComponents = CyPhyMLClasses.Components.Create(rf); importedComponents.Name = CyPhyComponentImporter.CyPhyComponentImporterInterpreter.ImportedComponentsFolderName; } var avmidComponentMap = CyPhyComponentImporter.CyPhyComponentImporterInterpreter.getCyPhyMLComponentDictionary_ByAVMID(rf); createdComp = CyPhy2ComponentModel.Convert.AVMComponent2CyPhyML(importedComponents, component, true, GMEConsole); // Ricardo requirement: Classification must not be empy if (createdComp.Attributes.Classifications.Length == 0) createdComp.Attributes.Classifications = "Unknown"; List<string> notcopied = new List<string>(); CopyResources(Path.Combine(GetProjectDir(), createdComp.GetDirectoryPath(), "CAD\\"), doc, manager, notcopied, false); CyPhyML.CADModel cadModel = createdComp.Children.CADModelCollection.First(); // Ricardo requirement: ID must be cad.path if (cadModel.SrcConnections.UsesResourceCollection.Any() && cadModel.SrcConnections.UsesResourceCollection.First().DstEnds.Resource != null) { cadModel.SrcConnections.UsesResourceCollection.First().DstEnds.Resource.Attributes.ID = "cad.path"; } else if (cadModel.DstConnections.UsesResourceCollection.Any() && cadModel.DstConnections.UsesResourceCollection.First().DstEnds.Resource != null) { cadModel.DstConnections.UsesResourceCollection.First().DstEnds.Resource.Attributes.ID = "cad.path"; } foreach (var res in createdComp.Children.ResourceCollection) { res.Attributes.Path = Path.Combine("CAD", res.Name); } CyphyMetaLinkUtils.SetCADModelTypesFromFilenames(createdComp); RefreshManufacturingResources(createdComp, Path.Combine(createdComp.GetDirectoryPath(), "Manufacturing")); createdavmid = createdComp.Attributes.AVMID; } finally { addon.Project.CommitTransaction(); } if (createdavmid != null && topic != null) { MetaLinkProtobuf.Edit Edit_msg = new MetaLinkProtobuf.Edit(){ editMode = Edit.EditMode.POST }; Edit_msg.topic.Add(CadPassiveTopic); Edit_msg.topic.Add(topic); MetaLinkProtobuf.Action action = new MetaLinkProtobuf.Action(){ actionMode = MetaLinkProtobuf.Action.ActionMode.SWITCH, interest = new Interest() }; action.interest.topic.Add(ComponentUpdateTopic); action.interest.uid.Add(createdavmid); Edit_msg.actions.Add(action); bridgeClient.SendToMetaLinkBridge(Edit_msg); SendInterest(null, ComponentUpdateTopic, createdavmid); } } } }
// 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 gcmv = Google.Cloud.Monitoring.V3; using sys = System; namespace Google.Cloud.Monitoring.V3 { /// <summary>Resource name for the <c>Service</c> resource.</summary> public sealed partial class ServiceName : gax::IResourceName, sys::IEquatable<ServiceName> { /// <summary>The possible contents of <see cref="ServiceName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>projects/{project}/services/{service}</c>.</summary> ProjectService = 1, /// <summary>A resource name with pattern <c>organizations/{organization}/services/{service}</c>.</summary> OrganizationService = 2, /// <summary>A resource name with pattern <c>folders/{folder}/services/{service}</c>.</summary> FolderService = 3, } private static gax::PathTemplate s_projectService = new gax::PathTemplate("projects/{project}/services/{service}"); private static gax::PathTemplate s_organizationService = new gax::PathTemplate("organizations/{organization}/services/{service}"); private static gax::PathTemplate s_folderService = new gax::PathTemplate("folders/{folder}/services/{service}"); /// <summary>Creates a <see cref="ServiceName"/> 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="ServiceName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static ServiceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ServiceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ServiceName"/> with the pattern <c>projects/{project}/services/{service}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ServiceName"/> constructed from the provided ids.</returns> public static ServiceName FromProjectService(string projectId, string serviceId) => new ServiceName(ResourceNameType.ProjectService, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId))); /// <summary> /// Creates a <see cref="ServiceName"/> with the pattern <c>organizations/{organization}/services/{service}</c>. /// </summary> /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ServiceName"/> constructed from the provided ids.</returns> public static ServiceName FromOrganizationService(string organizationId, string serviceId) => new ServiceName(ResourceNameType.OrganizationService, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId))); /// <summary> /// Creates a <see cref="ServiceName"/> with the pattern <c>folders/{folder}/services/{service}</c>. /// </summary> /// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ServiceName"/> constructed from the provided ids.</returns> public static ServiceName FromFolderService(string folderId, string serviceId) => new ServiceName(ResourceNameType.FolderService, folderId: gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ServiceName"/> with pattern /// <c>projects/{project}/services/{service}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ServiceName"/> with pattern /// <c>projects/{project}/services/{service}</c>. /// </returns> public static string Format(string projectId, string serviceId) => FormatProjectService(projectId, serviceId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ServiceName"/> with pattern /// <c>projects/{project}/services/{service}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ServiceName"/> with pattern /// <c>projects/{project}/services/{service}</c>. /// </returns> public static string FormatProjectService(string projectId, string serviceId) => s_projectService.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ServiceName"/> with pattern /// <c>organizations/{organization}/services/{service}</c>. /// </summary> /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ServiceName"/> with pattern /// <c>organizations/{organization}/services/{service}</c>. /// </returns> public static string FormatOrganizationService(string organizationId, string serviceId) => s_organizationService.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ServiceName"/> with pattern /// <c>folders/{folder}/services/{service}</c>. /// </summary> /// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ServiceName"/> with pattern /// <c>folders/{folder}/services/{service}</c>. /// </returns> public static string FormatFolderService(string folderId, string serviceId) => s_folderService.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId))); /// <summary>Parses the given resource name string into a new <see cref="ServiceName"/> 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}/services/{service}</c></description></item> /// <item><description><c>organizations/{organization}/services/{service}</c></description></item> /// <item><description><c>folders/{folder}/services/{service}</c></description></item> /// </list> /// </remarks> /// <param name="serviceName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ServiceName"/> if successful.</returns> public static ServiceName Parse(string serviceName) => Parse(serviceName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ServiceName"/> 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}/services/{service}</c></description></item> /// <item><description><c>organizations/{organization}/services/{service}</c></description></item> /// <item><description><c>folders/{folder}/services/{service}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="serviceName">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="ServiceName"/> if successful.</returns> public static ServiceName Parse(string serviceName, bool allowUnparsed) => TryParse(serviceName, allowUnparsed, out ServiceName 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="ServiceName"/> 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}/services/{service}</c></description></item> /// <item><description><c>organizations/{organization}/services/{service}</c></description></item> /// <item><description><c>folders/{folder}/services/{service}</c></description></item> /// </list> /// </remarks> /// <param name="serviceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ServiceName"/>, 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 serviceName, out ServiceName result) => TryParse(serviceName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ServiceName"/> 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}/services/{service}</c></description></item> /// <item><description><c>organizations/{organization}/services/{service}</c></description></item> /// <item><description><c>folders/{folder}/services/{service}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="serviceName">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="ServiceName"/>, 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 serviceName, bool allowUnparsed, out ServiceName result) { gax::GaxPreconditions.CheckNotNull(serviceName, nameof(serviceName)); gax::TemplatedResourceName resourceName; if (s_projectService.TryParseName(serviceName, out resourceName)) { result = FromProjectService(resourceName[0], resourceName[1]); return true; } if (s_organizationService.TryParseName(serviceName, out resourceName)) { result = FromOrganizationService(resourceName[0], resourceName[1]); return true; } if (s_folderService.TryParseName(serviceName, out resourceName)) { result = FromFolderService(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(serviceName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ServiceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string folderId = null, string organizationId = null, string projectId = null, string serviceId = null) { Type = type; UnparsedResource = unparsedResourceName; FolderId = folderId; OrganizationId = organizationId; ProjectId = projectId; ServiceId = serviceId; } /// <summary> /// Constructs a new instance of a <see cref="ServiceName"/> class from the component parts of pattern /// <c>projects/{project}/services/{service}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> public ServiceName(string projectId, string serviceId) : this(ResourceNameType.ProjectService, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId))) { } /// <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>Folder</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string FolderId { get; } /// <summary> /// The <c>Organization</c> ID. May be <c>null</c>, depending on which resource name is contained by this /// instance. /// </summary> public string OrganizationId { get; } /// <summary> /// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Service</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string ServiceId { 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.ProjectService: return s_projectService.Expand(ProjectId, ServiceId); case ResourceNameType.OrganizationService: return s_organizationService.Expand(OrganizationId, ServiceId); case ResourceNameType.FolderService: return s_folderService.Expand(FolderId, ServiceId); 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 ServiceName); /// <inheritdoc/> public bool Equals(ServiceName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ServiceName a, ServiceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ServiceName a, ServiceName b) => !(a == b); } /// <summary>Resource name for the <c>ServiceLevelObjective</c> resource.</summary> public sealed partial class ServiceLevelObjectiveName : gax::IResourceName, sys::IEquatable<ServiceLevelObjectiveName> { /// <summary>The possible contents of <see cref="ServiceLevelObjectiveName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>. /// </summary> ProjectServiceServiceLevelObjective = 1, /// <summary> /// A resource name with pattern /// <c>organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>. /// </summary> OrganizationServiceServiceLevelObjective = 2, /// <summary> /// A resource name with pattern /// <c>folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>. /// </summary> FolderServiceServiceLevelObjective = 3, } private static gax::PathTemplate s_projectServiceServiceLevelObjective = new gax::PathTemplate("projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}"); private static gax::PathTemplate s_organizationServiceServiceLevelObjective = new gax::PathTemplate("organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}"); private static gax::PathTemplate s_folderServiceServiceLevelObjective = new gax::PathTemplate("folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}"); /// <summary>Creates a <see cref="ServiceLevelObjectiveName"/> 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="ServiceLevelObjectiveName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static ServiceLevelObjectiveName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ServiceLevelObjectiveName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ServiceLevelObjectiveName"/> with the pattern /// <c>projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceLevelObjectiveId"> /// The <c>ServiceLevelObjective</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// A new instance of <see cref="ServiceLevelObjectiveName"/> constructed from the provided ids. /// </returns> public static ServiceLevelObjectiveName FromProjectServiceServiceLevelObjective(string projectId, string serviceId, string serviceLevelObjectiveId) => new ServiceLevelObjectiveName(ResourceNameType.ProjectServiceServiceLevelObjective, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)), serviceLevelObjectiveId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceLevelObjectiveId, nameof(serviceLevelObjectiveId))); /// <summary> /// Creates a <see cref="ServiceLevelObjectiveName"/> with the pattern /// <c>organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>. /// </summary> /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceLevelObjectiveId"> /// The <c>ServiceLevelObjective</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// A new instance of <see cref="ServiceLevelObjectiveName"/> constructed from the provided ids. /// </returns> public static ServiceLevelObjectiveName FromOrganizationServiceServiceLevelObjective(string organizationId, string serviceId, string serviceLevelObjectiveId) => new ServiceLevelObjectiveName(ResourceNameType.OrganizationServiceServiceLevelObjective, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)), serviceLevelObjectiveId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceLevelObjectiveId, nameof(serviceLevelObjectiveId))); /// <summary> /// Creates a <see cref="ServiceLevelObjectiveName"/> with the pattern /// <c>folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>. /// </summary> /// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceLevelObjectiveId"> /// The <c>ServiceLevelObjective</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// A new instance of <see cref="ServiceLevelObjectiveName"/> constructed from the provided ids. /// </returns> public static ServiceLevelObjectiveName FromFolderServiceServiceLevelObjective(string folderId, string serviceId, string serviceLevelObjectiveId) => new ServiceLevelObjectiveName(ResourceNameType.FolderServiceServiceLevelObjective, folderId: gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)), serviceLevelObjectiveId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceLevelObjectiveId, nameof(serviceLevelObjectiveId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ServiceLevelObjectiveName"/> with pattern /// <c>projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceLevelObjectiveId"> /// The <c>ServiceLevelObjective</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="ServiceLevelObjectiveName"/> with pattern /// <c>projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>. /// </returns> public static string Format(string projectId, string serviceId, string serviceLevelObjectiveId) => FormatProjectServiceServiceLevelObjective(projectId, serviceId, serviceLevelObjectiveId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ServiceLevelObjectiveName"/> with pattern /// <c>projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceLevelObjectiveId"> /// The <c>ServiceLevelObjective</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="ServiceLevelObjectiveName"/> with pattern /// <c>projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>. /// </returns> public static string FormatProjectServiceServiceLevelObjective(string projectId, string serviceId, string serviceLevelObjectiveId) => s_projectServiceServiceLevelObjective.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceLevelObjectiveId, nameof(serviceLevelObjectiveId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ServiceLevelObjectiveName"/> with pattern /// <c>organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>. /// </summary> /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceLevelObjectiveId"> /// The <c>ServiceLevelObjective</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="ServiceLevelObjectiveName"/> with pattern /// <c>organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>. /// </returns> public static string FormatOrganizationServiceServiceLevelObjective(string organizationId, string serviceId, string serviceLevelObjectiveId) => s_organizationServiceServiceLevelObjective.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceLevelObjectiveId, nameof(serviceLevelObjectiveId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ServiceLevelObjectiveName"/> with pattern /// <c>folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>. /// </summary> /// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceLevelObjectiveId"> /// The <c>ServiceLevelObjective</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="ServiceLevelObjectiveName"/> with pattern /// <c>folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}</c>. /// </returns> public static string FormatFolderServiceServiceLevelObjective(string folderId, string serviceId, string serviceLevelObjectiveId) => s_folderServiceServiceLevelObjective.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceLevelObjectiveId, nameof(serviceLevelObjectiveId))); /// <summary> /// Parses the given resource name string into a new <see cref="ServiceLevelObjectiveName"/> 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}/services/{service}/serviceLevelObjectives/{service_level_objective}</c> /// </description> /// </item> /// <item> /// <description> /// <c>organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}</c> /// </description> /// </item> /// <item> /// <description> /// <c>folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="serviceLevelObjectiveName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ServiceLevelObjectiveName"/> if successful.</returns> public static ServiceLevelObjectiveName Parse(string serviceLevelObjectiveName) => Parse(serviceLevelObjectiveName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ServiceLevelObjectiveName"/> 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}/services/{service}/serviceLevelObjectives/{service_level_objective}</c> /// </description> /// </item> /// <item> /// <description> /// <c>organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}</c> /// </description> /// </item> /// <item> /// <description> /// <c>folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="serviceLevelObjectiveName">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="ServiceLevelObjectiveName"/> if successful.</returns> public static ServiceLevelObjectiveName Parse(string serviceLevelObjectiveName, bool allowUnparsed) => TryParse(serviceLevelObjectiveName, allowUnparsed, out ServiceLevelObjectiveName 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="ServiceLevelObjectiveName"/> 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}/services/{service}/serviceLevelObjectives/{service_level_objective}</c> /// </description> /// </item> /// <item> /// <description> /// <c>organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}</c> /// </description> /// </item> /// <item> /// <description> /// <c>folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="serviceLevelObjectiveName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ServiceLevelObjectiveName"/>, 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 serviceLevelObjectiveName, out ServiceLevelObjectiveName result) => TryParse(serviceLevelObjectiveName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ServiceLevelObjectiveName"/> 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}/services/{service}/serviceLevelObjectives/{service_level_objective}</c> /// </description> /// </item> /// <item> /// <description> /// <c>organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}</c> /// </description> /// </item> /// <item> /// <description> /// <c>folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="serviceLevelObjectiveName">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="ServiceLevelObjectiveName"/>, 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 serviceLevelObjectiveName, bool allowUnparsed, out ServiceLevelObjectiveName result) { gax::GaxPreconditions.CheckNotNull(serviceLevelObjectiveName, nameof(serviceLevelObjectiveName)); gax::TemplatedResourceName resourceName; if (s_projectServiceServiceLevelObjective.TryParseName(serviceLevelObjectiveName, out resourceName)) { result = FromProjectServiceServiceLevelObjective(resourceName[0], resourceName[1], resourceName[2]); return true; } if (s_organizationServiceServiceLevelObjective.TryParseName(serviceLevelObjectiveName, out resourceName)) { result = FromOrganizationServiceServiceLevelObjective(resourceName[0], resourceName[1], resourceName[2]); return true; } if (s_folderServiceServiceLevelObjective.TryParseName(serviceLevelObjectiveName, out resourceName)) { result = FromFolderServiceServiceLevelObjective(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(serviceLevelObjectiveName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ServiceLevelObjectiveName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string folderId = null, string organizationId = null, string projectId = null, string serviceId = null, string serviceLevelObjectiveId = null) { Type = type; UnparsedResource = unparsedResourceName; FolderId = folderId; OrganizationId = organizationId; ProjectId = projectId; ServiceId = serviceId; ServiceLevelObjectiveId = serviceLevelObjectiveId; } /// <summary> /// Constructs a new instance of a <see cref="ServiceLevelObjectiveName"/> class from the component parts of /// pattern <c>projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceLevelObjectiveId"> /// The <c>ServiceLevelObjective</c> ID. Must not be <c>null</c> or empty. /// </param> public ServiceLevelObjectiveName(string projectId, string serviceId, string serviceLevelObjectiveId) : this(ResourceNameType.ProjectServiceServiceLevelObjective, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)), serviceLevelObjectiveId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceLevelObjectiveId, nameof(serviceLevelObjectiveId))) { } /// <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>Folder</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string FolderId { get; } /// <summary> /// The <c>Organization</c> ID. May be <c>null</c>, depending on which resource name is contained by this /// instance. /// </summary> public string OrganizationId { get; } /// <summary> /// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Service</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string ServiceId { get; } /// <summary> /// The <c>ServiceLevelObjective</c> ID. May be <c>null</c>, depending on which resource name is contained by /// this instance. /// </summary> public string ServiceLevelObjectiveId { 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.ProjectServiceServiceLevelObjective: return s_projectServiceServiceLevelObjective.Expand(ProjectId, ServiceId, ServiceLevelObjectiveId); case ResourceNameType.OrganizationServiceServiceLevelObjective: return s_organizationServiceServiceLevelObjective.Expand(OrganizationId, ServiceId, ServiceLevelObjectiveId); case ResourceNameType.FolderServiceServiceLevelObjective: return s_folderServiceServiceLevelObjective.Expand(FolderId, ServiceId, ServiceLevelObjectiveId); 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 ServiceLevelObjectiveName); /// <inheritdoc/> public bool Equals(ServiceLevelObjectiveName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ServiceLevelObjectiveName a, ServiceLevelObjectiveName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ServiceLevelObjectiveName a, ServiceLevelObjectiveName b) => !(a == b); } public partial class Service { /// <summary> /// <see cref="gcmv::ServiceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcmv::ServiceName ServiceName { get => string.IsNullOrEmpty(Name) ? null : gcmv::ServiceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gax::IResourceName ResourceName { get { if (string.IsNullOrEmpty(Name)) { return null; } if (gcmv::ServiceName.TryParse(Name, out gcmv::ServiceName service)) { return service; } return gax::UnparsedResourceName.Parse(Name); } set => Name = value?.ToString() ?? ""; } } public partial class ServiceLevelObjective { /// <summary> /// <see cref="gcmv::ServiceLevelObjectiveName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcmv::ServiceLevelObjectiveName ServiceLevelObjectiveName { get => string.IsNullOrEmpty(Name) ? null : gcmv::ServiceLevelObjectiveName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gax::IResourceName ResourceName { get { if (string.IsNullOrEmpty(Name)) { return null; } if (gcmv::ServiceLevelObjectiveName.TryParse(Name, out gcmv::ServiceLevelObjectiveName serviceLevelObjective)) { return serviceLevelObjective; } return gax::UnparsedResourceName.Parse(Name); } set => Name = value?.ToString() ?? ""; } } }
namespace Nancy.Bootstrappers.Unity { using System; using System.Collections.Generic; using Diagnostics; using Microsoft.Practices.Unity; using Nancy.Configuration; using Bootstrapper; using ViewEngines; /// <summary> /// Nancy bootstrapper for the Unity container. /// </summary> public abstract class UnityNancyBootstrapper : NancyBootstrapperWithRequestContainerBase<IUnityContainer> { /// <summary> /// Gets the diagnostics for intialisation /// </summary> /// <returns>An <see cref="IDiagnostics"/> implementation</returns> protected override IDiagnostics GetDiagnostics() { return this.ApplicationContainer.Resolve<IDiagnostics>(); } /// <summary> /// Gets all registered startup tasks /// </summary> /// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="IApplicationStartup"/> instances. </returns> protected override IEnumerable<IApplicationStartup> GetApplicationStartupTasks() { return this.ApplicationContainer.ResolveAll<IApplicationStartup>(); } /// <summary> /// Registers and resolves all request startup tasks /// </summary> /// <param name="container">Container to use</param> /// <param name="requestStartupTypes">Types to register</param> /// <returns>An <see cref="System.Collections.Generic.IEnumerable{T}"/> instance containing <see cref="IRequestStartup"/> instances.</returns> protected override IEnumerable<IRequestStartup> RegisterAndGetRequestStartupTasks(IUnityContainer container, Type[] requestStartupTypes) { foreach (var requestStartupType in requestStartupTypes) { container.RegisterType( typeof(IRequestStartup), requestStartupType, requestStartupType.ToString(), new ContainerControlledLifetimeManager()); } return container.ResolveAll<IRequestStartup>(); } /// <summary> /// Gets all registered application registration tasks /// </summary> /// <returns>An <see cref="System.Collections.Generic.IEnumerable{T}"/> instance containing <see cref="IRegistrations"/> instances.</returns> protected override IEnumerable<IRegistrations> GetRegistrationTasks() { return this.ApplicationContainer.ResolveAll<IRegistrations>(); } /// <summary> /// Resolve <see cref="INancyEngine"/> /// </summary> /// <returns>An <see cref="INancyEngine"/> implementation</returns> protected override INancyEngine GetEngineInternal() { return this.ApplicationContainer.Resolve<INancyEngine>(); } /// <summary> /// Gets the <see cref="INancyEnvironmentConfigurator"/> used by th. /// </summary> /// <returns>An <see cref="INancyEnvironmentConfigurator"/> instance.</returns> protected override INancyEnvironmentConfigurator GetEnvironmentConfigurator() { return this.ApplicationContainer.Resolve<INancyEnvironmentConfigurator>(); } /// <summary> /// Get the <see cref="INancyEnvironment" /> instance. /// </summary> /// <returns>An configured <see cref="INancyEnvironment" /> instance.</returns> /// <remarks>The boostrapper must be initialised (<see cref="INancyBootstrapper.Initialise" />) prior to calling this.</remarks> public override INancyEnvironment GetEnvironment() { return this.ApplicationContainer.Resolve<INancyEnvironment>(); } /// <summary> /// Registers an <see cref="INancyEnvironment"/> instance in the container. /// </summary> /// <param name="container">The container to register into.</param> /// <param name="environment">The <see cref="INancyEnvironment"/> instance to register.</param> protected override void RegisterNancyEnvironment(IUnityContainer container, INancyEnvironment environment) { container.RegisterInstance(environment); } /// <summary> /// Gets the application level container /// </summary> /// <returns>Container instance</returns> protected override IUnityContainer GetApplicationContainer() { return new UnityContainer(); } /// <summary> /// Register the bootstrapper's implemented types into the container. /// This is necessary so a user can pass in a populated container but not have /// to take the responsibility of registering things like <see cref="INancyModuleCatalog"/> manually. /// </summary> /// <param name="applicationContainer">Application container to register into</param> protected override void RegisterBootstrapperTypes(IUnityContainer applicationContainer) { // This is here to add the EnumerableExtension, even though someone // used an external IUnityContainer (not created by this bootstrapper). // It's probably not the best place for it, but it's called right after // GetApplicationContainer in NancyBootstrapperBase. applicationContainer.AddNewExtension<EnumerableExtension>(); applicationContainer.RegisterInstance<INancyModuleCatalog>(this, new ContainerControlledLifetimeManager()); } /// <summary> /// Register the default implementations of internally used types into the container as singletons /// </summary> /// <param name="container">Container to register into</param> /// <param name="typeRegistrations">Type registrations to register</param> protected override void RegisterTypes(IUnityContainer container, IEnumerable<TypeRegistration> typeRegistrations) { foreach (var typeRegistration in typeRegistrations) { switch (typeRegistration.Lifetime) { case Lifetime.Transient: container.RegisterType( typeRegistration.RegistrationType, typeRegistration.ImplementationType, new TransientLifetimeManager()); break; case Lifetime.Singleton: container.RegisterType( typeRegistration.RegistrationType, typeRegistration.ImplementationType, new ContainerControlledLifetimeManager()); break; case Lifetime.PerRequest: throw new InvalidOperationException("Unable to directly register a per request lifetime."); default: throw new ArgumentOutOfRangeException(); } } // Added this in here because Unity doesn't seem to support // resolving using the greediest resolvable constructor container.RegisterType<IFileSystemReader, DefaultFileSystemReader>(new ContainerControlledLifetimeManager()); } /// <summary> /// Register the various collections into the container as singletons to later be resolved /// by IEnumerable{Type} constructor dependencies. /// </summary> /// <param name="container">Container to register into</param> /// <param name="collectionTypeRegistrations">Collection type registrations to register</param> protected override void RegisterCollectionTypes(IUnityContainer container, IEnumerable<CollectionTypeRegistration> collectionTypeRegistrations) { foreach (var collectionTypeRegistration in collectionTypeRegistrations) { foreach (var implementationType in collectionTypeRegistration.ImplementationTypes) { switch (collectionTypeRegistration.Lifetime) { case Lifetime.Transient: container.RegisterType( collectionTypeRegistration.RegistrationType, implementationType, implementationType.ToString(), new TransientLifetimeManager()); break; case Lifetime.Singleton: container.RegisterType( collectionTypeRegistration.RegistrationType, implementationType, implementationType.ToString(), new ContainerControlledLifetimeManager()); break; case Lifetime.PerRequest: throw new InvalidOperationException("Unable to directly register a per request lifetime."); default: throw new ArgumentOutOfRangeException(); } } } } /// <summary> /// Register the given instances into the container /// </summary> /// <param name="container">Container to register into</param> /// <param name="instanceRegistrations">Instance registration types</param> protected override void RegisterInstances(IUnityContainer container, IEnumerable<InstanceRegistration> instanceRegistrations) { foreach (var instanceRegistration in instanceRegistrations) { container.RegisterInstance( instanceRegistration.RegistrationType, instanceRegistration.Implementation, new ContainerControlledLifetimeManager()); } } /// <summary> /// Creates a per request child/nested container /// </summary> /// <param name="context">Current context</param> /// <returns>Request container instance</returns> protected override IUnityContainer CreateRequestContainer(NancyContext context) { return this.ApplicationContainer.CreateChildContainer(); } /// <summary> /// Register the given module types into the request container /// </summary> /// <param name="container">Container to register into</param> /// <param name="moduleRegistrationTypes">An <see cref="INancyModule"/> types</param> protected override void RegisterRequestContainerModules(IUnityContainer container, IEnumerable<ModuleRegistration> moduleRegistrationTypes) { foreach (var moduleRegistrationType in moduleRegistrationTypes) { container.RegisterType( typeof(INancyModule), moduleRegistrationType.ModuleType, moduleRegistrationType.ModuleType.FullName, new ContainerControlledLifetimeManager()); } } /// <summary> /// Retrieve all module instances from the container /// </summary> /// <param name="container">Container to use</param> /// <returns>Collection of An <see cref="INancyModule"/> instances</returns> protected override IEnumerable<INancyModule> GetAllModules(IUnityContainer container) { return container.ResolveAll<INancyModule>(); } /// <summary> /// Retreive a specific module instance from the container /// </summary> /// <param name="container">Container to use</param> /// <param name="moduleType">Type of the module</param> /// <returns>An <see cref="INancyModule"/> instance</returns> protected override INancyModule GetModule(IUnityContainer container, Type moduleType) { container.RegisterType(typeof(INancyModule), moduleType, new ContainerControlledLifetimeManager()); return container.Resolve<INancyModule>(); } } }
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2019 Hotcakes Commerce, LLC // // 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.Net.Mail; using System.Text; using Hotcakes.Commerce.Utilities; using Hotcakes.CommerceDTO.v1.Catalog; using Hotcakes.Web.Logging; namespace Hotcakes.Commerce.Catalog { /// <summary> /// This is the primary object that is used to manage all aspects of product inventory /// </summary> /// <remarks>The REST API equivalent is ProductInventoryyDTO.</remarks> [Serializable] public class ProductInventory { public ProductInventory() { Bvin = string.Empty; StoreId = 0; LastUpdated = DateTime.UtcNow; ProductBvin = string.Empty; VariantId = string.Empty; QuantityOnHand = 0; QuantityReserved = 0; LowStockPoint = 0; OutOfStockPoint = 0; } /// <summary> /// This is the unique ID or primary key of the product inventory record. /// </summary> public string Bvin { get; set; } /// <summary> /// This is the ID of the Hotcakes store. Typically, this is 1, except in multi-tenant environments. /// </summary> public long StoreId { get; set; } /// <summary> /// The last updated date is used for auditing purposes to know when the product inventory was last updated. /// </summary> public DateTime LastUpdated { get; set; } /// <summary> /// The unique ID or Bvin of the product that this inventory relates to. /// </summary> public string ProductBvin { get; set; } /// <summary> /// When populated, the variant ID specifies that this record relates to a specific variant of the product. /// </summary> public string VariantId { get; set; } /// <summary> /// The total physical count of items on hand. /// </summary> public int QuantityOnHand { get; set; } /// <summary> /// Count of items in stock but reserved for carts or orders. /// </summary> public int QuantityReserved { get; set; } /// <summary> /// Determines when a product has hit a point to where it is considered to be low on stock. /// </summary> public int LowStockPoint { get; set; } /// <summary> /// The value that signifies that the the product should be considered out of stock. /// </summary> public int OutOfStockPoint { get; set; } /// <summary> /// Calculates the number of products currently available to sale based on inventory levels and settings. /// </summary> public int QuantityAvailableForSale { get { var result = QuantityOnHand - OutOfStockPoint - QuantityReserved; return result; } } /// <summary> /// Use this method to send an email to the merchant about the low stock level. /// </summary> /// <param name="State">This parameter is not used. Pass null to it.</param> /// <param name="app">An active instance of HotcakesApplication, used to access store settings.</param> /// <remarks>This method is currently not called in the application.</remarks> public static void EmailLowStockReport(object State, HotcakesApplication app) { var context = app.CurrentRequestContext; if (context == null) return; if ( !EmailLowStockReport(context.CurrentStore.Settings.MailServer.EmailForGeneral, context.CurrentStore.Settings.FriendlyName, app)) { EventLog.LogEvent("Low Stock Report", "Low Stock Report Failed", EventLogSeverity.Error); } } /// <summary> /// Use this method to send an email to the merchant about the low stock level. /// </summary> /// <param name="recipientEmail">String - the email address where to send the low stock report to</param> /// <param name="storeName">String - the name of the store to use for the email template</param> /// <param name="app">An active instance of HotcakesApplication, used to access store settings.</param> /// <returns>If true, the email was sent successfully using the given parameters.</returns> public static bool EmailLowStockReport(string recipientEmail, string storeName, HotcakesApplication app) { var result = false; try { var fromAddress = string.Empty; fromAddress = recipientEmail; var m = new MailMessage(fromAddress, recipientEmail); m.IsBodyHtml = false; m.Subject = "Low Stock Report From " + storeName; var sb = new StringBuilder(); sb.AppendLine("The following are low in stock or out of stock:"); sb.Append(Environment.NewLine); var inventories = app.CatalogServices.ProductInventories.FindAllLowStock(); if (inventories.Count < 1) { sb.Append("No out of stock items found."); } else { foreach (var item in inventories) { var product = app.CatalogServices.Products.Find(item.ProductBvin); if (product != null) { sb.Append(WebAppSettings.InventoryLowReportLinePrefix); sb.Append(product.Sku); sb.Append(", "); sb.Append(product.ProductName); sb.Append(", "); sb.Append(item.QuantityOnHand); sb.AppendLine(" "); } } } m.Body = sb.ToString(); result = MailServices.SendMail(m, app.CurrentStore); } catch (Exception ex) { EventLog.LogEvent(ex); result = false; } return result; } #region DTO /// <summary> /// Allows you to convert the current product inventory object to the DTO equivalent for use with the REST API /// </summary> /// <returns>A new instance of ProductInventoryDTO</returns> public ProductInventoryDTO ToDto() { var dto = new ProductInventoryDTO(); dto.Bvin = Bvin; dto.LastUpdated = LastUpdated; dto.LowStockPoint = LowStockPoint; dto.ProductBvin = ProductBvin; dto.QuantityOnHand = QuantityOnHand; dto.QuantityReserved = QuantityReserved; dto.OutOfStockPoint = OutOfStockPoint; dto.VariantId = VariantId; return dto; } /// <summary> /// Allows you to populate the current product inventory object using a ProductInventoryDTO instance /// </summary> /// <param name="dto">An instance of the product inventory from the REST API</param> public void FromDto(ProductInventoryDTO dto) { if (dto == null) return; Bvin = dto.Bvin; LastUpdated = dto.LastUpdated; LowStockPoint = dto.LowStockPoint; ProductBvin = dto.ProductBvin; QuantityOnHand = dto.QuantityOnHand; QuantityReserved = dto.QuantityReserved; OutOfStockPoint = dto.OutOfStockPoint; VariantId = dto.VariantId; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // // Description: // Class that serializes and deserializes Templates. // using System; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Collections; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; using MS.Utility; #if !PBTCOMPILER using System.Windows.Data; using System.Windows.Controls; using System.Windows.Documents; #endif #if PBTCOMPILER namespace MS.Internal.Markup #else namespace System.Windows.Markup #endif { /// <summary> /// Class that knows how to serialize and deserialize Template objects /// </summary> internal class XamlTemplateSerializer : XamlSerializer { #if PBTCOMPILER #region Construction /// <summary> /// Constructor for XamlTemplateSerializer /// </summary> public XamlTemplateSerializer() : base() { } internal XamlTemplateSerializer(ParserHooks parserHooks) : base() { _parserHooks = parserHooks; } private ParserHooks _parserHooks = null; #endregion Construction /// <summary> /// Convert from Xaml read by a token reader into baml being written /// out by a record writer. The context gives mapping information. /// </summary> internal override void ConvertXamlToBaml ( XamlReaderHelper tokenReader, ParserContext context, XamlNode xamlNode, BamlRecordWriter bamlWriter) { TemplateXamlParser templateParser = new TemplateXamlParser(tokenReader, context); templateParser.ParserHooks = _parserHooks; templateParser.BamlRecordWriter = bamlWriter; // Process the xamlNode that is passed in so that the <Template> element is written to baml templateParser.WriteElementStart((XamlElementStartNode)xamlNode); // Parse the entire Template section now, writing everything out directly to BAML. templateParser.Parse(); } #else /// <summary> /// If the Template represented by a group of baml records is stored in a dictionary, this /// method will extract the key used for this dictionary from the passed /// collection of baml records. For ControlTemplate, this is the styleTargetType. /// For DataTemplate, this is the DataTemplateKey containing the DataType. /// </summary> internal override object GetDictionaryKey(BamlRecord startRecord, ParserContext parserContext) { object key = null; int numberOfElements = 0; BamlRecord record = startRecord; short ownerTypeId = 0; while (record != null) { if (record.RecordType == BamlRecordType.ElementStart) { BamlElementStartRecord elementStart = record as BamlElementStartRecord; if (++numberOfElements == 1) { // save the type ID of the first element (i.e. <ControlTemplate>) ownerTypeId = elementStart.TypeId; } else { // We didn't find the key before a reading the // VisualTree nodes of the template break; } } else if (record.RecordType == BamlRecordType.Property && numberOfElements == 1) { // look for the TargetType property on the <ControlTemplate> element // or the DataType property on the <DataTemplate> element BamlPropertyRecord propertyRecord = record as BamlPropertyRecord; short attributeOwnerTypeId; string attributeName; BamlAttributeUsage attributeUsage; parserContext.MapTable.GetAttributeInfoFromId(propertyRecord.AttributeId, out attributeOwnerTypeId, out attributeName, out attributeUsage); if (attributeOwnerTypeId == ownerTypeId) { if (attributeName == TargetTypePropertyName) { key = parserContext.XamlTypeMapper.GetDictionaryKey(propertyRecord.Value, parserContext); } else if (attributeName == DataTypePropertyName) { object dataType = parserContext.XamlTypeMapper.GetDictionaryKey(propertyRecord.Value, parserContext); Exception ex = TemplateKey.ValidateDataType(dataType, null); if (ex != null) { ThrowException(SRID.TemplateBadDictionaryKey, parserContext.LineNumber, parserContext.LinePosition, ex); } key = new DataTemplateKey(dataType); } } } else if (record.RecordType == BamlRecordType.PropertyComplexStart || record.RecordType == BamlRecordType.PropertyIListStart || record.RecordType == BamlRecordType.ElementEnd) { // We didn't find the targetType before a complex property like // FrameworkTemplate.VisualTree or the </ControlTemplate> tag or // TableTemplate.Tree or the </TableTemplate> tag break; } record = record.Next; } if (key == null) { ThrowException(SRID.StyleNoDictionaryKey, parserContext.LineNumber, parserContext.LinePosition, null); } return key; } // Helper to insert line and position numbers into message, if they are present void ThrowException( string id, int lineNumber, int linePosition, Exception innerException) { string message = SR.Get(id); XamlParseException parseException; // Throw the appropriate execption. If we have line numbers, then we are // parsing a xaml file, so throw a xaml exception. Otherwise were are // parsing a baml file. if (lineNumber > 0) { message += " "; message += SR.Get(SRID.ParserLineAndOffset, lineNumber.ToString(CultureInfo.CurrentUICulture), linePosition.ToString(CultureInfo.CurrentUICulture)); parseException = new XamlParseException(message, lineNumber, linePosition); } else { parseException = new XamlParseException(message); } throw parseException; } #endif // !PBTCOMPILER #region Data // Constants used for emitting specific properties and attributes for a Style internal const string ControlTemplateTagName = "ControlTemplate"; internal const string DataTemplateTagName = "DataTemplate"; internal const string HierarchicalDataTemplateTagName = "HierarchicalDataTemplate"; internal const string ItemsPanelTemplateTagName = "ItemsPanelTemplate"; internal const string TargetTypePropertyName = "TargetType"; internal const string DataTypePropertyName = "DataType"; internal const string TriggersPropertyName = "Triggers"; internal const string ResourcesPropertyName = "Resources"; internal const string SettersPropertyName = "Setters"; internal const string ItemsSourcePropertyName = "ItemsSource"; internal const string ItemTemplatePropertyName = "ItemTemplate"; internal const string ItemTemplateSelectorPropertyName = "ItemTemplateSelector"; internal const string ItemContainerStylePropertyName = "ItemContainerStyle"; internal const string ItemContainerStyleSelectorPropertyName = "ItemContainerStyleSelector"; internal const string ItemStringFormatPropertyName = "ItemStringFormat"; internal const string ItemBindingGroupPropertyName = "ItemBindingGroup"; internal const string AlternationCountPropertyName = "AlternationCount"; internal const string ControlTemplateTriggersFullPropertyName = ControlTemplateTagName + "." + TriggersPropertyName; internal const string ControlTemplateResourcesFullPropertyName = ControlTemplateTagName + "." + ResourcesPropertyName; internal const string DataTemplateTriggersFullPropertyName = DataTemplateTagName + "." + TriggersPropertyName; internal const string DataTemplateResourcesFullPropertyName = DataTemplateTagName + "." + ResourcesPropertyName; internal const string HierarchicalDataTemplateTriggersFullPropertyName = HierarchicalDataTemplateTagName + "." + TriggersPropertyName; internal const string HierarchicalDataTemplateItemsSourceFullPropertyName = HierarchicalDataTemplateTagName + "." + ItemsSourcePropertyName; internal const string HierarchicalDataTemplateItemTemplateFullPropertyName = HierarchicalDataTemplateTagName + "." + ItemTemplatePropertyName; internal const string HierarchicalDataTemplateItemTemplateSelectorFullPropertyName = HierarchicalDataTemplateTagName + "." + ItemTemplateSelectorPropertyName; internal const string HierarchicalDataTemplateItemContainerStyleFullPropertyName = HierarchicalDataTemplateTagName + "." + ItemContainerStylePropertyName; internal const string HierarchicalDataTemplateItemContainerStyleSelectorFullPropertyName = HierarchicalDataTemplateTagName + "." + ItemContainerStyleSelectorPropertyName; internal const string HierarchicalDataTemplateItemStringFormatFullPropertyName = HierarchicalDataTemplateTagName + "." + ItemStringFormatPropertyName; internal const string HierarchicalDataTemplateItemBindingGroupFullPropertyName = HierarchicalDataTemplateTagName + "." + ItemBindingGroupPropertyName; internal const string HierarchicalDataTemplateAlternationCountFullPropertyName = HierarchicalDataTemplateTagName + "." + AlternationCountPropertyName; internal const string PropertyTriggerPropertyName = "Property"; internal const string PropertyTriggerValuePropertyName = "Value"; internal const string PropertyTriggerSourceName = "SourceName"; internal const string PropertyTriggerEnterActions = "EnterActions"; internal const string PropertyTriggerExitActions = "ExitActions"; internal const string DataTriggerBindingPropertyName = "Binding"; internal const string EventTriggerEventName = "RoutedEvent"; internal const string EventTriggerSourceName = "SourceName"; internal const string EventTriggerActions = "Actions"; internal const string MultiPropertyTriggerConditionsPropertyName = "Conditions"; internal const string SetterTagName = "Setter"; internal const string SetterPropertyAttributeName = "Property"; internal const string SetterValueAttributeName = "Value"; internal const string SetterTargetAttributeName = "TargetName"; internal const string SetterEventAttributeName = "Event"; internal const string SetterHandlerAttributeName = "Handler"; #if HANDLEDEVENTSTOO internal const string SetterHandledEventsTooAttributeName = "HandledEventsToo"; #endif #endregion Data } }
using System; using System.IO; using System.Linq; using System.Text; using System.Collections; using System.Collections.Generic; using System.Reflection; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace KoKu.JsonApi { [AttributeUsage(AttributeTargets.Class)] public class Type : Attribute { public readonly string Value; public Type(string value) { this.Value = value; } } [AttributeUsage(AttributeTargets.Property)] public class Included : Attribute {} [AttributeUsage(AttributeTargets.Property)] public class Ignore : Attribute {} public class Serializer { private static List<object> fromObjectData(JsonWriter writer, object value) { var props = value.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); // get type writer.WritePropertyName("type"); var type = ((Type)value.GetType().GetCustomAttribute(typeof(Type))).Value; writer.WriteValue(type); // get id var id = value.GetType().GetProperty("Id"); writer.WritePropertyName("id"); writer.WriteValue(id.GetValue(value, null)); var filteredProps = props.Where(x => x != id && !x.GetCustomAttributes(true).Any(y => y as Ignore != null)); // get all attributes var relatedObjects = new List<PropertyInfo>(); writer.WritePropertyName("attributes"); writer.WriteStartObject(); foreach (var prop in filteredProps) { var propValue = prop.GetValue(value, null); if (propValue == null) { continue; } if (propValue as String == null && propValue as IEnumerable != null) { relatedObjects.Add(prop); continue; } writer.WritePropertyName(prop.Name); writer.WriteValue(propValue); } writer.WriteEndObject(); // get all relationships var includedObjects = new List<object>(); if (relatedObjects.Count > 0) { writer.WritePropertyName("relationships"); writer.WriteStartObject(); foreach (var prop in relatedObjects) { var propValue = prop.GetValue(value, null); if (propValue == null) { continue; } var propEnumerable = (IEnumerable)propValue; bool included = prop.GetCustomAttributes(true).Any(x => x as Included != null); writer.WritePropertyName(prop.Name); writer.WriteStartObject(); writer.WritePropertyName("data"); writer.WriteStartArray(); foreach (var item in propEnumerable) { if (included) { includedObjects.Add(item); } writer.WriteStartObject(); // get type writer.WritePropertyName("type"); var itemType = ((Type)item.GetType().GetCustomAttribute(typeof(Type))).Value; writer.WriteValue(itemType); // get id var itemId = item.GetType().GetProperty("Id"); writer.WritePropertyName("id"); writer.WriteValue(itemId.GetValue(item, null)); writer.WriteEndObject(); } writer.WriteEndArray(); writer.WriteEndObject(); } writer.WriteEndObject(); } return includedObjects; } public static string fromObject(List<object> value, bool deepInclude = false) { var includedObjects = new List<object>(); var includedObjectsBack = new List<object>(); var sb = new StringBuilder(); var sw = new StringWriter(sb); using (JsonWriter writer = new JsonTextWriter(sw)) { writer.Formatting = Formatting.Indented; // TODO: add camelCase writer.WriteStartObject(); // write data part writer.WritePropertyName("data"); writer.WriteStartArray(); foreach (var item in value) { writer.WriteStartObject(); includedObjects.AddRange(fromObjectData(writer, item)); writer.WriteEndObject(); } writer.WriteEndArray(); if (includedObjects.Count > 0) { writer.WritePropertyName("included"); writer.WriteStartArray(); var currentIncludedObjects = includedObjects; var nextIncludedObjects = includedObjectsBack; do { foreach (var item in currentIncludedObjects) { writer.WriteStartObject(); if (deepInclude) { nextIncludedObjects.AddRange(fromObjectData(writer, item)); } else { fromObjectData(writer, item); } writer.WriteEndObject(); } // swap references var tmp = currentIncludedObjects; currentIncludedObjects = nextIncludedObjects; nextIncludedObjects = tmp; } while (currentIncludedObjects.Count > 0); writer.WriteEndArray(); } writer.WriteEndObject(); } return sb.ToString(); } } public class Deserializer { private static IEnumerable<System.Type> GetTypesWith<TAttribute>(bool inherit) where TAttribute: System.Attribute { return from a in AppDomain.CurrentDomain.GetAssemblies() from t in a.GetTypes() where t.IsDefined(typeof(TAttribute), inherit) select t; } private static object ConvertList(List<object> value, System.Type type) { var containedType = type.GenericTypeArguments.First(); var list = (IList) Activator.CreateInstance(type); foreach (var v in value) { list.Add(Convert.ChangeType(v, containedType)); } return list; } private static List<object> toObjectData(JToken token, JEnumerable<JObject> included) { var list = new List<object>(); var ignoreCase = BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance; // TODO: add deCamelCase var types = GetTypesWith<Type>(true); foreach (var data in token["data"].Children<JObject>()) { var itemType = (string)data["type"]; var type = types.First(x => ((Type)x.GetCustomAttribute(typeof(Type))).Value == itemType); var item = Activator.CreateInstance(type); list.Add(item); // set id type.GetProperty("id", ignoreCase).SetValue(item, Convert.ChangeType(data["id"], type.GetProperty("id", ignoreCase).PropertyType), null); var ndata = data; // there is probably a better way todo this if (included.Any(x => (string)x["type"] == (string)data["type"] && (string)x["id"] == (string)data["id"])) { // get data from included ndata = included.First(x => (string)x["type"] == (string)data["type"] && (string)x["id"] == (string)data["id"]); } // set attributes if (ndata["attributes"] as JObject != null) { foreach (var attr in ((JObject)ndata["attributes"]).Properties()) { type.GetProperty(attr.Name, ignoreCase).SetValue(item, Convert.ChangeType(attr.Value, type.GetProperty(attr.Name, ignoreCase).PropertyType), null); } } // set relationships if (ndata["relationships"] as JObject != null) { foreach (var rela in ((JObject)ndata["relationships"]).Properties()) { // will this work ? // just hopes it's a ?????<T> container type.GetProperty(rela.Name, ignoreCase).SetValue(item, ConvertList(toObjectData(rela.Value, included), type.GetProperty(rela.Name, ignoreCase).PropertyType), null); } } } return list; } public static List<object> toObject(string json) { JToken token = JObject.Parse(json); var included = token["included"].Children<JObject>(); return toObjectData(token, included); } } }
/// <summary> /// Xcode PBX support library. This is from the Unity open source. /// https://bitbucket.org/Unity-Technologies/xcodeapi/overview /// </summary> /// /// The MIT License (MIT) /// Copyright (c) 2014 Unity Technologies /// /// 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 !UNITY_5 namespace GooglePlayGames.xcode { using System.Collections.Generic; using System.Collections; using System.Text.RegularExpressions; using System.IO; using System.Linq; using System; internal class PBXObject { public string guid; protected PBXElementDict m_Properties = new PBXElementDict(); internal void SetPropertiesWhenSerializing(PBXElementDict props) { m_Properties = props; } internal PBXElementDict GetPropertiesWhenSerializing() { return m_Properties; } // returns null if it does not exist protected string GetPropertyString(string name) { var prop = m_Properties[name]; if (prop == null) return null; return prop.AsString(); } protected void SetPropertyString(string name, string value) { if (value == null) m_Properties.Remove(name); else m_Properties.SetString(name, value); } protected List<string> GetPropertyList(string name) { var prop = m_Properties[name]; if (prop == null) return null; var list = new List<string>(); foreach (var el in prop.AsArray().values) list.Add(el.AsString()); return list; } protected void SetPropertyList(string name, List<string> value) { if (value == null) m_Properties.Remove(name); else { var array = m_Properties.CreateArray(name); foreach (string val in value) array.AddString(val); } } private static PropertyCommentChecker checkerData = new PropertyCommentChecker(); internal virtual PropertyCommentChecker checker { get { return checkerData; } } internal virtual bool shouldCompact { get { return false; } } public virtual void UpdateProps() {} // Updates the props from cached variables public virtual void UpdateVars() {} // Updates the cached variables from underlying props } internal class PBXBuildFile : PBXObject { public string fileRef; public string compileFlags; public bool weak; private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "fileRef/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } internal override bool shouldCompact { get { return true; } } public static PBXBuildFile CreateFromFile(string fileRefGUID, bool weak, string compileFlags) { PBXBuildFile buildFile = new PBXBuildFile(); buildFile.guid = PBXGUID.Generate(); buildFile.SetPropertyString("isa", "PBXBuildFile"); buildFile.fileRef = fileRefGUID; buildFile.compileFlags = compileFlags; buildFile.weak = weak; return buildFile; } PBXElementDict GetSettingsDictOptional() { if (m_Properties.Contains("settings")) return m_Properties["settings"].AsDict(); return null; } PBXElementDict GetSettingsDict() { if (m_Properties.Contains("settings")) return m_Properties["settings"].AsDict(); else return m_Properties.CreateDict("settings"); } public override void UpdateProps() { SetPropertyString("fileRef", fileRef); if (compileFlags != null && compileFlags != "") { GetSettingsDict().SetString("COMPILER_FLAGS", compileFlags); } else { var dict = GetSettingsDictOptional(); if (dict != null) dict.Remove("COMPILER_FLAGS"); } if (weak) { var dict = GetSettingsDict(); PBXElementArray attrs = null; if (dict.Contains("ATTRIBUTES")) attrs = dict["ATTRIBUTES"].AsArray(); else attrs = dict.CreateArray("ATTRIBUTES"); bool exists = false; foreach (var value in attrs.values) { if (value is PBXElementString && value.AsString() == "Weak") exists = true; } if (!exists) attrs.AddString("Weak"); } else { var dict = GetSettingsDictOptional(); if (dict != null && dict.Contains("ATTRIBUTES")) { var attrs = dict["ATTRIBUTES"].AsArray(); attrs.values.RemoveAll(el => (el is PBXElementString && el.AsString() == "Weak")); if (attrs.values.Count == 0) dict.Remove("ATTRIBUTES"); if (dict.values.Count == 0) m_Properties.Remove("settings"); } } } public override void UpdateVars() { fileRef = GetPropertyString("fileRef"); compileFlags = null; weak = false; if (m_Properties.Contains("settings")) { var dict = m_Properties["settings"].AsDict(); if (dict.Contains("COMPILER_FLAGS")) compileFlags = dict["COMPILER_FLAGS"].AsString(); if (dict.Contains("ATTRIBUTES")) { var attrs = dict["ATTRIBUTES"].AsArray(); foreach (var value in attrs.values) { if (value is PBXElementString && value.AsString() == "Weak") weak = true; } } } } } internal class PBXFileReference : PBXObject { string m_Path = null; string m_ExplicitFileType = null; string m_LastKnownFileType = null; public string path { get { return m_Path; } set { m_ExplicitFileType = null; m_LastKnownFileType = null; m_Path = value; } } public string name; public PBXSourceTree tree; internal override bool shouldCompact { get { return true; } } public static PBXFileReference CreateFromFile(string path, string projectFileName, PBXSourceTree tree) { string guid = PBXGUID.Generate(); PBXFileReference fileRef = new PBXFileReference(); fileRef.SetPropertyString("isa", "PBXFileReference"); fileRef.guid = guid; fileRef.path = path; fileRef.name = projectFileName; fileRef.tree = tree; return fileRef; } public override void UpdateProps() { string ext = null; if (m_ExplicitFileType != null) SetPropertyString("explicitFileType", m_ExplicitFileType); else if (m_LastKnownFileType != null) SetPropertyString("lastKnownFileType", m_LastKnownFileType); else { if (name != null) ext = Path.GetExtension(name); else if (m_Path != null) ext = Path.GetExtension(m_Path); if (ext != null) { if (FileTypeUtils.IsFileTypeExplicit(ext)) SetPropertyString("explicitFileType", FileTypeUtils.GetTypeName(ext)); else SetPropertyString("lastKnownFileType", FileTypeUtils.GetTypeName(ext)); } } if (m_Path == name) SetPropertyString("name", null); else SetPropertyString("name", name); if (m_Path == null) SetPropertyString("path", ""); else SetPropertyString("path", m_Path); SetPropertyString("sourceTree", FileTypeUtils.SourceTreeDesc(tree)); } public override void UpdateVars() { name = GetPropertyString("name"); m_Path = GetPropertyString("path"); if (name == null) name = m_Path; if (m_Path == null) m_Path = ""; tree = FileTypeUtils.ParseSourceTree(GetPropertyString("sourceTree")); m_ExplicitFileType = GetPropertyString("explicitFileType"); m_LastKnownFileType = GetPropertyString("lastKnownFileType"); } } class GUIDList : IEnumerable<string> { private List<string> m_List = new List<string>(); public GUIDList() {} public GUIDList(List<string> data) { m_List = data; } public static implicit operator List<string>(GUIDList list) { return list.m_List; } public static implicit operator GUIDList(List<string> data) { return new GUIDList(data); } public void AddGUID(string guid) { m_List.Add(guid); } public void RemoveGUID(string guid) { m_List.RemoveAll(x => x == guid); } public bool Contains(string guid) { return m_List.Contains(guid); } public int Count { get { return m_List.Count; } } public void Clear() { m_List.Clear(); } IEnumerator<string> IEnumerable<string>.GetEnumerator() { return m_List.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return m_List.GetEnumerator(); } } internal class XCConfigurationList : PBXObject { public GUIDList buildConfigs; private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "buildConfigurations/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public static XCConfigurationList Create() { var res = new XCConfigurationList(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "XCConfigurationList"); res.buildConfigs = new GUIDList(); res.SetPropertyString("defaultConfigurationIsVisible", "0"); return res; } public override void UpdateProps() { SetPropertyList("buildConfigurations", buildConfigs); } public override void UpdateVars() { buildConfigs = GetPropertyList("buildConfigurations"); } } internal class PBXGroup : PBXObject { public GUIDList children; public PBXSourceTree tree; public string name, path; private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "children/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } // name must not contain '/' public static PBXGroup Create(string name, string path, PBXSourceTree tree) { if (name.Contains("/")) throw new Exception("Group name must not contain '/'"); PBXGroup gr = new PBXGroup(); gr.guid = PBXGUID.Generate(); gr.SetPropertyString("isa", "PBXGroup"); gr.name = name; gr.path = path; gr.tree = PBXSourceTree.Group; gr.children = new GUIDList(); return gr; } public static PBXGroup CreateRelative(string name) { return Create(name, name, PBXSourceTree.Group); } public override void UpdateProps() { // The name property is set only if it is different from the path property SetPropertyList("children", children); if (name == path) SetPropertyString("name", null); else SetPropertyString("name", name); if (path == "") SetPropertyString("path", null); else SetPropertyString("path", path); SetPropertyString("sourceTree", FileTypeUtils.SourceTreeDesc(tree)); } public override void UpdateVars() { children = GetPropertyList("children"); path = GetPropertyString("path"); name = GetPropertyString("name"); if (name == null) name = path; if (path == null) path = ""; tree = FileTypeUtils.ParseSourceTree(GetPropertyString("sourceTree")); } } internal class PBXVariantGroup : PBXGroup { } internal class PBXNativeTarget : PBXObject { public GUIDList phases; public string buildConfigList; // guid public string name; public GUIDList dependencies; private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "buildPhases/*", "buildRules/*", "dependencies/*", "productReference/*", "buildConfigurationList/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public static PBXNativeTarget Create(string name, string productRef, string productType, string buildConfigList) { var res = new PBXNativeTarget(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXNativeTarget"); res.buildConfigList = buildConfigList; res.phases = new GUIDList(); res.SetPropertyList("buildRules", new List<string>()); res.dependencies = new GUIDList(); res.name = name; res.SetPropertyString("productName", name); res.SetPropertyString("productReference", productRef); res.SetPropertyString("productType", productType); return res; } public override void UpdateProps() { SetPropertyString("buildConfigurationList", buildConfigList); SetPropertyString("name", name); SetPropertyList("buildPhases", phases); SetPropertyList("dependencies", dependencies); } public override void UpdateVars() { buildConfigList = GetPropertyString("buildConfigurationList"); name = GetPropertyString("name"); phases = GetPropertyList("buildPhases"); dependencies = GetPropertyList("dependencies"); } } internal class FileGUIDListBase : PBXObject { public GUIDList files; private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "files/*", }); internal override PropertyCommentChecker checker { get { return checkerData; } } public override void UpdateProps() { SetPropertyList("files", files); } public override void UpdateVars() { files = GetPropertyList("files"); } } internal class PBXSourcesBuildPhase : FileGUIDListBase { public static PBXSourcesBuildPhase Create() { var res = new PBXSourcesBuildPhase(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXSourcesBuildPhase"); res.SetPropertyString("buildActionMask", "2147483647"); res.files = new List<string>(); res.SetPropertyString("runOnlyForDeploymentPostprocessing", "0"); return res; } } internal class PBXFrameworksBuildPhase : FileGUIDListBase { public static PBXFrameworksBuildPhase Create() { var res = new PBXFrameworksBuildPhase(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXFrameworksBuildPhase"); res.SetPropertyString("buildActionMask", "2147483647"); res.files = new List<string>(); res.SetPropertyString("runOnlyForDeploymentPostprocessing", "0"); return res; } } internal class PBXResourcesBuildPhase : FileGUIDListBase { public static PBXResourcesBuildPhase Create() { var res = new PBXResourcesBuildPhase(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXResourcesBuildPhase"); res.SetPropertyString("buildActionMask", "2147483647"); res.files = new List<string>(); res.SetPropertyString("runOnlyForDeploymentPostprocessing", "0"); return res; } } internal class PBXCopyFilesBuildPhase : FileGUIDListBase { private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "files/*", }); internal override PropertyCommentChecker checker { get { return checkerData; } } public string name; // name may be null public static PBXCopyFilesBuildPhase Create(string name, string subfolderSpec) { var res = new PBXCopyFilesBuildPhase(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXCopyFilesBuildPhase"); res.SetPropertyString("buildActionMask", "2147483647"); res.SetPropertyString("dstPath", ""); res.SetPropertyString("dstSubfolderSpec", subfolderSpec); res.files = new List<string>(); res.SetPropertyString("runOnlyForDeploymentPostprocessing", "0"); res.name = name; return res; } public override void UpdateProps() { SetPropertyList("files", files); SetPropertyString("name", name); } public override void UpdateVars() { files = GetPropertyList("files"); name = GetPropertyString("name"); } } internal class PBXShellScriptBuildPhase : PBXObject { public GUIDList files; private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "files/*", }); internal override PropertyCommentChecker checker { get { return checkerData; } } public override void UpdateProps() { SetPropertyList("files", files); } public override void UpdateVars() { files = GetPropertyList("files"); } } internal class BuildConfigEntry { public string name; public List<string> val = new List<string>(); public static string ExtractValue(string src) { return PBXStream.UnquoteString(src.Trim().TrimEnd(',')); } public void AddValue(string value) { if (!val.Contains(value)) val.Add(value); } public void RemoveValue(string value) { val.RemoveAll(v => v == value); } public static BuildConfigEntry FromNameValue(string name, string value) { BuildConfigEntry ret = new BuildConfigEntry(); ret.name = name; ret.AddValue(value); return ret; } } internal class XCBuildConfiguration : PBXObject { protected SortedDictionary<string, BuildConfigEntry> entries = new SortedDictionary<string, BuildConfigEntry>(); public string name { get { return GetPropertyString("name"); } } // Note that QuoteStringIfNeeded does its own escaping. Double-escaping with quotes is // required to please Xcode that does not handle paths with spaces if they are not // enclosed in quotes. static string EscapeWithQuotesIfNeeded(string name, string value) { if (name != "LIBRARY_SEARCH_PATHS") return value; if (!value.Contains(" ")) return value; if (value.First() == '\"' && value.Last() == '\"') return value; return "\"" + value + "\""; } public void SetProperty(string name, string value) { entries[name] = BuildConfigEntry.FromNameValue(name, EscapeWithQuotesIfNeeded(name, value)); } public void AddProperty(string name, string value) { if (entries.ContainsKey(name)) entries[name].AddValue(EscapeWithQuotesIfNeeded(name, value)); else SetProperty(name, value); } public void RemoveProperty(string name) { if (entries.ContainsKey(name)) entries.Remove(name); } public void RemovePropertyValue(string name, string value) { if (entries.ContainsKey(name)) entries[name].RemoveValue(EscapeWithQuotesIfNeeded(name, value)); } // name should be either release or debug public static XCBuildConfiguration Create(string name) { var res = new XCBuildConfiguration(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "XCBuildConfiguration"); res.SetPropertyString("name", name); return res; } public override void UpdateProps() { var dict = m_Properties.CreateDict("buildSettings"); foreach (var kv in entries) { if (kv.Value.val.Count == 0) continue; else if (kv.Value.val.Count == 1) dict.SetString(kv.Key, kv.Value.val[0]); else // kv.Value.val.Count > 1 { var array = dict.CreateArray(kv.Key); foreach (var value in kv.Value.val) array.AddString(value); } } } public override void UpdateVars() { entries = new SortedDictionary<string, BuildConfigEntry>(); if (m_Properties.Contains("buildSettings")) { var dict = m_Properties["buildSettings"].AsDict(); foreach (var key in dict.values.Keys) { var value = dict[key]; if (value is PBXElementString) { if (entries.ContainsKey(key)) entries[key].val.Add(value.AsString()); else entries.Add(key, BuildConfigEntry.FromNameValue(key, value.AsString())); } else if (value is PBXElementArray) { foreach (var pvalue in value.AsArray().values) { if (pvalue is PBXElementString) { if (entries.ContainsKey(key)) entries[key].val.Add(pvalue.AsString()); else entries.Add(key, BuildConfigEntry.FromNameValue(key, pvalue.AsString())); } } } } } } } internal class PBXContainerItemProxy : PBXObject { private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "containerPortal/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public static PBXContainerItemProxy Create(string containerRef, string proxyType, string remoteGlobalGUID, string remoteInfo) { var res = new PBXContainerItemProxy(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXContainerItemProxy"); res.SetPropertyString("containerPortal", containerRef); // guid res.SetPropertyString("proxyType", proxyType); res.SetPropertyString("remoteGlobalIDString", remoteGlobalGUID); // guid res.SetPropertyString("remoteInfo", remoteInfo); return res; } } internal class PBXReferenceProxy : PBXObject { private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "remoteRef/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public string path { get { return GetPropertyString("path"); } } public static PBXReferenceProxy Create(string path, string fileType, string remoteRef, string sourceTree) { var res = new PBXReferenceProxy(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXReferenceProxy"); res.SetPropertyString("path", path); res.SetPropertyString("fileType", fileType); res.SetPropertyString("remoteRef", remoteRef); res.SetPropertyString("sourceTree", sourceTree); return res; } } internal class PBXTargetDependency : PBXObject { private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "target/*", "targetProxy/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public static PBXTargetDependency Create(string target, string targetProxy) { var res = new PBXTargetDependency(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXTargetDependency"); res.SetPropertyString("target", target); res.SetPropertyString("targetProxy", targetProxy); return res; } } internal class ProjectReference { public string group; // guid public string projectRef; // guid public static ProjectReference Create(string group, string projectRef) { var res = new ProjectReference(); res.group = group; res.projectRef = projectRef; return res; } } internal class PBXProjectObject : PBXObject { private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "buildConfigurationList/*", "mainGroup/*", "projectReferences/*/ProductGroup/*", "projectReferences/*/ProjectRef/*", "targets/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public List<ProjectReference> projectReferences = new List<ProjectReference>(); public string mainGroup { get { return GetPropertyString("mainGroup"); } } public List<string> targets { get { return GetPropertyList("targets"); } } public string buildConfigList; public void AddReference(string productGroup, string projectRef) { projectReferences.Add(ProjectReference.Create(productGroup, projectRef)); } public override void UpdateProps() { m_Properties.values.Remove("projectReferences"); if (projectReferences.Count > 0) { var array = m_Properties.CreateArray("projectReferences"); foreach (var value in projectReferences) { var dict = array.AddDict(); dict.SetString("ProductGroup", value.group); dict.SetString("ProjectRef", value.projectRef); } }; SetPropertyString("buildConfigurationList", buildConfigList); } public override void UpdateVars() { projectReferences = new List<ProjectReference>(); if (m_Properties.Contains("projectReferences")) { var el = m_Properties["projectReferences"].AsArray(); foreach (var value in el.values) { PBXElementDict dict = value.AsDict(); if (dict.Contains("ProductGroup") && dict.Contains("ProjectRef")) { string group = dict["ProductGroup"].AsString(); string projectRef = dict["ProjectRef"].AsString(); projectReferences.Add(ProjectReference.Create(group, projectRef)); } } } buildConfigList = GetPropertyString("buildConfigurationList"); } } } #endif
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Management.Automation; using System.Threading; using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell.Commands { /// <summary> /// This cmdlet waits for job to complete. /// </summary> [Cmdlet(VerbsLifecycle.Wait, "Job", DefaultParameterSetName = JobCmdletBase.SessionIdParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113422")] [OutputType(typeof(Job))] public class WaitJobCommand : JobCmdletBase, IDisposable { #region Parameters /// <summary> /// Specifies the Jobs objects which need to be /// removed. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = RemoveJobCommand.JobParameterSet)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public Job[] Job { get; set; } /// <summary> /// Complete the cmdlet when any of the job is completed, instead of waiting for all of them to be completed. /// </summary> [Parameter] public SwitchParameter Any { get; set; } /// <summary> /// If timeout is specified, the cmdlet will only wait for this number of seconds. /// Value of -1 means never timeout. /// </summary> [Parameter] [Alias("TimeoutSec")] [ValidateRangeAttribute(-1, Int32.MaxValue)] public int Timeout { get { return _timeoutInSeconds; } set { _timeoutInSeconds = value; } } private int _timeoutInSeconds = -1; // -1: infinite, this default is to wait for as long as it takes. /// <summary> /// Forces the cmdlet to wait for Finished states (Completed, Failed, Stopped) instead of /// persistent states, which also include Suspended and Disconnected. /// </summary> [Parameter] public SwitchParameter Force { get; set; } /// <summary> /// </summary> public override string[] Command { get; set; } #endregion Parameters #region Coordinating how different events (timeout, stopprocessing, job finished, job blocked) affect what happens in EndProcessing private readonly object _endProcessingActionLock = new object(); private Action _endProcessingAction; private readonly ManualResetEventSlim _endProcessingActionIsReady = new ManualResetEventSlim(false); private void SetEndProcessingAction(Action endProcessingAction) { Dbg.Assert(endProcessingAction != null, "Caller should verify endProcessingAction != null"); lock (_endProcessingActionLock) { if (_endProcessingAction == null) { Dbg.Assert(!_endProcessingActionIsReady.IsSet, "This line should execute only once"); _endProcessingAction = endProcessingAction; _endProcessingActionIsReady.Set(); } } } private void InvokeEndProcessingAction() { _endProcessingActionIsReady.Wait(); Action endProcessingAction; lock (_endProcessingActionLock) { endProcessingAction = _endProcessingAction; } // Invoke action outside lock. if (endProcessingAction != null) { endProcessingAction(); } } private void CleanUpEndProcessing() { _endProcessingActionIsReady.Dispose(); } #endregion #region Support for triggering EndProcessing when jobs are finished or blocked private readonly HashSet<Job> _finishedJobs = new HashSet<Job>(); private readonly HashSet<Job> _blockedJobs = new HashSet<Job>(); private readonly List<Job> _jobsToWaitFor = new List<Job>(); private readonly object _jobTrackingLock = new object(); private void HandleJobStateChangedEvent(object source, JobStateEventArgs eventArgs) { Dbg.Assert(source is Job, "Caller should verify source is Job"); Dbg.Assert(eventArgs != null, "Caller should verify eventArgs != null"); var job = (Job)source; lock (_jobTrackingLock) { Dbg.Assert(_blockedJobs.All(j => !_finishedJobs.Contains(j)), "Job cannot be in *both* _blockedJobs and _finishedJobs"); if (eventArgs.JobStateInfo.State == JobState.Blocked) { _blockedJobs.Add(job); } else { _blockedJobs.Remove(job); } // Treat jobs in Disconnected state as finished jobs since the user // will have to reconnect the job before more information can be // obtained. // Suspended jobs require a Resume-Job call. Both of these states are persistent // without user interaction. // Wait should wait until a job is in a persistent state, OR if the force parameter // is specified, until the job is in a finished state, which is a subset of // persistent states. if (!Force && job.IsPersistentState(eventArgs.JobStateInfo.State) || (Force && job.IsFinishedState(eventArgs.JobStateInfo.State))) { if (!job.IsFinishedState(eventArgs.JobStateInfo.State)) { _warnNotTerminal = true; } _finishedJobs.Add(job); } else { _finishedJobs.Remove(job); } Dbg.Assert(_blockedJobs.All(j => !_finishedJobs.Contains(j)), "Job cannot be in *both* _blockedJobs and _finishedJobs"); if (this.Any.IsPresent) { if (_finishedJobs.Count > 0) { this.SetEndProcessingAction(this.EndProcessingOutputSingleFinishedJob); } else if (_blockedJobs.Count == _jobsToWaitFor.Count) { this.SetEndProcessingAction(this.EndProcessingBlockedJobsError); } } else { if (_finishedJobs.Count == _jobsToWaitFor.Count) { this.SetEndProcessingAction(this.EndProcessingOutputAllFinishedJobs); } else if (_blockedJobs.Count > 0) { this.SetEndProcessingAction(this.EndProcessingBlockedJobsError); } } } } private void AddJobsThatNeedJobChangesTracking(IEnumerable<Job> jobsToAdd) { Dbg.Assert(jobsToAdd != null, "Caller should verify jobs != null"); lock (_jobTrackingLock) { _jobsToWaitFor.AddRange(jobsToAdd); } } private void StartJobChangesTracking() { lock (_jobTrackingLock) { if (_jobsToWaitFor.Count == 0) { this.SetEndProcessingAction(this.EndProcessingDoNothing); return; } foreach (Job job in _jobsToWaitFor) { job.StateChanged += this.HandleJobStateChangedEvent; this.HandleJobStateChangedEvent(job, new JobStateEventArgs(job.JobStateInfo)); } } } private void CleanUpJobChangesTracking() { lock (_jobTrackingLock) { foreach (Job job in _jobsToWaitFor) { job.StateChanged -= this.HandleJobStateChangedEvent; } } } private List<Job> GetFinishedJobs() { List<Job> jobsToOutput; lock (_jobTrackingLock) { jobsToOutput = _jobsToWaitFor.Where(j => ((!Force && j.IsPersistentState(j.JobStateInfo.State)) || (Force && j.IsFinishedState(j.JobStateInfo.State)))).ToList(); } return jobsToOutput; } private Job GetOneBlockedJob() { lock (_jobTrackingLock) { return _jobsToWaitFor.FirstOrDefault(j => j.JobStateInfo.State == JobState.Blocked); } } #endregion #region Support for triggering EndProcessing when timing out private Timer _timer; private readonly object _timerLock = new object(); private void StartTimeoutTracking(int timeoutInSeconds) { if (timeoutInSeconds == 0) { this.SetEndProcessingAction(this.EndProcessingDoNothing); } else if (timeoutInSeconds > 0) { lock (_timerLock) { _timer = new Timer((_) => this.SetEndProcessingAction(this.EndProcessingDoNothing), null, timeoutInSeconds * 1000, System.Threading.Timeout.Infinite); } } } private void CleanUpTimeoutTracking() { lock (_timerLock) { if (_timer != null) { _timer.Dispose(); _timer = null; } } } #endregion #region Overrides /// <summary> /// Cancel the Wait-Job cmdlet. /// </summary> protected override void StopProcessing() { this.SetEndProcessingAction(this.EndProcessingDoNothing); } /// <summary> /// In this method, we initialize the timer if timeout parameter is specified. /// </summary> protected override void BeginProcessing() { this.StartTimeoutTracking(_timeoutInSeconds); } /// <summary> /// This method just collects the Jobs which will be waited on in the EndProcessing method. /// </summary> protected override void ProcessRecord() { // List of jobs to wait List<Job> matches; switch (ParameterSetName) { case NameParameterSet: matches = FindJobsMatchingByName(true, false, true, false); break; case InstanceIdParameterSet: matches = FindJobsMatchingByInstanceId(true, false, true, false); break; case SessionIdParameterSet: matches = FindJobsMatchingBySessionId(true, false, true, false); break; case StateParameterSet: matches = FindJobsMatchingByState(false); break; case FilterParameterSet: matches = FindJobsMatchingByFilter(false); break; default: matches = CopyJobsToList(this.Job, false, false); break; } this.AddJobsThatNeedJobChangesTracking(matches); } /// <summary> /// Wait on the collected Jobs. /// </summary> protected override void EndProcessing() { this.StartJobChangesTracking(); this.InvokeEndProcessingAction(); if (_warnNotTerminal) { WriteWarning(RemotingErrorIdStrings.JobSuspendedDisconnectedWaitWithForce); } } private void EndProcessingOutputSingleFinishedJob() { Job finishedJob = this.GetFinishedJobs().FirstOrDefault(); if (finishedJob != null) { this.WriteObject(finishedJob); } } private void EndProcessingOutputAllFinishedJobs() { IEnumerable<Job> finishedJobs = this.GetFinishedJobs(); foreach (Job finishedJob in finishedJobs) { this.WriteObject(finishedJob); } } private void EndProcessingBlockedJobsError() { string message = RemotingErrorIdStrings.JobBlockedSoWaitJobCannotContinue; Exception exception = new ArgumentException(message); ErrorRecord errorRecord = new ErrorRecord( exception, "BlockedJobsDeadlockWithWaitJob", ErrorCategory.DeadlockDetected, this.GetOneBlockedJob()); this.ThrowTerminatingError(errorRecord); } private void EndProcessingDoNothing() { // do nothing } #endregion Overrides #region IDisposable Members /// <summary> /// Dispose all managed resources. This will suppress finalizer on the object from getting called by /// calling System.GC.SuppressFinalize(this). /// </summary> public void Dispose() { Dispose(true); // To prevent derived types with finalizers from having to re-implement System.IDisposable to call it, // unsealed types without finalizers should still call SuppressFinalize. System.GC.SuppressFinalize(this); } /// <summary> /// Release all the resources. /// </summary> /// <param name="disposing"> /// if true, release all the managed objects. /// </param> private void Dispose(bool disposing) { if (disposing) { lock (_disposableLock) { if (!_isDisposed) { _isDisposed = true; this.CleanUpTimeoutTracking(); this.CleanUpJobChangesTracking(); this.CleanUpEndProcessing(); // <- has to be last } } } } private bool _isDisposed; private readonly object _disposableLock = new object(); private bool _warnNotTerminal = false; #endregion IDisposable Members } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace Signum.Analyzer { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class ExpressionFieldAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "SF0002"; internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, "Use ExpressionFieldAttribute in non-trivial method or property", "'{0}' should reference an static field of type Expression<T> with the same signature ({1})", "Expressions", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: "A property or method can use ExpressionFieldAttribute pointing to an static fied of type Expression<T> to use it in LINQ queries"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); context.RegisterSyntaxNodeAction(AnalyzeAttributeSymbol, SyntaxKind.Attribute); } static void AnalyzeAttributeSymbol(SyntaxNodeAnalysisContext context) { try { var att = (AttributeSyntax)context.Node; var name = att.Name.ToString(); if (name != "ExpressionField") return; var member = att.FirstAncestorOrSelf<MemberDeclarationSyntax>(); var method = member as MethodDeclarationSyntax; var prop = member as PropertyDeclarationSyntax; var ident = prop?.Identifier.ToString() ?? method?.Identifier.ToString(); if (method != null) { if (method.ReturnType.ToString() == "void") { Diagnostic(context, ident, method.ReturnType.GetLocation(), "no return type"); return; } foreach (var param in method.ParameterList.Parameters) { if (param.Modifiers.Any(a => a.Kind() != SyntaxKind.ThisKeyword)) { Diagnostic(context, ident, param.Modifiers.First().GetLocation(), "complex parameter '" + param.Identifier.ToString() + "'"); return; } } } var argument = att.ArgumentList?.Arguments.Select(a => a.Expression).FirstOrDefault(); if (argument == null) return; var val = context.SemanticModel.GetConstantValue(argument); string fieldName = val.HasValue ? (val.Value as string) : null; if (fieldName == null) { Diagnostic(context, ident, argument.GetLocation(), "invalid field name"); return; } var typeSyntax = member.FirstAncestorOrSelf<TypeDeclarationSyntax>(); if (typeSyntax == null) return; var type = context.SemanticModel.GetDeclaredSymbol(typeSyntax); var fieldSymbol = type.GetMembers().OfType<IFieldSymbol>().SingleOrDefault(a => a.Name == fieldName); if (fieldSymbol == null) { Diagnostic(context, ident, att.GetLocation(), string.Format("field '{0}' not found", fieldName)); return; } var memberSymbol = context.SemanticModel.GetDeclaredSymbol(member); var expressionType = GetExpressionType(memberSymbol, context.SemanticModel); if (!expressionType.Equals(fieldSymbol.Type, SymbolEqualityComparer.IncludeNullability)) { var minimalParts = expressionType.ToMinimalDisplayString(context.SemanticModel, member.GetLocation().SourceSpan.Start); Diagnostic(context, ident, att.GetLocation(), string.Format("type of '{0}' should be '{1}'", fieldName, minimalParts)); return; } } catch (Exception e) { throw new Exception(context.SemanticModel.SyntaxTree.FilePath + "\r\n" + e.Message + "\r\n" + e.StackTrace); } } private static INamedTypeSymbol GetExpressionType(ISymbol memberSymbol, SemanticModel sm) { var parameters = memberSymbol is IMethodSymbol ? ((IMethodSymbol)memberSymbol).Parameters.Select(p => (p.Type, p.NullableAnnotation)).ToList() : new List<(ITypeSymbol, NullableAnnotation)>(); if (!memberSymbol.IsStatic) parameters.Insert(0, ((ITypeSymbol)memberSymbol.ContainingSymbol, NullableAnnotation.NotAnnotated)); var returnType = memberSymbol is IMethodSymbol mi ? (mi.ReturnType, mi.ReturnNullableAnnotation) : memberSymbol is IPropertySymbol pi ? (pi.Type, pi.NullableAnnotation) : throw new InvalidOperationException("Unexpected member"); parameters.Add(returnType); var expression = sm.Compilation.GetTypeByMetadataName("System.Linq.Expressions.Expression`1"); var func = sm.Compilation.GetTypeByMetadataName("System.Func`" + parameters.Count); var funcConstruct = func.Construct( parameters.Select(a => a.Item1).ToImmutableArray(), parameters.Select(a => a.Item2).ToImmutableArray()); return expression.Construct( ImmutableArray.Create((ITypeSymbol)funcConstruct), ImmutableArray.Create(NullableAnnotation.NotAnnotated)); } public static ExpressionSyntax GetSingleBody(SyntaxNodeAnalysisContext context, string ident, AttributeSyntax att, MemberDeclarationSyntax member) { if (member is MethodDeclarationSyntax) { var method = (MethodDeclarationSyntax)member; if (method.ExpressionBody != null) return method.ExpressionBody.Expression; return OnlyReturn(context, ident, att, method.Body.Statements); } else if (member is PropertyDeclarationSyntax) { var property = (PropertyDeclarationSyntax)member; if (property.ExpressionBody != null) return property.ExpressionBody.Expression; var getter = property.AccessorList.Accessors.SingleOrDefault(a => a.Kind() == SyntaxKind.GetAccessorDeclaration); if (getter == null) { Diagnostic(context, ident, att.GetLocation(), "no getter"); return null; } if (property.AccessorList.Accessors.Any(a => a.Kind() == SyntaxKind.SetAccessorDeclaration)) { Diagnostic(context, ident, att.GetLocation(), "setter not allowed"); return null; } if (getter.Body == null) { Diagnostic(context, ident, getter.GetLocation(), "no getter body"); return null; } return OnlyReturn(context, ident, att, getter.Body.Statements); } Diagnostic(context, ident, att.GetLocation(), "no property or method"); return null; } internal static ExpressionSyntax OnlyReturn(SyntaxNodeAnalysisContext context, string ident, AttributeSyntax att, SyntaxList<StatementSyntax> statements) { var only = statements.Only(); if (only == null) { Diagnostic(context, ident, att.GetLocation(), statements.Count + " statements"); return null; } var ret = only as ReturnStatementSyntax; if (ret == null) { Diagnostic(context, ident, only.GetLocation(), "no return"); return null; } if (ret.Expression == null) { Diagnostic(context, ident, only.GetLocation(), "no return expression"); return null; } return ret.Expression; } private static void Diagnostic(SyntaxNodeAnalysisContext context, string identifier, Location location, string error, bool fixable = false) { var properties = ImmutableDictionary<string, string>.Empty.Add("fixable", fixable.ToString()); var diagnostic = Microsoft.CodeAnalysis.Diagnostic.Create(Rule, location, properties, identifier, error); context.ReportDiagnostic(diagnostic); } } }
using RSG.Promises; using System; using System.Linq; using RSG.Exceptions; using Xunit; namespace RSG.Tests { public class PromiseTests { [Fact] public void can_resolve_simple_promise() { const int promisedValue = 5; var promise = Promise<int>.Resolved(promisedValue); var completed = 0; promise.Then(v => { Assert.Equal(promisedValue, v); ++completed; }); Assert.Equal(1, completed); } [Fact] public void can_reject_simple_promise() { var ex = new Exception(); var promise = Promise<int>.Rejected(ex); var errors = 0; promise.Catch(e => { Assert.Equal(ex, e); ++errors; }); Assert.Equal(1, errors); } [Fact] public void exception_is_thrown_for_reject_after_reject() { var promise = new Promise<int>(); promise.Reject(new Exception()); Assert.Throws<PromiseStateException>(() => promise.Reject(new Exception()) ); } [Fact] public void exception_is_thrown_for_reject_after_resolve() { var promise = new Promise<int>(); promise.Resolve(5); Assert.Throws<PromiseStateException>(() => promise.Reject(new Exception()) ); } [Fact] public void exception_is_thrown_for_resolve_after_reject() { var promise = new Promise<int>(); promise.Reject(new Exception()); Assert.Throws<PromiseStateException>(() => promise.Resolve(5)); } [Fact] public void can_resolve_promise_and_trigger_then_handler() { var promise = new Promise<int>(); var completed = 0; const int promisedValue = 15; promise.Then(v => { Assert.Equal(promisedValue, v); ++completed; }); promise.Resolve(promisedValue); Assert.Equal(1, completed); } [Fact] public void exception_is_thrown_for_resolve_after_resolve() { var promise = new Promise<int>(); promise.Resolve(5); Assert.Throws<PromiseStateException>(() => promise.Resolve(5)); } [Fact] public void can_resolve_promise_and_trigger_multiple_then_handlers_in_order() { var promise = new Promise<int>(); var completed = 0; promise.Then(v => Assert.Equal(1, ++completed)); promise.Then(v => Assert.Equal(2, ++completed)); promise.Resolve(1); Assert.Equal(2, completed); } [Fact] public void can_resolve_promise_and_trigger_then_handler_with_callback_registration_after_resolve() { var promise = new Promise<int>(); var completed = 0; const int promisedValue = -10; promise.Resolve(promisedValue); promise.Then(v => { Assert.Equal(promisedValue, v); ++completed; }); Assert.Equal(1, completed); } [Fact] public void can_reject_promise_and_trigger_error_handler() { var promise = new Promise<int>(); var ex = new Exception(); var completed = 0; promise.Catch(e => { Assert.Equal(ex, e); ++completed; }); promise.Reject(ex); Assert.Equal(1, completed); } [Fact] public void can_reject_promise_and_trigger_multiple_error_handlers_in_order() { var promise = new Promise<int>(); var ex = new Exception(); var completed = 0; promise.Catch(e => { Assert.Equal(ex, e); Assert.Equal(1, ++completed); }); promise.Catch(e => { Assert.Equal(ex, e); Assert.Equal(2, ++completed); }); promise.Reject(ex); Assert.Equal(2, completed); } [Fact] public void can_reject_promise_and_trigger_error_handler_with_registration_after_reject() { var promise = new Promise<int>(); var ex = new Exception(); promise.Reject(ex); var completed = 0; promise.Catch(e => { Assert.Equal(ex, e); ++completed; }); Assert.Equal(1, completed); } [Fact] public void error_handler_is_not_invoked_for_resolved_promised() { var promise = new Promise<int>(); promise.Catch(e => throw new Exception("This shouldn't happen")); promise.Resolve(5); } [Fact] public void then_handler_is_not_invoked_for_rejected_promise() { var promise = new Promise<int>(); promise.Then(v => throw new Exception("This shouldn't happen")); promise.Reject(new Exception("Rejection!")); } [Fact] public void chain_multiple_promises_using_all() { var promise = new Promise<string>(); var chainedPromise1 = new Promise<int>(); var chainedPromise2 = new Promise<int>(); const int chainedResult1 = 10; const int chainedResult2 = 15; var completed = 0; TestHelpers.VerifyDoesntThrowUnhandledException(() => { promise .ThenAll(i => EnumerableExt.FromItems(chainedPromise1, chainedPromise2) .Cast<IPromise<int>>()) .Then(result => { var items = result.ToArray(); Assert.Equal(2, items.Length); Assert.Equal(chainedResult1, items[0]); Assert.Equal(chainedResult2, items[1]); ++completed; }); Assert.Equal(0, completed); promise.Resolve("hello"); Assert.Equal(0, completed); chainedPromise1.Resolve(chainedResult1); Assert.Equal(0, completed); chainedPromise2.Resolve(chainedResult2); Assert.Equal(1, completed); }); } [Fact] public void chain_multiple_promises_using_all_that_are_resolved_out_of_order() { var promise = new Promise<string>(); var chainedPromise1 = new Promise<int>(); var chainedPromise2 = new Promise<int>(); const int chainedResult1 = 10; const int chainedResult2 = 15; var completed = 0; TestHelpers.VerifyDoesntThrowUnhandledException(() => { promise .ThenAll(i => EnumerableExt.FromItems(chainedPromise1, chainedPromise2) .Cast<IPromise<int>>()) .Then(result => { var items = result.ToArray(); Assert.Equal(2, items.Length); Assert.Equal(chainedResult1, items[0]); Assert.Equal(chainedResult2, items[1]); ++completed; }); Assert.Equal(0, completed); promise.Resolve("hello"); Assert.Equal(0, completed); chainedPromise2.Resolve(chainedResult2); Assert.Equal(0, completed); chainedPromise1.Resolve(chainedResult1); Assert.Equal(1, completed); }); } [Fact] public void chain_multiple_promises_using_all_and_convert_to_non_value_promise() { var promise = new Promise<string>(); var chainedPromise1 = new Promise(); var chainedPromise2 = new Promise(); var completed = 0; TestHelpers.VerifyDoesntThrowUnhandledException(() => { promise .ThenAll(i => EnumerableExt.FromItems(chainedPromise1, chainedPromise2) .Cast<IPromise>()) .Then(() => ++completed); Assert.Equal(0, completed); promise.Resolve("hello"); Assert.Equal(0, completed); chainedPromise1.Resolve(); Assert.Equal(0, completed); chainedPromise2.Resolve(); Assert.Equal(1, completed); }); } [Fact] public void combined_promise_is_resolved_when_children_are_resolved() { var promise1 = new Promise<int>(); var promise2 = new Promise<int>(); TestHelpers.VerifyDoesntThrowUnhandledException(() => { var all = Promise<int>.All(EnumerableExt.FromItems<IPromise<int>>(promise1, promise2)); var completed = 0; all.Then(v => { ++completed; var values = v.ToArray(); Assert.Equal(2, values.Length); Assert.Equal(1, values[0]); Assert.Equal(2, values[1]); }); promise1.Resolve(1); promise2.Resolve(2); Assert.Equal(1, completed); }); } [Fact] public void combined_promise_of_multiple_types_is_resolved_when_children_are_resolved() { var promise1 = new Promise<int>(); var promise2 = new Promise<bool>(); TestHelpers.VerifyDoesntThrowUnhandledException(() => { var all = PromiseHelpers.All(promise1, promise2); var completed = 0; all.Then(v => { ++completed; Assert.Equal(1, v.Item1); Assert.Equal(true, v.Item2); }); promise1.Resolve(1); promise2.Resolve(true); Assert.Equal(1, completed); }); } [Fact] public void combined_promise_of_three_types_is_resolved_when_children_are_resolved() { var promise1 = new Promise<int>(); var promise2 = new Promise<bool>(); var promise3 = new Promise<float>(); TestHelpers.VerifyDoesntThrowUnhandledException(() => { var all = PromiseHelpers.All(promise1, promise2, promise3); var completed = 0; all.Then(v => { ++completed; Assert.Equal(1, v.Item1); Assert.Equal(true, v.Item2); Assert.Equal(3.0f, v.Item3); }); promise1.Resolve(1); promise2.Resolve(true); promise3.Resolve(3.0f); Assert.Equal(1, completed); }); } [Fact] public void combined_promise_of_four_types_is_resolved_when_children_are_resolved() { var promise1 = new Promise<int>(); var promise2 = new Promise<bool>(); var promise3 = new Promise<float>(); var promise4 = new Promise<double>(); TestHelpers.VerifyDoesntThrowUnhandledException(() => { var all = PromiseHelpers.All(promise1, promise2, promise3, promise4); var completed = 0; all.Then(v => { ++completed; Assert.Equal(1, v.Item1); Assert.Equal(true, v.Item2); Assert.Equal(3.0f, v.Item3); Assert.Equal(4.0, v.Item4); }); promise1.Resolve(1); promise2.Resolve(true); promise3.Resolve(3.0f); promise4.Resolve(4.0); Assert.Equal(1, completed); }); } [Fact] public void combined_promise_is_rejected_when_first_promise_is_rejected() { var promise1 = new Promise<int>(); var promise2 = new Promise<int>(); TestHelpers.VerifyDoesntThrowUnhandledException(() => { var all = Promise<int>.All(EnumerableExt.FromItems<IPromise<int>>(promise1, promise2)); all.Then(v => throw new Exception("Shouldn't happen")); var errors = 0; all.Catch(e => ++errors); promise1.Reject(new Exception("Error!")); promise2.Resolve(2); Assert.Equal(1, errors); }); } [Fact] public void combined_promise_of_multiple_types_is_rejected_when_first_promise_is_rejected() { var promise1 = new Promise<int>(); var promise2 = new Promise<bool>(); TestHelpers.VerifyDoesntThrowUnhandledException(() => { var all = PromiseHelpers.All(promise1, promise2); all.Then(v => throw new Exception("Shouldn't happen")); var errors = 0; all.Catch(e => ++errors); promise1.Reject(new Exception("Error!")); promise2.Resolve(true); Assert.Equal(1, errors); }); } [Fact] public void combined_promise_is_rejected_when_second_promise_is_rejected() { var promise1 = new Promise<int>(); var promise2 = new Promise<int>(); TestHelpers.VerifyDoesntThrowUnhandledException(() => { var all = Promise<int>.All(EnumerableExt.FromItems<IPromise<int>>(promise1, promise2)); all.Then(v => throw new Exception("Shouldn't happen")); var errors = 0; all.Catch(e => ++errors); promise1.Resolve(2); promise2.Reject(new Exception("Error!")); Assert.Equal(1, errors); }); } [Fact] public void combined_promise_of_multiple_types_is_rejected_when_second_promise_is_rejected() { var promise1 = new Promise<int>(); var promise2 = new Promise<bool>(); TestHelpers.VerifyDoesntThrowUnhandledException(() => { var all = PromiseHelpers.All(promise1, promise2); all.Then(v => throw new Exception("Shouldn't happen")); var errors = 0; all.Catch(e => ++errors); promise1.Resolve(2); promise2.Reject(new Exception("Error!")); Assert.Equal(1, errors); }); } [Fact] public void combined_promise_is_rejected_when_both_promises_are_rejected() { var promise1 = new Promise<int>(); var promise2 = new Promise<int>(); TestHelpers.VerifyDoesntThrowUnhandledException(() => { var all = Promise<int>.All(EnumerableExt.FromItems<IPromise<int>>(promise1, promise2)); all.Then(v => throw new Exception("Shouldn't happen")); var errors = 0; all.Catch(e => { ++errors; }); promise1.Reject(new Exception("Error!")); promise2.Reject(new Exception("Error!")); Assert.Equal(1, errors); }); } [Fact] public void combined_promise_of_multiple_types_is_rejected_when_both_promises_are_rejected() { var promise1 = new Promise<int>(); var promise2 = new Promise<bool>(); TestHelpers.VerifyDoesntThrowUnhandledException(() => { var all = PromiseHelpers.All(promise1, promise2); all.Then(v => throw new Exception("Shouldn't happen")); var errors = 0; all.Catch(e => ++errors); promise1.Reject(new Exception("Error!")); promise2.Reject(new Exception("Error!")); Assert.Equal(1, errors); }); } [Fact] public void combined_promise_is_resolved_if_there_are_no_promises() { TestHelpers.VerifyDoesntThrowUnhandledException(() => { var all = Promise<int>.All(Enumerable.Empty<IPromise<int>>()); var completed = 0; all.Then(v => { ++completed; Assert.Empty(v); }); Assert.Equal(1, completed); }); } [Fact] public void combined_promise_is_resolved_when_all_promises_are_already_resolved() { var promise1 = Promise<int>.Resolved(1); var promise2 = Promise<int>.Resolved(1); TestHelpers.VerifyDoesntThrowUnhandledException(() => { var all = Promise<int>.All(EnumerableExt.FromItems(promise1, promise2)); var completed = 0; all.Then(v => { ++completed; Assert.Empty(v); }); Assert.Equal(1, completed); }); } [Fact] public void combined_promise_of_multiple_types_is_resolved_when_all_promises_are_already_resolved() { var promise1 = Promise<int>.Resolved(1); var promise2 = Promise<bool>.Resolved(true); TestHelpers.VerifyDoesntThrowUnhandledException(() => { var all = PromiseHelpers.All(promise1, promise2); var completed = 0; all.Then(v => { ++completed; Assert.Equal(1, v.Item1); Assert.Equal(true, v.Item2); }); Assert.Equal(1, completed); }); } [Fact] public void can_transform_promise_value() { var promise = new Promise<int>(); var promisedValue = 15; var completed = 0; promise .Then(v => v.ToString()) .Then(v => { Assert.Equal(promisedValue.ToString(), v); ++completed; }); promise.Resolve(promisedValue); Assert.Equal(1, completed); } [Fact] public void rejection_of_source_promise_rejects_transformed_promise() { var promise = new Promise<int>(); var ex = new Exception(); var errors = 0; promise .Then(v => v.ToString()) .Catch(e => { Assert.Equal(ex, e); ++errors; }); promise.Reject(ex); Assert.Equal(1, errors); } [Fact] public void exception_thrown_during_transform_rejects_transformed_promise() { var promise = new Promise<int>(); const int promisedValue = 15; var errors = 0; var ex = new Exception(); promise .Then(v => throw ex) .Catch(e => { Assert.Equal(ex, e); ++errors; }); promise.Resolve(promisedValue); Assert.Equal(1, errors); } [Fact] public void can_chain_promise_and_convert_type_of_value() { var promise = new Promise<int>(); var chainedPromise = new Promise<string>(); const int promisedValue = 15; const string chainedPromiseValue = "blah"; var completed = 0; promise .Then<string>(v => chainedPromise) .Then(v => { Assert.Equal(chainedPromiseValue, v); ++completed; }); promise.Resolve(promisedValue); chainedPromise.Resolve(chainedPromiseValue); Assert.Equal(1, completed); } [Fact] public void can_chain_promise_and_convert_to_non_value_promise() { var promise = new Promise<int>(); var chainedPromise = new Promise(); const int promisedValue = 15; var completed = 0; promise .Then(v => (IPromise)chainedPromise) .Then(() => ++completed); promise.Resolve(promisedValue); chainedPromise.Resolve(); Assert.Equal(1, completed); } [Fact] public void exception_thrown_in_chain_rejects_resulting_promise() { var promise = new Promise<int>(); var ex = new Exception(); var errors = 0; promise .Then(v => throw ex) .Catch(e => { Assert.Equal(ex, e); ++errors; }); promise.Resolve(15); Assert.Equal(1, errors); } [Fact] public void rejection_of_source_promise_rejects_chained_promise() { var promise = new Promise<int>(); var chainedPromise = new Promise<string>(); var ex = new Exception(); var errors = 0; promise .Then<string>(v => chainedPromise) .Catch(e => { Assert.Equal(ex, e); ++errors; }); promise.Reject(ex); Assert.Equal(1, errors); } [Fact] public void race_is_resolved_when_first_promise_is_resolved_first() { var promise1 = new Promise<int>(); var promise2 = new Promise<int>(); var resolved = 0; TestHelpers.VerifyDoesntThrowUnhandledException(() => { Promise<int> .Race(promise1, promise2) .Then(i => resolved = i); promise1.Resolve(5); Assert.Equal(5, resolved); }); } [Fact] public void race_is_resolved_when_second_promise_is_resolved_first() { var promise1 = new Promise<int>(); var promise2 = new Promise<int>(); var resolved = 0; TestHelpers.VerifyDoesntThrowUnhandledException(() => { Promise<int> .Race(promise1, promise2) .Then(i => resolved = i); promise2.Resolve(12); Assert.Equal(12, resolved); }); } [Fact] public void race_is_rejected_when_first_promise_is_rejected_first() { var promise1 = new Promise<int>(); var promise2 = new Promise<int>(); Exception ex = null; TestHelpers.VerifyDoesntThrowUnhandledException(() => { Promise<int> .Race(promise1, promise2) .Catch(e => ex = e); var expected = new Exception(); promise1.Reject(expected); Assert.Equal(expected, ex); }); } [Fact] public void race_is_rejected_when_second_promise_is_rejected_first() { var promise1 = new Promise<int>(); var promise2 = new Promise<int>(); Exception ex = null; TestHelpers.VerifyDoesntThrowUnhandledException(() => { Promise<int> .Race(promise1, promise2) .Catch(e => ex = e); var expected = new Exception(); promise2.Reject(expected); Assert.Equal(expected, ex); }); } [Fact] public void can_resolve_promise_via_resolver_function() { var promise = new Promise<int>((resolve, reject) => resolve(5)); var completed = 0; promise.Then(v => { Assert.Equal(5, v); ++completed; }); Assert.Equal(1, completed); } [Fact] public void can_reject_promise_via_reject_function() { var ex = new Exception(); var promise = new Promise<int>((resolve, reject) => { reject(ex); }); var completed = 0; promise.Catch(e => { Assert.Equal(ex, e); ++completed; }); Assert.Equal(1, completed); } [Fact] public void exception_thrown_during_resolver_rejects_promise() { var ex = new Exception(); var promise = new Promise<int>((resolve, reject) => throw ex); var completed = 0; promise.Catch(e => { Assert.Equal(ex, e); ++completed; }); Assert.Equal(1, completed); } [Fact] public void unhandled_exception_is_propagated_via_event() { var promise = new Promise<int>(); var ex = new Exception(); var eventRaised = 0; EventHandler<ExceptionEventArgs> handler = (s, e) => { Assert.Equal(ex, e.Exception); ++eventRaised; }; Promise.UnhandledException += handler; try { promise .Then(a => throw ex) .Done(); promise.Resolve(5); Assert.Equal(1, eventRaised); } finally { Promise.UnhandledException -= handler; } } [Fact] public void exception_in_done_callback_is_propagated_via_event() { var promise = new Promise<int>(); var ex = new Exception(); var eventRaised = 0; EventHandler<ExceptionEventArgs> handler = (s, e) => { Assert.Equal(ex, e.Exception); ++eventRaised; }; Promise.UnhandledException += handler; try { promise .Done(x => throw ex); promise.Resolve(5); Assert.Equal(1, eventRaised); } finally { Promise.UnhandledException -= handler; } } [Fact] public void handled_exception_is_not_propagated_via_event() { var promise = new Promise<int>(); var ex = new Exception(); var eventRaised = 0; EventHandler<ExceptionEventArgs> handler = (s, e) => ++eventRaised; Promise.UnhandledException += handler; try { promise .Then(a => throw ex) .Catch(_ => { // Catch the error. }) .Done(); promise.Resolve(5); Assert.Equal(0, eventRaised); } finally { Promise.UnhandledException -= handler; } } [Fact] public void can_handle_Done_onResolved() { var promise = new Promise<int>(); var callback = 0; const int expectedValue = 5; promise.Done(value => { Assert.Equal(expectedValue, value); ++callback; }); promise.Resolve(expectedValue); Assert.Equal(1, callback); } [Fact] public void can_handle_Done_onResolved_with_onReject() { var promise = new Promise<int>(); var callback = 0; var errorCallback = 0; const int expectedValue = 5; promise.Done( value => { Assert.Equal(expectedValue, value); ++callback; }, ex => ++errorCallback ); promise.Resolve(expectedValue); Assert.Equal(1, callback); Assert.Equal(0, errorCallback); } /*todo: * Also want a test that exception thrown during Then triggers the error handler. * How do Javascript promises work in this regard? [Fact] public void exception_during_Done_onResolved_triggers_error_hander() { var promise = new Promise<int>(); var callback = 0; var errorCallback = 0; var expectedValue = 5; var expectedException = new Exception(); promise.Done( value => { Assert.Equal(expectedValue, value); ++callback; throw expectedException; }, ex => { Assert.Equal(expectedException, ex); ++errorCallback; } ); promise.Resolve(expectedValue); Assert.Equal(1, callback); Assert.Equal(1, errorCallback); } * */ [Fact] public void exception_during_Then_onResolved_triggers_error_hander() { var promise = new Promise<int>(); var callback = 0; var errorCallback = 0; var expectedException = new Exception(); promise .Then(value => throw expectedException) .Done( () => ++callback, ex => { Assert.Equal(expectedException, ex); ++errorCallback; } ); promise.Resolve(6); Assert.Equal(0, callback); Assert.Equal(1, errorCallback); } [Fact] public void promises_have_sequential_ids() { var promise1 = new Promise<int>(); var promise2 = new Promise<int>(); Assert.Equal(promise1.Id + 1, promise2.Id); } [Fact] public void finally_is_called_after_resolve() { var promise = new Promise<int>(); var callback = 0; promise.Finally(() => ++callback); promise.Resolve(0); Assert.Equal(1, callback); } [Fact] public void finally_is_called_after_reject() { var promise = new Promise<int>(); var callback = 0; promise.Finally(() => ++callback); promise.Reject(new Exception()); Assert.Equal(1, callback); } [Fact] //tc39 public void resolved_chain_continues_after_finally() { var promise = new Promise<int>(); var callback = 0; const int expectedValue = 42; promise .Finally(() => ++callback) .Then((x) => { Assert.Equal(expectedValue, x); ++callback; }); promise.Resolve(expectedValue); Assert.Equal(2, callback); } [Fact] //tc39 public void rejected_chain_rejects_after_finally() { var promise = new Promise<int>(); var callback = 0; promise .Finally(() => ++callback) .Catch(_ => ++callback); promise.Reject(new Exception()); Assert.Equal(2, callback); } [Fact] public void rejected_chain_continues_after_ContinueWith_returning_non_value_promise() { var promise = new Promise<int>(); var callback = 0; promise.ContinueWith(() => { ++callback; return Promise.Resolved(); }) .Then(() => ++callback); promise.Reject(new Exception()); Assert.Equal(2, callback); } [Fact] public void rejected_chain_continues_after_ContinueWith_returning_value_promise() { var promise = new Promise<int>(); var callback = 0; const int expectedValue = 42; promise.ContinueWith(() => { ++callback; return Promise<int>.Resolved(expectedValue); }) .Then(x => { Assert.Equal(expectedValue, x); ++callback; }); promise.Reject(new Exception()); Assert.Equal(2, callback); } [Fact] public void can_chain_promise_generic_after_finally() { var promise = new Promise<int>(); const int expectedValue = 5; var callback = 0; promise.ContinueWith(() => { ++callback; return Promise<int>.Resolved(expectedValue); }) .Then(x => { Assert.Equal(expectedValue, x); ++callback; }); promise.Resolve(0); Assert.Equal(2, callback); } [Fact] //tc39 public void can_chain_promise_after_finally() { var promise = new Promise<int>(); var callback = 0; promise .Finally(() => ++callback) .Then(_ => ++callback); promise.Resolve(0); Assert.Equal(2, callback); } [Fact] //tc39 note: "a throw (or returning a rejected promise) in the finally callback will reject the new promise with that rejection reason." public void exception_in_finally_callback_is_caught_by_chained_catch() { //NOTE: Also tests that the new exception is passed thru promise chain var promise = new Promise<int>(); var callback = 0; var expectedException = new Exception("Expected"); promise.Finally(() => { ++callback; throw expectedException; }) .Catch(ex => { Assert.Equal(expectedException, ex); ++callback; }); promise.Reject(new Exception()); Assert.Equal(2, callback); } [Fact] public void exception_in_ContinueWith_callback_returning_non_value_promise_is_caught_by_chained_catch() { //NOTE: Also tests that the new exception is passed thru promise chain var promise = new Promise<int>(); var callback = 0; var expectedException = new Exception("Expected"); promise.ContinueWith(() => { ++callback; throw expectedException; }) .Catch(ex => { Assert.Equal(expectedException, ex); ++callback; }); promise.Reject(new Exception()); Assert.Equal(2, callback); } [Fact] public void exception_in_ContinueWith_callback_returning_value_promise_is_caught_by_chained_catch() { // NOTE: Also tests that the new exception is passed through promise chain var promise = new Promise<int>(); var callback = 0; var expectedException = new Exception("Expected"); promise.ContinueWith(new Func<IPromise<int>>(() => { ++callback; throw expectedException; })) .Catch(ex => { Assert.Equal(expectedException, ex); ++callback; }); promise.Reject(new Exception()); Assert.Equal(2, callback); } [Fact] public void exception_in_reject_callback_is_caught_by_chained_catch() { var expectedException = new Exception("Expected"); Exception actualException = null; new Promise<object>((res, rej) => rej(new Exception())) .Then( _ => Promise<object>.Resolved(null), _ => throw expectedException ) .Catch(ex => actualException = ex); Assert.Equal(expectedException, actualException); } [Fact] public void rejected_reject_callback_is_caught_by_chained_catch() { var expectedException = new Exception("Expected"); Exception actualException = null; new Promise<object>((res, rej) => rej(new Exception())) .Then( _ => Promise<object>.Resolved(null), _ => Promise<object>.Rejected(expectedException) ) .Catch(ex => actualException = ex); Assert.Equal(expectedException, actualException); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using ProcessImageDemo.Areas.HelpPage.ModelDescriptions; using ProcessImageDemo.Areas.HelpPage.Models; namespace ProcessImageDemo.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System.Linq; using ICSharpCode.NRefactory.Completion; using ICSharpCode.NRefactory.TypeSystem; using Newtonsoft.Json; using QuantConnect.CodingServices.CompletionDataFactory; namespace QuantConnect.CodingServices.Models { /// <summary> /// This guy will get his data from CodeCompletionDataFactory.CompletionData /// </summary> public class CodeCompletionResult { /// <summary> /// A unique identifier (in the context of a single response?) /// NOTE: This is required by the client code /// </summary> [JsonProperty("id")] public int Id { get; set; } /// <summary> /// The derived declaration category. /// This tells us something about how the option was declared (if it was declared at all). /// It is intended to provide a useful cue for icons to be associated with the autocomplete options. /// </summary> [JsonIgnore] // leave as ignore. The property below will be used for serialization for now (temporarily). public DeclarationCategory DeclarationCategory { get; set; } [JsonProperty("sDeclarationCategory")] public string DeclarationCategoryName { get { return DeclarationCategory.ToString().Replace('_', ' '); } } /// <summary> /// Display text to represent the code completion option in the IDE's code completion list. /// </summary> [JsonProperty("sName")] public string DisplayText { get; set; } /// <summary> /// Completion text represented by this option. /// For most options, this will be the same as the display text, but for snippets and the like, /// this will almost certainly consist of much more than is displayed in the autocomplete option list. /// </summary> [JsonProperty("sCode")] public string CompletionText { get; set; } /// <summary> /// The summary content extracted from XML documentation comments /// </summary> //[JsonProperty("sSummary")] [JsonIgnore] public string Summary { get; set; } /// <summary> /// (optional) A [more comprehensive] description of the code completion option, intended /// to be used for tooltip content. This could contain information about the return type of the member, /// the type in which the member resides, domentation about the member, or anything else... /// </summary> [JsonProperty("sDescription")] public string Description { get; set; } /// <summary> /// Attributes which are applicable only to members of types. /// </summary> [JsonProperty("memberInfo")] public CodeCompletionMemberOfTypeResult MemberInformation { get; set; } public override string ToString() { return string.Format("[{0}] {1}", DisplayText, Description); //if (MemberInformation == null) //{ // return string.Format("[{0}] {1}\r\n{2} ", // DisplayText, // DeclarationCategoryName, // Summary); //} //else //{ // return string.Format("[{0}] {1} {2} {3}\r\n{4} {5}", // DisplayText, // DeclarationCategoryName, // MemberInformation.DeclaredResultType, // MemberInformation.FullName, // Summary, // (MemberInformation.OverloadCount == 0 ? "" : " (" + MemberInformation.OverloadCount + " overloads) ")); //} } } public class CodeCompletionMemberOfTypeResult { /// <summary> /// The name of the type inside of which this member is declared. /// Applicable to members of types. /// </summary> [JsonProperty("sMemberDeclaringType")] public string DeclaringType { get; set; } /// <summary> /// The fuly-qualified name of the declared result type of this member. /// For properties and fields, it will be the declared type; for methods, it will be the declared return type. /// Applicable to members of types. /// </summary> [JsonProperty("sMemberType")] public string DeclaredResultType { get; set; } /// <summary> /// The fully-qualified name of the member. /// </summary> [JsonIgnore] //[JsonProperty("sFullName")] public string FullName { get; set; } /// <summary> /// Indicates the number of overloads which exist for the completion option. /// NOTE: This ONLY applies to C# completion options for which overloads can exist (i.e. methods), /// but in VB.NET, indexers can also be overloaded. /// </summary> //[JsonIgnore] [JsonProperty("iOverloadCount")] public int OverloadCount { get; set; } } public static class CodeCompletionResultUtility { public static CodeCompletionResult FromICompletionDataToFileCodeCompletionResult(this ICompletionData completionData) { CodeCompletionResult result = new CodeCompletionResult(); // Set Defaults result.CompletionText = completionData.CompletionText; result.DisplayText = completionData.DisplayText; result.Description = completionData.Description; //result.MemberDeclaringType = ""; //result.MemberDeclaredResultType = ""; CodeCompletionDataFactory.CompletionData cd = (CodeCompletionDataFactory.CompletionData) completionData; // Extract and capture the summary from the XML documentation for the option // We shouldn't be surprised that in many cases this will be empty. var xmlDoc = new XmlDocumentationModel(cd.Documentation); result.Summary = xmlDoc.Summary; result.DeclarationCategory = cd.DeclarationCategory; bool boringDescription = string.IsNullOrWhiteSpace(result.Description) || result.Description == result.CompletionText; // For EntityCompletionData, if the entity is an IMember, NRefactory sets the CompletionCategory's DisplayText to the name of the class (i.e. member.DeclaringTypeDefinintion.Name) //if (completionData.CompletionCategory != null) // result.MemberDeclaringType = completionData.CompletionCategory.DisplayText; // Let's see if we can reproduce... var entity = cd as CodeCompletionDataFactory.EntityCompletionData; if (entity != null) { var member = entity.Entity as IMember; if (member != null) { var memberInfo = new CodeCompletionMemberOfTypeResult(); result.MemberInformation = memberInfo; memberInfo.FullName = member.FullName; memberInfo.DeclaringType = member.DeclaringTypeDefinition.FullName; memberInfo.DeclaredResultType = member.MemberDefinition.ReturnType.FullName; memberInfo.OverloadCount = completionData.OverloadedData.Count(); if (boringDescription) { result.Description = string.Format("{0} {1} {2}\r\n{3} {4}", result.DeclarationCategoryName, memberInfo.DeclaredResultType, memberInfo.FullName, result.Summary, (memberInfo.OverloadCount == 0 ? "" : " (" + memberInfo.OverloadCount + " overloads) ")); } } else { result.Description = string.Format("{0} \r\n{1}", result.DeclarationCategoryName, result.Summary); } } var ns = cd as CodeCompletionDataFactory.NamespaceCompletionData; if (ns != null) { result.Description = string.Format("{0} {1}", result.DeclarationCategoryName, ns.Namespace.FullName); } var variable = cd as CodeCompletionDataFactory.VariableCompletionData; if (variable != null) { result.Description = string.Format("{0} {1} {2}", result.DeclarationCategoryName, variable.Variable.Type.FullName, variable.Variable.Name); } var literal = cd as CodeCompletionDataFactory.LiteralCompletionData; if (literal != null) { if (literal.Description == literal.DisplayText) result.Description = string.Format("{0} {1}", result.DeclarationCategoryName, literal.DisplayText); else result.Description = string.Format("{0} {1}\r\n{2}", result.DeclarationCategoryName, literal.DisplayText, literal.Description); } var enumMember = cd as CodeCompletionDataFactory.MemberCompletionData; if (enumMember != null) { result.Description = string.Format("{0} {1}", result.DeclarationCategoryName, enumMember.DisplayText); } var typeCompletion = cd as CodeCompletionDataFactory.TypeCompletionData; if (typeCompletion!= null) { result.Description = string.Format("{0} {1}\r\n{2}", result.DeclarationCategoryName, typeCompletion.Type.FullName, result.Summary); } var typeParameter = cd as CodeCompletionDataFactory.TypeParameterCompletionData; if (typeParameter != null) { var owner = typeParameter.TypeParameter.Owner; if (owner != null) { var ownerXmlDoc = new XmlDocumentationModel(owner.Documentation); result.Summary = ownerXmlDoc.GetTypeParameterDescription(typeParameter.TypeParameter.Name); } result.Description = string.Format("{0} {1}\r\n{2}", result.DeclarationCategoryName, typeParameter.TypeParameter.FullName, result.Summary); } result.Description = result.Description.TrimEnd('\n', '\r'); return result; } } /// <summary> /// For now, this class only extracts the content of the <code>summary</code> XML tag from XML documentation, /// but in the future, we may want to flesh it out to extract some other common XML tags, such as <code>params</code> /// and <code>returns</code>. /// </summary> class XmlDocumentationModel { private string Xml; public XmlDocumentationModel(string xml) { Xml = xml; } private readonly string SUMMARY_OPENING_TAG = "<summary>"; private readonly string SUMMARY_CLOSING_TAG = "</summary>"; public string Summary { get { if (string.IsNullOrWhiteSpace(Xml)) return ""; int startingIndex = Xml.IndexOf(SUMMARY_OPENING_TAG); if (startingIndex == -1) return ""; int endingIndex = Xml.IndexOf(SUMMARY_CLOSING_TAG); if (endingIndex == -1) return ""; int contentStart = startingIndex + SUMMARY_OPENING_TAG.Length; return Xml.Substring(contentStart, endingIndex - contentStart).Trim(); } } private readonly string TYPEPARAM_CLOSING_TAG = "</typeparam>"; public string GetTypeParameterDescription(string typeParamName) { if (string.IsNullOrWhiteSpace(Xml)) return ""; string typeParamOpeningTag = string.Format("<typeparam name=\"{0}\">", typeParamName); int startingIndex = Xml.IndexOf(typeParamOpeningTag); if (startingIndex == -1) return ""; int endingIndex = Xml.IndexOf(TYPEPARAM_CLOSING_TAG); if (endingIndex == -1) return ""; int contentStart = startingIndex + typeParamOpeningTag.Length; return Xml.Substring(contentStart, endingIndex - contentStart).Trim(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Logic { using Azure; using Management; using Rest; using Rest.Azure; using Rest.Azure.OData; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// WorkflowRunsOperations operations. /// </summary> internal partial class WorkflowRunsOperations : IServiceOperations<LogicManagementClient>, IWorkflowRunsOperations { /// <summary> /// Initializes a new instance of the WorkflowRunsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal WorkflowRunsOperations(LogicManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the LogicManagementClient /// </summary> public LogicManagementClient Client { get; private set; } /// <summary> /// Gets a list of workflow runs. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<WorkflowRun>>> ListWithHttpMessagesAsync(string resourceGroupName, string workflowName, ODataQuery<WorkflowRunFilter> odataQuery = default(ODataQuery<WorkflowRunFilter>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (workflowName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workflowName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("workflowName", workflowName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/workflows/{workflowName}/runs").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{workflowName}", System.Uri.EscapeDataString(workflowName)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<WorkflowRun>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<WorkflowRun>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a workflow run. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='runName'> /// The workflow run name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<WorkflowRun>> GetWithHttpMessagesAsync(string resourceGroupName, string workflowName, string runName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (workflowName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workflowName"); } if (runName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "runName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("workflowName", workflowName); tracingParameters.Add("runName", runName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/workflows/{workflowName}/runs/{runName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{workflowName}", System.Uri.EscapeDataString(workflowName)); _url = _url.Replace("{runName}", System.Uri.EscapeDataString(runName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<WorkflowRun>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<WorkflowRun>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Cancels a workflow run. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='runName'> /// The workflow run name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> CancelWithHttpMessagesAsync(string resourceGroupName, string workflowName, string runName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (workflowName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workflowName"); } if (runName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "runName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("workflowName", workflowName); tracingParameters.Add("runName", runName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Cancel", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/workflows/{workflowName}/runs/{runName}/cancel").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{workflowName}", System.Uri.EscapeDataString(workflowName)); _url = _url.Replace("{runName}", System.Uri.EscapeDataString(runName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a list of workflow runs. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<WorkflowRun>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<WorkflowRun>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<WorkflowRun>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using AVFoundation; using CoreGraphics; using Foundation; using ObjCRuntime; using OpenGLES; using UIKit; // @interface RTCMediaSource : NSObject [BaseType (typeof(NSObject))] [DisableDefaultCtor] interface RTCMediaSource { // @property (readonly, assign, nonatomic) RTCSourceState state; [Export ("state", ArgumentSemantic.Assign)] RTCSourceState State { get; } } // @interface RTCVideoSource : RTCMediaSource [BaseType (typeof(RTCMediaSource))] [DisableDefaultCtor] interface RTCVideoSource { } // @interface RTCAVFoundationVideoSource : RTCVideoSource [BaseType (typeof(RTCVideoSource))] interface RTCAVFoundationVideoSource { // -(instancetype)initWithFactory:(RTCPeerConnectionFactory *)factory constraints:(RTCMediaConstraints *)constraints; [Export ("initWithFactory:constraints:")] IntPtr Constructor (RTCPeerConnectionFactory factory, RTCMediaConstraints constraints); // @property (assign, nonatomic) BOOL useBackCamera; [Export ("useBackCamera")] bool UseBackCamera { get; set; } // @property (readonly, nonatomic) AVCaptureSession * captureSession; [Export ("captureSession")] AVCaptureSession CaptureSession { get; } } // @interface RTCAudioSource : RTCMediaSource [BaseType (typeof(RTCMediaSource))] [DisableDefaultCtor] interface RTCAudioSource { } // @protocol RTCMediaStreamTrackDelegate <NSObject> [Protocol, Model] [BaseType (typeof(NSObject))] interface RTCMediaStreamTrackDelegate { // @required -(void)mediaStreamTrackDidChange:(RTCMediaStreamTrack *)mediaStreamTrack; [Abstract] [Export ("mediaStreamTrackDidChange:")] void MediaStreamTrackDidChange (RTCMediaStreamTrack mediaStreamTrack); } // @interface RTCMediaStreamTrack : NSObject [BaseType (typeof(NSObject))] [DisableDefaultCtor] interface RTCMediaStreamTrack { // @property (readonly, nonatomic) NSString * kind; [Export ("kind")] string Kind { get; } // @property (readonly, nonatomic) NSString * label; [Export ("label")] string Label { get; } [Wrap ("WeakDelegate")] RTCMediaStreamTrackDelegate Delegate { get; set; } // @property (nonatomic, weak) id<RTCMediaStreamTrackDelegate> delegate; [NullAllowed, Export ("delegate", ArgumentSemantic.Weak)] NSObject WeakDelegate { get; set; } // -(BOOL)isEnabled; [Export ("isEnabled")] [Verify (MethodToProperty)] bool IsEnabled { get; } // -(BOOL)setEnabled:(BOOL)enabled; [Export ("setEnabled:")] bool SetEnabled (bool enabled); // -(RTCTrackState)state; [Export ("state")] [Verify (MethodToProperty)] RTCTrackState State { get; } // -(BOOL)setState:(RTCTrackState)state; [Export ("setState:")] bool SetState (RTCTrackState state); } // @interface RTCAudioTrack : RTCMediaStreamTrack [BaseType (typeof(RTCMediaStreamTrack))] [DisableDefaultCtor] interface RTCAudioTrack { } // @interface RTCDataChannelInit : NSObject [BaseType (typeof(NSObject))] interface RTCDataChannelInit { // @property (nonatomic) BOOL isOrdered; [Export ("isOrdered")] bool IsOrdered { get; set; } // @property (nonatomic) NSInteger maxRetransmitTimeMs; [Export ("maxRetransmitTimeMs")] nint MaxRetransmitTimeMs { get; set; } // @property (nonatomic) NSInteger maxRetransmits; [Export ("maxRetransmits")] nint MaxRetransmits { get; set; } // @property (nonatomic) BOOL isNegotiated; [Export ("isNegotiated")] bool IsNegotiated { get; set; } // @property (nonatomic) NSInteger streamId; [Export ("streamId")] nint StreamId { get; set; } // @property (nonatomic) NSString * protocol; [Export ("protocol")] string Protocol { get; set; } } // @interface RTCDataBuffer : NSObject [BaseType (typeof(NSObject))] [DisableDefaultCtor] interface RTCDataBuffer { // @property (readonly, nonatomic) NSData * data; [Export ("data")] NSData Data { get; } // @property (readonly, nonatomic) BOOL isBinary; [Export ("isBinary")] bool IsBinary { get; } // -(instancetype)initWithData:(NSData *)data isBinary:(BOOL)isBinary; [Export ("initWithData:isBinary:")] IntPtr Constructor (NSData data, bool isBinary); } // @protocol RTCDataChannelDelegate <NSObject> [Protocol, Model] [BaseType (typeof(NSObject))] interface RTCDataChannelDelegate { // @required -(void)channelDidChangeState:(RTCDataChannel *)channel; [Abstract] [Export ("channelDidChangeState:")] void ChannelDidChangeState (RTCDataChannel channel); // @required -(void)channel:(RTCDataChannel *)channel didReceiveMessageWithBuffer:(RTCDataBuffer *)buffer; [Abstract] [Export ("channel:didReceiveMessageWithBuffer:")] void Channel (RTCDataChannel channel, RTCDataBuffer buffer); // @optional -(void)channel:(RTCDataChannel *)channel didChangeBufferedAmount:(NSUInteger)amount; [Export ("channel:didChangeBufferedAmount:")] void Channel (RTCDataChannel channel, nuint amount); } // @interface RTCDataChannel : NSObject [BaseType (typeof(NSObject))] [DisableDefaultCtor] interface RTCDataChannel { // @property (readonly, nonatomic) NSString * label; [Export ("label")] string Label { get; } // @property (readonly, nonatomic) BOOL isReliable; [Export ("isReliable")] bool IsReliable { get; } // @property (readonly, nonatomic) BOOL isOrdered; [Export ("isOrdered")] bool IsOrdered { get; } // @property (readonly, nonatomic) NSUInteger maxRetransmitTime; [Export ("maxRetransmitTime")] nuint MaxRetransmitTime { get; } // @property (readonly, nonatomic) NSUInteger maxRetransmits; [Export ("maxRetransmits")] nuint MaxRetransmits { get; } // @property (readonly, nonatomic) NSString * protocol; [Export ("protocol")] string Protocol { get; } // @property (readonly, nonatomic) BOOL isNegotiated; [Export ("isNegotiated")] bool IsNegotiated { get; } // @property (readonly, nonatomic) NSInteger streamId; [Export ("streamId")] nint StreamId { get; } // @property (readonly, nonatomic) RTCDataChannelState state; [Export ("state")] RTCDataChannelState State { get; } // @property (readonly, nonatomic) NSUInteger bufferedAmount; [Export ("bufferedAmount")] nuint BufferedAmount { get; } [Wrap ("WeakDelegate")] RTCDataChannelDelegate Delegate { get; set; } // @property (nonatomic, weak) id<RTCDataChannelDelegate> delegate; [NullAllowed, Export ("delegate", ArgumentSemantic.Weak)] NSObject WeakDelegate { get; set; } // -(void)close; [Export ("close")] void Close (); // -(BOOL)sendData:(RTCDataBuffer *)data; [Export ("sendData:")] bool SendData (RTCDataBuffer data); } // @protocol RTCVideoRenderer <NSObject> [Protocol, Model] [BaseType (typeof(NSObject))] interface RTCVideoRenderer { // @required -(void)setSize:(CGSize)size; [Abstract] [Export ("setSize:")] void SetSize (CGSize size); // @required -(void)renderFrame:(RTCI420Frame *)frame; [Abstract] [Export ("renderFrame:")] void RenderFrame (RTCI420Frame frame); } // @protocol RTCEAGLVideoViewDelegate [Protocol, Model] interface RTCEAGLVideoViewDelegate { // @required -(void)videoView:(RTCEAGLVideoView *)videoView didChangeVideoSize:(CGSize)size; [Abstract] [Export ("videoView:didChangeVideoSize:")] void DidChangeVideoSize (RTCEAGLVideoView videoView, CGSize size); } // @interface RTCEAGLVideoView : UIView <RTCVideoRenderer> [BaseType (typeof(UIView))] interface RTCEAGLVideoView : IRTCVideoRenderer { [Wrap ("WeakDelegate")] RTCEAGLVideoViewDelegate Delegate { get; set; } // @property (nonatomic, weak) id<RTCEAGLVideoViewDelegate> delegate; [NullAllowed, Export ("delegate", ArgumentSemantic.Weak)] NSObject WeakDelegate { get; set; } } // @interface RTCFileLogger : NSObject [BaseType (typeof(NSObject))] interface RTCFileLogger { // @property (assign, nonatomic) RTCFileLoggerSeverity severity; [Export ("severity", ArgumentSemantic.Assign)] RTCFileLoggerSeverity Severity { get; set; } // @property (readonly, nonatomic) RTCFileLoggerRotationType rotationType; [Export ("rotationType")] RTCFileLoggerRotationType RotationType { get; } // -(instancetype)initWithDirPath:(NSString *)dirPath maxFileSize:(NSUInteger)maxFileSize; [Export ("initWithDirPath:maxFileSize:")] IntPtr Constructor (string dirPath, nuint maxFileSize); // -(instancetype)initWithDirPath:(NSString *)dirPath maxFileSize:(NSUInteger)maxFileSize rotationType:(RTCFileLoggerRotationType)rotationType __attribute__((objc_designated_initializer)); [Export ("initWithDirPath:maxFileSize:rotationType:")] [DesignatedInitializer] IntPtr Constructor (string dirPath, nuint maxFileSize, RTCFileLoggerRotationType rotationType); // -(void)start; [Export ("start")] void Start (); // -(void)stop; [Export ("stop")] void Stop (); // -(NSData *)logData; [Export ("logData")] [Verify (MethodToProperty)] NSData LogData { get; } } // @interface RTCI420Frame : NSObject [BaseType (typeof(NSObject))] [DisableDefaultCtor] interface RTCI420Frame { // @property (readonly, nonatomic) NSUInteger width; [Export ("width")] nuint Width { get; } // @property (readonly, nonatomic) NSUInteger height; [Export ("height")] nuint Height { get; } // @property (readonly, nonatomic) NSUInteger chromaWidth; [Export ("chromaWidth")] nuint ChromaWidth { get; } // @property (readonly, nonatomic) NSUInteger chromaHeight; [Export ("chromaHeight")] nuint ChromaHeight { get; } // @property (readonly, nonatomic) NSUInteger chromaSize; [Export ("chromaSize")] nuint ChromaSize { get; } // @property (readonly, nonatomic) const uint8_t * yPlane; [Export ("yPlane")] unsafe byte* YPlane { get; } // @property (readonly, nonatomic) const uint8_t * uPlane; [Export ("uPlane")] unsafe byte* UPlane { get; } // @property (readonly, nonatomic) const uint8_t * vPlane; [Export ("vPlane")] unsafe byte* VPlane { get; } // @property (readonly, nonatomic) NSInteger yPitch; [Export ("yPitch")] nint YPitch { get; } // @property (readonly, nonatomic) NSInteger uPitch; [Export ("uPitch")] nint UPitch { get; } // @property (readonly, nonatomic) NSInteger vPitch; [Export ("vPitch")] nint VPitch { get; } // -(BOOL)makeExclusive; [Export ("makeExclusive")] [Verify (MethodToProperty)] bool MakeExclusive { get; } } // @interface RTCICECandidate : NSObject [BaseType (typeof(NSObject))] [DisableDefaultCtor] interface RTCICECandidate { // @property (readonly, copy, nonatomic) NSString * sdpMid; [Export ("sdpMid")] string SdpMid { get; } // @property (readonly, assign, nonatomic) NSInteger sdpMLineIndex; [Export ("sdpMLineIndex")] nint SdpMLineIndex { get; } // @property (readonly, copy, nonatomic) NSString * sdp; [Export ("sdp")] string Sdp { get; } // -(id)initWithMid:(NSString *)sdpMid index:(NSInteger)sdpMLineIndex sdp:(NSString *)sdp; [Export ("initWithMid:index:sdp:")] IntPtr Constructor (string sdpMid, nint sdpMLineIndex, string sdp); } // @interface RTCICEServer : NSObject [BaseType (typeof(NSObject))] [DisableDefaultCtor] interface RTCICEServer { // @property (readonly, nonatomic, strong) NSURL * URI; [Export ("URI", ArgumentSemantic.Strong)] NSUrl URI { get; } // @property (readonly, copy, nonatomic) NSString * username; [Export ("username")] string Username { get; } // @property (readonly, copy, nonatomic) NSString * password; [Export ("password")] string Password { get; } // -(id)initWithURI:(NSURL *)URI username:(NSString *)username password:(NSString *)password; [Export ("initWithURI:username:password:")] IntPtr Constructor (NSUrl URI, string username, string password); } // @interface RTCMediaConstraints : NSObject [BaseType (typeof(NSObject))] interface RTCMediaConstraints { // -(id)initWithMandatoryConstraints:(NSArray *)mandatory optionalConstraints:(NSArray *)optional; [Export ("initWithMandatoryConstraints:optionalConstraints:")] [Verify (StronglyTypedNSArray), Verify (StronglyTypedNSArray)] IntPtr Constructor (NSObject[] mandatory, NSObject[] optional); } // @interface RTCMediaStream : NSObject [BaseType (typeof(NSObject))] [DisableDefaultCtor] interface RTCMediaStream { // @property (readonly, nonatomic, strong) NSArray * audioTracks; [Export ("audioTracks", ArgumentSemantic.Strong)] [Verify (StronglyTypedNSArray)] NSObject[] AudioTracks { get; } // @property (readonly, nonatomic, strong) NSArray * videoTracks; [Export ("videoTracks", ArgumentSemantic.Strong)] [Verify (StronglyTypedNSArray)] NSObject[] VideoTracks { get; } // @property (readonly, nonatomic, strong) NSString * label; [Export ("label", ArgumentSemantic.Strong)] string Label { get; } // -(BOOL)addAudioTrack:(RTCAudioTrack *)track; [Export ("addAudioTrack:")] bool AddAudioTrack (RTCAudioTrack track); // -(BOOL)addVideoTrack:(RTCVideoTrack *)track; [Export ("addVideoTrack:")] bool AddVideoTrack (RTCVideoTrack track); // -(BOOL)removeAudioTrack:(RTCAudioTrack *)track; [Export ("removeAudioTrack:")] bool RemoveAudioTrack (RTCAudioTrack track); // -(BOOL)removeVideoTrack:(RTCVideoTrack *)track; [Export ("removeVideoTrack:")] bool RemoveVideoTrack (RTCVideoTrack track); } // @protocol RTCNSGLVideoViewDelegate [Protocol, Model] interface RTCNSGLVideoViewDelegate { // @required -(void)videoView:(RTCNSGLVideoView *)videoView didChangeVideoSize:(CGSize)size; [Abstract] [Export ("videoView:didChangeVideoSize:")] void DidChangeVideoSize (RTCNSGLVideoView videoView, CGSize size); } // @interface RTCNSGLVideoView <RTCVideoRenderer> interface RTCNSGLVideoView : IRTCVideoRenderer { [Wrap ("WeakDelegate")] RTCNSGLVideoViewDelegate Delegate { get; set; } // @property (nonatomic, weak) id<RTCNSGLVideoViewDelegate> delegate; [NullAllowed, Export ("delegate", ArgumentSemantic.Weak)] NSObject WeakDelegate { get; set; } } // @interface RTCOpenGLVideoRenderer : NSObject [BaseType (typeof(NSObject))] [DisableDefaultCtor] interface RTCOpenGLVideoRenderer { // @property (readonly, nonatomic) RTCI420Frame * lastDrawnFrame; [Export ("lastDrawnFrame")] RTCI420Frame LastDrawnFrame { get; } // -(instancetype)initWithContext:(EAGLContext *)context; [Export ("initWithContext:")] IntPtr Constructor (EAGLContext context); // -(BOOL)drawFrame:(RTCI420Frame *)frame; [Export ("drawFrame:")] bool DrawFrame (RTCI420Frame frame); // -(void)setupGL; [Export ("setupGL")] void SetupGL (); // -(void)teardownGL; [Export ("teardownGL")] void TeardownGL (); } // @interface RTCPair : NSObject [BaseType (typeof(NSObject))] [DisableDefaultCtor] interface RTCPair { // @property (readonly, nonatomic, strong) NSString * key; [Export ("key", ArgumentSemantic.Strong)] string Key { get; } // @property (readonly, nonatomic, strong) NSString * value; [Export ("value", ArgumentSemantic.Strong)] string Value { get; } // -(id)initWithKey:(NSString *)key value:(NSString *)value; [Export ("initWithKey:value:")] IntPtr Constructor (string key, string value); } // @protocol RTCPeerConnectionDelegate <NSObject> [Protocol, Model] [BaseType (typeof(NSObject))] interface RTCPeerConnectionDelegate { // @required -(void)peerConnection:(RTCPeerConnection *)peerConnection signalingStateChanged:(RTCSignalingState)stateChanged; [Abstract] [Export ("peerConnection:signalingStateChanged:")] void PeerConnection (RTCPeerConnection peerConnection, RTCSignalingState stateChanged); // @required -(void)peerConnection:(RTCPeerConnection *)peerConnection addedStream:(RTCMediaStream *)stream; [Abstract] [Export ("peerConnection:addedStream:")] void PeerConnection (RTCPeerConnection peerConnection, RTCMediaStream stream); // @required -(void)peerConnection:(RTCPeerConnection *)peerConnection removedStream:(RTCMediaStream *)stream; [Abstract] [Export ("peerConnection:removedStream:")] void PeerConnection (RTCPeerConnection peerConnection, RTCMediaStream stream); // @required -(void)peerConnectionOnRenegotiationNeeded:(RTCPeerConnection *)peerConnection; [Abstract] [Export ("peerConnectionOnRenegotiationNeeded:")] void PeerConnectionOnRenegotiationNeeded (RTCPeerConnection peerConnection); // @required -(void)peerConnection:(RTCPeerConnection *)peerConnection iceConnectionChanged:(RTCICEConnectionState)newState; [Abstract] [Export ("peerConnection:iceConnectionChanged:")] void PeerConnection (RTCPeerConnection peerConnection, RTCICEConnectionState newState); // @required -(void)peerConnection:(RTCPeerConnection *)peerConnection iceGatheringChanged:(RTCICEGatheringState)newState; [Abstract] [Export ("peerConnection:iceGatheringChanged:")] void PeerConnection (RTCPeerConnection peerConnection, RTCICEGatheringState newState); // @required -(void)peerConnection:(RTCPeerConnection *)peerConnection gotICECandidate:(RTCICECandidate *)candidate; [Abstract] [Export ("peerConnection:gotICECandidate:")] void PeerConnection (RTCPeerConnection peerConnection, RTCICECandidate candidate); // @required -(void)peerConnection:(RTCPeerConnection *)peerConnection didOpenDataChannel:(RTCDataChannel *)dataChannel; [Abstract] [Export ("peerConnection:didOpenDataChannel:")] void PeerConnection (RTCPeerConnection peerConnection, RTCDataChannel dataChannel); } // @interface RTCPeerConnection : NSObject [BaseType (typeof(NSObject))] [DisableDefaultCtor] interface RTCPeerConnection { [Wrap ("WeakDelegate")] RTCPeerConnectionDelegate Delegate { get; set; } // @property (nonatomic, weak) id<RTCPeerConnectionDelegate> delegate; [NullAllowed, Export ("delegate", ArgumentSemantic.Weak)] NSObject WeakDelegate { get; set; } // @property (readonly, nonatomic, strong) NSArray * localStreams; [Export ("localStreams", ArgumentSemantic.Strong)] [Verify (StronglyTypedNSArray)] NSObject[] LocalStreams { get; } // @property (readonly, assign, nonatomic) RTCSessionDescription * localDescription; [Export ("localDescription", ArgumentSemantic.Assign)] RTCSessionDescription LocalDescription { get; } // @property (readonly, assign, nonatomic) RTCSessionDescription * remoteDescription; [Export ("remoteDescription", ArgumentSemantic.Assign)] RTCSessionDescription RemoteDescription { get; } // @property (readonly, assign, nonatomic) RTCSignalingState signalingState; [Export ("signalingState", ArgumentSemantic.Assign)] RTCSignalingState SignalingState { get; } // @property (readonly, assign, nonatomic) RTCICEConnectionState iceConnectionState; [Export ("iceConnectionState", ArgumentSemantic.Assign)] RTCICEConnectionState IceConnectionState { get; } // @property (readonly, assign, nonatomic) RTCICEGatheringState iceGatheringState; [Export ("iceGatheringState", ArgumentSemantic.Assign)] RTCICEGatheringState IceGatheringState { get; } // -(BOOL)addStream:(RTCMediaStream *)stream; [Export ("addStream:")] bool AddStream (RTCMediaStream stream); // -(void)removeStream:(RTCMediaStream *)stream; [Export ("removeStream:")] void RemoveStream (RTCMediaStream stream); // -(RTCDataChannel *)createDataChannelWithLabel:(NSString *)label config:(RTCDataChannelInit *)config; [Export ("createDataChannelWithLabel:config:")] RTCDataChannel CreateDataChannelWithLabel (string label, RTCDataChannelInit config); // -(void)createOfferWithDelegate:(id<RTCSessionDescriptionDelegate>)delegate constraints:(RTCMediaConstraints *)constraints; [Export ("createOfferWithDelegate:constraints:")] void CreateOfferWithDelegate (RTCSessionDescriptionDelegate @delegate, RTCMediaConstraints constraints); // -(void)createAnswerWithDelegate:(id<RTCSessionDescriptionDelegate>)delegate constraints:(RTCMediaConstraints *)constraints; [Export ("createAnswerWithDelegate:constraints:")] void CreateAnswerWithDelegate (RTCSessionDescriptionDelegate @delegate, RTCMediaConstraints constraints); // -(void)setLocalDescriptionWithDelegate:(id<RTCSessionDescriptionDelegate>)delegate sessionDescription:(RTCSessionDescription *)sdp; [Export ("setLocalDescriptionWithDelegate:sessionDescription:")] void SetLocalDescriptionWithDelegate (RTCSessionDescriptionDelegate @delegate, RTCSessionDescription sdp); // -(void)setRemoteDescriptionWithDelegate:(id<RTCSessionDescriptionDelegate>)delegate sessionDescription:(RTCSessionDescription *)sdp; [Export ("setRemoteDescriptionWithDelegate:sessionDescription:")] void SetRemoteDescriptionWithDelegate (RTCSessionDescriptionDelegate @delegate, RTCSessionDescription sdp); // -(BOOL)setConfiguration:(RTCConfiguration *)configuration; [Export ("setConfiguration:")] bool SetConfiguration (RTCConfiguration configuration); // -(BOOL)addICECandidate:(RTCICECandidate *)candidate; [Export ("addICECandidate:")] bool AddICECandidate (RTCICECandidate candidate); // -(void)close; [Export ("close")] void Close (); // -(BOOL)getStatsWithDelegate:(id<RTCStatsDelegate>)delegate mediaStreamTrack:(RTCMediaStreamTrack *)mediaStreamTrack statsOutputLevel:(RTCStatsOutputLevel)statsOutputLevel; [Export ("getStatsWithDelegate:mediaStreamTrack:statsOutputLevel:")] bool GetStatsWithDelegate (RTCStatsDelegate @delegate, RTCMediaStreamTrack mediaStreamTrack, RTCStatsOutputLevel statsOutputLevel); } // @interface RTCPeerConnectionFactory : NSObject [BaseType (typeof(NSObject))] interface RTCPeerConnectionFactory { // +(void)initializeSSL; [Static] [Export ("initializeSSL")] void InitializeSSL (); // +(void)deinitializeSSL; [Static] [Export ("deinitializeSSL")] void DeinitializeSSL (); // -(RTCPeerConnection *)peerConnectionWithICEServers:(NSArray *)servers constraints:(RTCMediaConstraints *)constraints delegate:(id<RTCPeerConnectionDelegate>)delegate; [Export ("peerConnectionWithICEServers:constraints:delegate:")] [Verify (StronglyTypedNSArray)] RTCPeerConnection PeerConnectionWithICEServers (NSObject[] servers, RTCMediaConstraints constraints, RTCPeerConnectionDelegate @delegate); // -(RTCPeerConnection *)peerConnectionWithConfiguration:(RTCConfiguration *)configuration constraints:(RTCMediaConstraints *)constraints delegate:(id<RTCPeerConnectionDelegate>)delegate; [Export ("peerConnectionWithConfiguration:constraints:delegate:")] RTCPeerConnection PeerConnectionWithConfiguration (RTCConfiguration configuration, RTCMediaConstraints constraints, RTCPeerConnectionDelegate @delegate); // -(RTCMediaStream *)mediaStreamWithLabel:(NSString *)label; [Export ("mediaStreamWithLabel:")] RTCMediaStream MediaStreamWithLabel (string label); // -(RTCVideoSource *)videoSourceWithCapturer:(RTCVideoCapturer *)capturer constraints:(RTCMediaConstraints *)constraints; [Export ("videoSourceWithCapturer:constraints:")] RTCVideoSource VideoSourceWithCapturer (RTCVideoCapturer capturer, RTCMediaConstraints constraints); // -(RTCVideoTrack *)videoTrackWithID:(NSString *)videoId source:(RTCVideoSource *)source; [Export ("videoTrackWithID:source:")] RTCVideoTrack VideoTrackWithID (string videoId, RTCVideoSource source); // -(RTCAudioTrack *)audioTrackWithID:(NSString *)audioId; [Export ("audioTrackWithID:")] RTCAudioTrack AudioTrackWithID (string audioId); } // @interface RTCConfiguration : NSObject [BaseType (typeof(NSObject))] interface RTCConfiguration { // @property (assign, nonatomic) RTCIceTransportsType iceTransportsType; [Export ("iceTransportsType", ArgumentSemantic.Assign)] RTCIceTransportsType IceTransportsType { get; set; } // @property (copy, nonatomic) NSArray * iceServers; [Export ("iceServers", ArgumentSemantic.Copy)] [Verify (StronglyTypedNSArray)] NSObject[] IceServers { get; set; } // @property (assign, nonatomic) RTCBundlePolicy bundlePolicy; [Export ("bundlePolicy", ArgumentSemantic.Assign)] RTCBundlePolicy BundlePolicy { get; set; } // @property (assign, nonatomic) RTCRtcpMuxPolicy rtcpMuxPolicy; [Export ("rtcpMuxPolicy", ArgumentSemantic.Assign)] RTCRtcpMuxPolicy RtcpMuxPolicy { get; set; } // @property (assign, nonatomic) RTCTcpCandidatePolicy tcpCandidatePolicy; [Export ("tcpCandidatePolicy", ArgumentSemantic.Assign)] RTCTcpCandidatePolicy TcpCandidatePolicy { get; set; } // @property (assign, nonatomic) int audioJitterBufferMaxPackets; [Export ("audioJitterBufferMaxPackets")] int AudioJitterBufferMaxPackets { get; set; } // @property (assign, nonatomic) int iceConnectionReceivingTimeout; [Export ("iceConnectionReceivingTimeout")] int IceConnectionReceivingTimeout { get; set; } // @property (assign, nonatomic) int iceBackupCandidatePairPingInterval; [Export ("iceBackupCandidatePairPingInterval")] int IceBackupCandidatePairPingInterval { get; set; } // -(instancetype)initWithIceTransportsType:(RTCIceTransportsType)iceTransportsType bundlePolicy:(RTCBundlePolicy)bundlePolicy rtcpMuxPolicy:(RTCRtcpMuxPolicy)rtcpMuxPolicy tcpCandidatePolicy:(RTCTcpCandidatePolicy)tcpCandidatePolicy audioJitterBufferMaxPackets:(int)audioJitterBufferMaxPackets iceConnectionReceivingTimeout:(int)iceConnectionReceivingTimeout iceBackupCandidatePairPingInterval:(int)iceBackupCandidatePairPingInterval; [Export ("initWithIceTransportsType:bundlePolicy:rtcpMuxPolicy:tcpCandidatePolicy:audioJitterBufferMaxPackets:iceConnectionReceivingTimeout:iceBackupCandidatePairPingInterval:")] IntPtr Constructor (RTCIceTransportsType iceTransportsType, RTCBundlePolicy bundlePolicy, RTCRtcpMuxPolicy rtcpMuxPolicy, RTCTcpCandidatePolicy tcpCandidatePolicy, int audioJitterBufferMaxPackets, int iceConnectionReceivingTimeout, int iceBackupCandidatePairPingInterval); } // @interface RTCSessionDescription : NSObject [BaseType (typeof(NSObject))] [DisableDefaultCtor] interface RTCSessionDescription { // @property (readonly, copy, nonatomic) NSString * description; [Export ("description")] string Description { get; } // @property (readonly, copy, nonatomic) NSString * type; [Export ("type")] string Type { get; } // -(id)initWithType:(NSString *)type sdp:(NSString *)sdp; [Export ("initWithType:sdp:")] IntPtr Constructor (string type, string sdp); } [Static] [Verify (ConstantsInterfaceAssociation)] partial interface Constants { // extern NSString *const kRTCSessionDescriptionDelegateErrorDomain; [Field ("kRTCSessionDescriptionDelegateErrorDomain", "__Internal")] NSString kRTCSessionDescriptionDelegateErrorDomain { get; } // extern const int kRTCSessionDescriptionDelegateErrorCode; [Field ("kRTCSessionDescriptionDelegateErrorCode", "__Internal")] int kRTCSessionDescriptionDelegateErrorCode { get; } } // @protocol RTCSessionDescriptionDelegate <NSObject> [Protocol, Model] [BaseType (typeof(NSObject))] interface RTCSessionDescriptionDelegate { // @required -(void)peerConnection:(RTCPeerConnection *)peerConnection didCreateSessionDescription:(RTCSessionDescription *)sdp error:(NSError *)error; [Abstract] [Export ("peerConnection:didCreateSessionDescription:error:")] void DidCreateSessionDescription (RTCPeerConnection peerConnection, RTCSessionDescription sdp, NSError error); // @required -(void)peerConnection:(RTCPeerConnection *)peerConnection didSetSessionDescriptionWithError:(NSError *)error; [Abstract] [Export ("peerConnection:didSetSessionDescriptionWithError:")] void DidSetSessionDescriptionWithError (RTCPeerConnection peerConnection, NSError error); } // @protocol RTCStatsDelegate <NSObject> [Protocol, Model] [BaseType (typeof(NSObject))] interface RTCStatsDelegate { // @required -(void)peerConnection:(RTCPeerConnection *)peerConnection didGetStats:(NSArray *)stats; [Abstract] [Export ("peerConnection:didGetStats:")] [Verify (StronglyTypedNSArray)] void DidGetStats (RTCPeerConnection peerConnection, NSObject[] stats); } // @interface RTCStatsReport : NSObject [BaseType (typeof(NSObject))] [DisableDefaultCtor] interface RTCStatsReport { // @property (readonly, nonatomic) NSString * reportId; [Export ("reportId")] string ReportId { get; } // @property (readonly, nonatomic) NSString * type; [Export ("type")] string Type { get; } // @property (readonly, nonatomic) CFTimeInterval timestamp; [Export ("timestamp")] double Timestamp { get; } // @property (readonly, nonatomic) NSArray * values; [Export ("values")] [Verify (StronglyTypedNSArray)] NSObject[] Values { get; } } // @interface RTCVideoCapturer : NSObject [BaseType (typeof(NSObject))] [DisableDefaultCtor] interface RTCVideoCapturer { // +(RTCVideoCapturer *)capturerWithDeviceName:(NSString *)deviceName; [Static] [Export ("capturerWithDeviceName:")] RTCVideoCapturer CapturerWithDeviceName (string deviceName); } // @interface RTCVideoTrack : RTCMediaStreamTrack [BaseType (typeof(RTCMediaStreamTrack))] [DisableDefaultCtor] interface RTCVideoTrack { // @property (readonly, nonatomic) RTCVideoSource * source; [Export ("source")] RTCVideoSource Source { get; } // -(instancetype)initWithFactory:(RTCPeerConnectionFactory *)factory source:(RTCVideoSource *)source trackId:(NSString *)trackId; [Export ("initWithFactory:source:trackId:")] IntPtr Constructor (RTCPeerConnectionFactory factory, RTCVideoSource source, string trackId); // -(void)addRenderer:(id<RTCVideoRenderer>)renderer; [Export ("addRenderer:")] void AddRenderer (RTCVideoRenderer renderer); // -(void)removeRenderer:(id<RTCVideoRenderer>)renderer; [Export ("removeRenderer:")] void RemoveRenderer (RTCVideoRenderer renderer); }
using NUnit.Framework; using System; using Mtg; using Mtg.Model; using Nancy; using System.Collections.Generic; using MongoDB.Driver; namespace testapi { //// xsp4 --port 8082 /// run the above command in api.mtgdb.info [TestFixture ()] public class TestApi { private const string connectionString = "mongodb://localhost"; IRepository repository = new MongoRepository (connectionString); [Test()] public void Test_get_card_sub_types() { string [] subtypes = repository.GetCardSubTypes().Result; Assert.Greater(subtypes.Length, 0); } [Test()] public void Test_get_card_types() { string [] types = repository.GetCardTypes().Result; Assert.Greater(types.Length, 0); } [Test()] public void Test_get_card_rarity_types() { string [] types = repository.GetCardRarity().Result; Assert.Greater(types.Length, 0); } [Test()] public void Test_search_verify() { CardSearch search = new CardSearch("name eq 'shit and shit' and type not creature"); string[] elements = search.Verify(); foreach(string s in elements) { System.Console.WriteLine(s); } } [Test()] public void Test_mongo() { CardSearch search = new CardSearch("name eq 'Giant Growth' and color eq green"); List<IMongoQuery> queries = search.MongoQuery(); Assert.Greater(queries.Count,1); } [Test()] public void Test_complex_search() { Card [] cards = repository.Search("name m 'giant'",isComplex: true).Result; Assert.Greater(cards.Length, 0); cards = repository.Search("name eq 'giant Growth'",isComplex: true).Result; Assert.Greater(cards.Length, 0); cards = repository.Search("name not 'Giant Growth'",isComplex: true).Result; Assert.Greater(cards.Length, 0); cards = repository.Search("name gt 'Giant Growth'",isComplex: true).Result; Assert.Greater(cards.Length, 0); cards = repository.Search("name gte 'Giant Growth'",isComplex: true).Result; Assert.Greater(cards.Length, 0); cards = repository.Search("name lt 'Giant Growth'",isComplex: true).Result; Assert.Greater(cards.Length, 0); cards = repository.Search("name lte 'Giant Growth'",isComplex: true).Result; Assert.Greater(cards.Length, 0); cards = repository.Search("color m green and name m 'Growth'", isComplex: true).Result; Assert.Greater(cards.Length, 0); cards = repository.Search("convertedmanacost lt 3", isComplex: true).Result; Assert.Greater(cards.Length, 0); //c:rb+t:knight+r:u cards = repository.Search("color eq white and color eq green and subtype m 'Knight' and " + "rarity eq Uncommon", isComplex: true).Result; Assert.Greater(cards.Length, 0); //"c=u+t:creature+d:flying+cc<3+n:cloud" cards = repository.Search("color eq blue and type m 'Creature' and description m 'flying' " + "and convertedmanacost lt 3 and name m 'Cloud'", isComplex: true).Result; Assert.Greater(cards.Length, 0); } [Test()] public void Test_get_card_by_setNumber() { Card card = repository.GetCardBySetNumber("THS", 90).Result; System.Console.Write(card.Id.ToString() + ":" + card.SetNumber.ToString()); Assert.AreEqual("THS", card.CardSetId); Assert.AreEqual(90, card.SetNumber); } [Test()] public void Test_get_random_card() { Card rcard = repository.GetRandomCard().Result; System.Console.Write(rcard.Id.ToString()); Assert.IsNotNull(rcard); } [Test()] public void Test_get_random_card_performance() { Card rcard = repository.GetRandomCard().Result; for(int i = 0; i < 1000; i++ ) { rcard = repository.GetRandomCard().Result; } } [Test()] public void Test_get_random_card_in_set() { Card rcard = repository.GetRandomCardInSet("lea").Result; System.Console.Write(rcard.Id.ToString()); Assert.IsNotNull(rcard); } [Test ()] public void Test_get_multiple_sets () { CardSet[] sets = repository.GetSets(new string[]{"all","arb"}).Result; Assert.Greater (sets.Length,1); } [Test ()] public void Test_get_multiple_cards () { Card[] cards = repository.GetCards(new int[]{1,2,3,4,5}).Result; Assert.Greater (cards.Length,1); } [Test ()] public void Test_search_cards () { Card[] cards = repository.Search ("giant").Result; Assert.Greater (cards.Length,1); } [Test ()] public void Test_get_cards_by_filter () { DynamicDictionary query = new DynamicDictionary(); query.Add ("name", "Ankh of Mishra"); Card[] cards = repository.GetCards (query).Result; Assert.Greater (cards.Length,1); } [Test ()] public void Test_get_cards_by_set () { Card[] cards = repository.GetCardsBySet ("10E").Result; Assert.Greater (cards.Length,1); } [Test ()] public void Test_get_cards_by_set_with_range () { Card[] cards = repository.GetCardsBySet ("10E",11,20).Result; Assert.AreEqual (10, cards.Length); } [Test ()] public void Test_get_card() { Card card = repository.GetCard(1).Result; Assert.IsNotNull (card); } [Test ()] public void Test_get_cards_by_name () { Card[] cards = repository.GetCards ("ankh of mishra").Result; Assert.Greater (cards.Length, 1); } [Test ()] public void Test_get_cards_by_name_without_match () { Card[] cards = repository.GetCards ("").Result; Assert.Greater (cards.Length, 0); } [Test ()] public void Test_get_sets () { CardSet[] sets = repository.GetSets().Result; Assert.Greater (sets.Length,1); } [Test ()] public void Test_get_set () { CardSet set = repository.GetSet("10E").Result; Assert.IsNotNull (set); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using ILRuntime.CLR.TypeSystem; using ILRuntime.CLR.Method; using ILRuntime.Runtime.Enviorment; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using ILRuntime.Reflection; using ILRuntime.CLR.Utils; namespace ILRuntime.Runtime.Generated { unsafe class UnityEngine_GameObject_Binding { public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app) { BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodBase method; Type[] args; Type type = typeof(UnityEngine.GameObject); args = new Type[]{}; method = type.GetMethod("get_activeSelf", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_activeSelf_0); args = new Type[]{typeof(System.Boolean)}; method = type.GetMethod("SetActive", flag, null, args, null); app.RegisterCLRMethodRedirection(method, SetActive_1); Dictionary<string, List<MethodInfo>> genericMethods = new Dictionary<string, List<MethodInfo>>(); List<MethodInfo> lst = null; foreach(var m in type.GetMethods()) { if(m.IsGenericMethodDefinition) { if (!genericMethods.TryGetValue(m.Name, out lst)) { lst = new List<MethodInfo>(); genericMethods[m.Name] = lst; } lst.Add(m); } } args = new Type[]{typeof(UnityEngine.UI.ViewControllerContainer)}; if (genericMethods.TryGetValue("GetComponent", out lst)) { foreach(var m in lst) { if(m.MatchGenericParameters(args, typeof(UnityEngine.UI.ViewControllerContainer))) { method = m.MakeGenericMethod(args); app.RegisterCLRMethodRedirection(method, GetComponent_2); break; } } } args = new Type[]{typeof(UnityEngine.UI.MemberBindingAbstract)}; if (genericMethods.TryGetValue("GetComponentsInChildren", out lst)) { foreach(var m in lst) { if(m.MatchGenericParameters(args, typeof(UnityEngine.UI.MemberBindingAbstract[]), typeof(System.Boolean))) { method = m.MakeGenericMethod(args); app.RegisterCLRMethodRedirection(method, GetComponentsInChildren_3); break; } } } args = new Type[]{typeof(UnityEngine.UI.ViewModelDataSourceTab)}; if (genericMethods.TryGetValue("GetComponentsInChildren", out lst)) { foreach(var m in lst) { if(m.MatchGenericParameters(args, typeof(UnityEngine.UI.ViewModelDataSourceTab[]), typeof(System.Boolean))) { method = m.MakeGenericMethod(args); app.RegisterCLRMethodRedirection(method, GetComponentsInChildren_4); break; } } } args = new Type[]{typeof(UnityEngine.UI.ViewModelDataSourceArray)}; if (genericMethods.TryGetValue("GetComponentsInChildren", out lst)) { foreach(var m in lst) { if(m.MatchGenericParameters(args, typeof(UnityEngine.UI.ViewModelDataSourceArray[]), typeof(System.Boolean))) { method = m.MakeGenericMethod(args); app.RegisterCLRMethodRedirection(method, GetComponentsInChildren_5); break; } } } args = new Type[]{typeof(UnityEngine.UI.EventBinding)}; if (genericMethods.TryGetValue("GetComponentsInChildren", out lst)) { foreach(var m in lst) { if(m.MatchGenericParameters(args, typeof(UnityEngine.UI.EventBinding[]), typeof(System.Boolean))) { method = m.MakeGenericMethod(args); app.RegisterCLRMethodRedirection(method, GetComponentsInChildren_6); break; } } } args = new Type[]{}; method = type.GetMethod("get_transform", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_transform_7); } static StackObject* get_activeSelf_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); UnityEngine.GameObject instance_of_this_method = (UnityEngine.GameObject)typeof(UnityEngine.GameObject).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.activeSelf; __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* SetActive_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Boolean @value = ptr_of_this_method->Value == 1; ptr_of_this_method = ILIntepreter.Minus(__esp, 2); UnityEngine.GameObject instance_of_this_method = (UnityEngine.GameObject)typeof(UnityEngine.GameObject).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); instance_of_this_method.SetActive(@value); return __ret; } static StackObject* GetComponent_2(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); UnityEngine.GameObject instance_of_this_method = (UnityEngine.GameObject)typeof(UnityEngine.GameObject).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.GetComponent<UnityEngine.UI.ViewControllerContainer>(); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* GetComponentsInChildren_3(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Boolean @includeInactive = ptr_of_this_method->Value == 1; ptr_of_this_method = ILIntepreter.Minus(__esp, 2); UnityEngine.GameObject instance_of_this_method = (UnityEngine.GameObject)typeof(UnityEngine.GameObject).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.GetComponentsInChildren<UnityEngine.UI.MemberBindingAbstract>(@includeInactive); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* GetComponentsInChildren_4(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Boolean @includeInactive = ptr_of_this_method->Value == 1; ptr_of_this_method = ILIntepreter.Minus(__esp, 2); UnityEngine.GameObject instance_of_this_method = (UnityEngine.GameObject)typeof(UnityEngine.GameObject).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.GetComponentsInChildren<UnityEngine.UI.ViewModelDataSourceTab>(@includeInactive); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* GetComponentsInChildren_5(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Boolean @includeInactive = ptr_of_this_method->Value == 1; ptr_of_this_method = ILIntepreter.Minus(__esp, 2); UnityEngine.GameObject instance_of_this_method = (UnityEngine.GameObject)typeof(UnityEngine.GameObject).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.GetComponentsInChildren<UnityEngine.UI.ViewModelDataSourceArray>(@includeInactive); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* GetComponentsInChildren_6(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Boolean @includeInactive = ptr_of_this_method->Value == 1; ptr_of_this_method = ILIntepreter.Minus(__esp, 2); UnityEngine.GameObject instance_of_this_method = (UnityEngine.GameObject)typeof(UnityEngine.GameObject).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.GetComponentsInChildren<UnityEngine.UI.EventBinding>(@includeInactive); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* get_transform_7(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); UnityEngine.GameObject instance_of_this_method = (UnityEngine.GameObject)typeof(UnityEngine.GameObject).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.transform; object obj_result_of_this_method = result_of_this_method; if(obj_result_of_this_method is CrossBindingAdaptorType) { return ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance); } return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } } }
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2010 Leopold Bushkin. 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. #endregion namespace MoreLinq { using System; using System.Collections.Generic; using Experimental; static partial class MoreEnumerable { /// <summary> /// Returns the Cartesian product of two sequences by enumerating all /// possible combinations of one item from each sequence, and applying /// a user-defined projection to the items in a given combination. /// </summary> /// <typeparam name="T1"> /// The type of the elements of <paramref name="first"/>.</typeparam> /// <typeparam name="T2"> /// The type of the elements of <paramref name="second"/>.</typeparam> /// <typeparam name="TResult"> /// The type of the elements of the result sequence.</typeparam> /// <param name="first">The first sequence of elements.</param> /// <param name="second">The second sequence of elements.</param> /// <param name="resultSelector">A projection function that combines /// elements from all of the sequences.</param> /// <returns>A sequence of elements returned by /// <paramref name="resultSelector"/>.</returns> /// <remarks> /// <para> /// The method returns items in the same order as a nested foreach /// loop, but all sequences except for <paramref name="first"/> are /// cached when iterated over. The cache is then re-used for any /// subsequent iterations.</para> /// <para> /// This method uses deferred execution and stream its results.</para> /// </remarks> public static IEnumerable<TResult> Cartesian<T1, T2, TResult>( this IEnumerable<T1> first, IEnumerable<T2> second, Func<T1, T2, TResult> resultSelector) { if (first == null) throw new ArgumentNullException(nameof(first)); if (second == null) throw new ArgumentNullException(nameof(second)); if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); return _(); IEnumerable<TResult> _() { IEnumerable<T2> secondMemo; using ((secondMemo = second.Memoize()) as IDisposable) { foreach (var item1 in first) foreach (var item2 in secondMemo) yield return resultSelector(item1, item2); } } } /// <summary> /// Returns the Cartesian product of three sequences by enumerating all /// possible combinations of one item from each sequence, and applying /// a user-defined projection to the items in a given combination. /// </summary> /// <typeparam name="T1"> /// The type of the elements of <paramref name="first"/>.</typeparam> /// <typeparam name="T2"> /// The type of the elements of <paramref name="second"/>.</typeparam> /// <typeparam name="T3"> /// The type of the elements of <paramref name="third"/>.</typeparam> /// <typeparam name="TResult"> /// The type of the elements of the result sequence.</typeparam> /// <param name="first">The first sequence of elements.</param> /// <param name="second">The second sequence of elements.</param> /// <param name="third">The third sequence of elements.</param> /// <param name="resultSelector">A projection function that combines /// elements from all of the sequences.</param> /// <returns>A sequence of elements returned by /// <paramref name="resultSelector"/>.</returns> /// <remarks> /// <para> /// The method returns items in the same order as a nested foreach /// loop, but all sequences except for <paramref name="first"/> are /// cached when iterated over. The cache is then re-used for any /// subsequent iterations.</para> /// <para> /// This method uses deferred execution and stream its results.</para> /// </remarks> public static IEnumerable<TResult> Cartesian<T1, T2, T3, TResult>( this IEnumerable<T1> first, IEnumerable<T2> second, IEnumerable<T3> third, Func<T1, T2, T3, TResult> resultSelector) { if (first == null) throw new ArgumentNullException(nameof(first)); if (second == null) throw new ArgumentNullException(nameof(second)); if (third == null) throw new ArgumentNullException(nameof(third)); if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); return _(); IEnumerable<TResult> _() { IEnumerable<T2> secondMemo; IEnumerable<T3> thirdMemo; using ((secondMemo = second.Memoize()) as IDisposable) using ((thirdMemo = third.Memoize()) as IDisposable) { foreach (var item1 in first) foreach (var item2 in secondMemo) foreach (var item3 in thirdMemo) yield return resultSelector(item1, item2, item3); } } } /// <summary> /// Returns the Cartesian product of four sequences by enumerating all /// possible combinations of one item from each sequence, and applying /// a user-defined projection to the items in a given combination. /// </summary> /// <typeparam name="T1"> /// The type of the elements of <paramref name="first"/>.</typeparam> /// <typeparam name="T2"> /// The type of the elements of <paramref name="second"/>.</typeparam> /// <typeparam name="T3"> /// The type of the elements of <paramref name="third"/>.</typeparam> /// <typeparam name="T4"> /// The type of the elements of <paramref name="fourth"/>.</typeparam> /// <typeparam name="TResult"> /// The type of the elements of the result sequence.</typeparam> /// <param name="first">The first sequence of elements.</param> /// <param name="second">The second sequence of elements.</param> /// <param name="third">The third sequence of elements.</param> /// <param name="fourth">The fourth sequence of elements.</param> /// <param name="resultSelector">A projection function that combines /// elements from all of the sequences.</param> /// <returns>A sequence of elements returned by /// <paramref name="resultSelector"/>.</returns> /// <remarks> /// <para> /// The method returns items in the same order as a nested foreach /// loop, but all sequences except for <paramref name="first"/> are /// cached when iterated over. The cache is then re-used for any /// subsequent iterations.</para> /// <para> /// This method uses deferred execution and stream its results.</para> /// </remarks> public static IEnumerable<TResult> Cartesian<T1, T2, T3, T4, TResult>( this IEnumerable<T1> first, IEnumerable<T2> second, IEnumerable<T3> third, IEnumerable<T4> fourth, Func<T1, T2, T3, T4, TResult> resultSelector) { if (first == null) throw new ArgumentNullException(nameof(first)); if (second == null) throw new ArgumentNullException(nameof(second)); if (third == null) throw new ArgumentNullException(nameof(third)); if (fourth == null) throw new ArgumentNullException(nameof(fourth)); if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); return _(); IEnumerable<TResult> _() { IEnumerable<T2> secondMemo; IEnumerable<T3> thirdMemo; IEnumerable<T4> fourthMemo; using ((secondMemo = second.Memoize()) as IDisposable) using ((thirdMemo = third.Memoize()) as IDisposable) using ((fourthMemo = fourth.Memoize()) as IDisposable) { foreach (var item1 in first) foreach (var item2 in secondMemo) foreach (var item3 in thirdMemo) foreach (var item4 in fourthMemo) yield return resultSelector(item1, item2, item3, item4); } } } /// <summary> /// Returns the Cartesian product of five sequences by enumerating all /// possible combinations of one item from each sequence, and applying /// a user-defined projection to the items in a given combination. /// </summary> /// <typeparam name="T1"> /// The type of the elements of <paramref name="first"/>.</typeparam> /// <typeparam name="T2"> /// The type of the elements of <paramref name="second"/>.</typeparam> /// <typeparam name="T3"> /// The type of the elements of <paramref name="third"/>.</typeparam> /// <typeparam name="T4"> /// The type of the elements of <paramref name="fourth"/>.</typeparam> /// <typeparam name="T5"> /// The type of the elements of <paramref name="fifth"/>.</typeparam> /// <typeparam name="TResult"> /// The type of the elements of the result sequence.</typeparam> /// <param name="first">The first sequence of elements.</param> /// <param name="second">The second sequence of elements.</param> /// <param name="third">The third sequence of elements.</param> /// <param name="fourth">The fourth sequence of elements.</param> /// <param name="fifth">The fifth sequence of elements.</param> /// <param name="resultSelector">A projection function that combines /// elements from all of the sequences.</param> /// <returns>A sequence of elements returned by /// <paramref name="resultSelector"/>.</returns> /// <remarks> /// <para> /// The method returns items in the same order as a nested foreach /// loop, but all sequences except for <paramref name="first"/> are /// cached when iterated over. The cache is then re-used for any /// subsequent iterations.</para> /// <para> /// This method uses deferred execution and stream its results.</para> /// </remarks> public static IEnumerable<TResult> Cartesian<T1, T2, T3, T4, T5, TResult>( this IEnumerable<T1> first, IEnumerable<T2> second, IEnumerable<T3> third, IEnumerable<T4> fourth, IEnumerable<T5> fifth, Func<T1, T2, T3, T4, T5, TResult> resultSelector) { if (first == null) throw new ArgumentNullException(nameof(first)); if (second == null) throw new ArgumentNullException(nameof(second)); if (third == null) throw new ArgumentNullException(nameof(third)); if (fourth == null) throw new ArgumentNullException(nameof(fourth)); if (fifth == null) throw new ArgumentNullException(nameof(fifth)); if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); return _(); IEnumerable<TResult> _() { IEnumerable<T2> secondMemo; IEnumerable<T3> thirdMemo; IEnumerable<T4> fourthMemo; IEnumerable<T5> fifthMemo; using ((secondMemo = second.Memoize()) as IDisposable) using ((thirdMemo = third.Memoize()) as IDisposable) using ((fourthMemo = fourth.Memoize()) as IDisposable) using ((fifthMemo = fifth.Memoize()) as IDisposable) { foreach (var item1 in first) foreach (var item2 in secondMemo) foreach (var item3 in thirdMemo) foreach (var item4 in fourthMemo) foreach (var item5 in fifthMemo) yield return resultSelector(item1, item2, item3, item4, item5); } } } /// <summary> /// Returns the Cartesian product of six sequences by enumerating all /// possible combinations of one item from each sequence, and applying /// a user-defined projection to the items in a given combination. /// </summary> /// <typeparam name="T1"> /// The type of the elements of <paramref name="first"/>.</typeparam> /// <typeparam name="T2"> /// The type of the elements of <paramref name="second"/>.</typeparam> /// <typeparam name="T3"> /// The type of the elements of <paramref name="third"/>.</typeparam> /// <typeparam name="T4"> /// The type of the elements of <paramref name="fourth"/>.</typeparam> /// <typeparam name="T5"> /// The type of the elements of <paramref name="fifth"/>.</typeparam> /// <typeparam name="T6"> /// The type of the elements of <paramref name="sixth"/>.</typeparam> /// <typeparam name="TResult"> /// The type of the elements of the result sequence.</typeparam> /// <param name="first">The first sequence of elements.</param> /// <param name="second">The second sequence of elements.</param> /// <param name="third">The third sequence of elements.</param> /// <param name="fourth">The fourth sequence of elements.</param> /// <param name="fifth">The fifth sequence of elements.</param> /// <param name="sixth">The sixth sequence of elements.</param> /// <param name="resultSelector">A projection function that combines /// elements from all of the sequences.</param> /// <returns>A sequence of elements returned by /// <paramref name="resultSelector"/>.</returns> /// <remarks> /// <para> /// The method returns items in the same order as a nested foreach /// loop, but all sequences except for <paramref name="first"/> are /// cached when iterated over. The cache is then re-used for any /// subsequent iterations.</para> /// <para> /// This method uses deferred execution and stream its results.</para> /// </remarks> public static IEnumerable<TResult> Cartesian<T1, T2, T3, T4, T5, T6, TResult>( this IEnumerable<T1> first, IEnumerable<T2> second, IEnumerable<T3> third, IEnumerable<T4> fourth, IEnumerable<T5> fifth, IEnumerable<T6> sixth, Func<T1, T2, T3, T4, T5, T6, TResult> resultSelector) { if (first == null) throw new ArgumentNullException(nameof(first)); if (second == null) throw new ArgumentNullException(nameof(second)); if (third == null) throw new ArgumentNullException(nameof(third)); if (fourth == null) throw new ArgumentNullException(nameof(fourth)); if (fifth == null) throw new ArgumentNullException(nameof(fifth)); if (sixth == null) throw new ArgumentNullException(nameof(sixth)); if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); return _(); IEnumerable<TResult> _() { IEnumerable<T2> secondMemo; IEnumerable<T3> thirdMemo; IEnumerable<T4> fourthMemo; IEnumerable<T5> fifthMemo; IEnumerable<T6> sixthMemo; using ((secondMemo = second.Memoize()) as IDisposable) using ((thirdMemo = third.Memoize()) as IDisposable) using ((fourthMemo = fourth.Memoize()) as IDisposable) using ((fifthMemo = fifth.Memoize()) as IDisposable) using ((sixthMemo = sixth.Memoize()) as IDisposable) { foreach (var item1 in first) foreach (var item2 in secondMemo) foreach (var item3 in thirdMemo) foreach (var item4 in fourthMemo) foreach (var item5 in fifthMemo) foreach (var item6 in sixthMemo) yield return resultSelector(item1, item2, item3, item4, item5, item6); } } } /// <summary> /// Returns the Cartesian product of seven sequences by enumerating all /// possible combinations of one item from each sequence, and applying /// a user-defined projection to the items in a given combination. /// </summary> /// <typeparam name="T1"> /// The type of the elements of <paramref name="first"/>.</typeparam> /// <typeparam name="T2"> /// The type of the elements of <paramref name="second"/>.</typeparam> /// <typeparam name="T3"> /// The type of the elements of <paramref name="third"/>.</typeparam> /// <typeparam name="T4"> /// The type of the elements of <paramref name="fourth"/>.</typeparam> /// <typeparam name="T5"> /// The type of the elements of <paramref name="fifth"/>.</typeparam> /// <typeparam name="T6"> /// The type of the elements of <paramref name="sixth"/>.</typeparam> /// <typeparam name="T7"> /// The type of the elements of <paramref name="seventh"/>.</typeparam> /// <typeparam name="TResult"> /// The type of the elements of the result sequence.</typeparam> /// <param name="first">The first sequence of elements.</param> /// <param name="second">The second sequence of elements.</param> /// <param name="third">The third sequence of elements.</param> /// <param name="fourth">The fourth sequence of elements.</param> /// <param name="fifth">The fifth sequence of elements.</param> /// <param name="sixth">The sixth sequence of elements.</param> /// <param name="seventh">The seventh sequence of elements.</param> /// <param name="resultSelector">A projection function that combines /// elements from all of the sequences.</param> /// <returns>A sequence of elements returned by /// <paramref name="resultSelector"/>.</returns> /// <remarks> /// <para> /// The method returns items in the same order as a nested foreach /// loop, but all sequences except for <paramref name="first"/> are /// cached when iterated over. The cache is then re-used for any /// subsequent iterations.</para> /// <para> /// This method uses deferred execution and stream its results.</para> /// </remarks> public static IEnumerable<TResult> Cartesian<T1, T2, T3, T4, T5, T6, T7, TResult>( this IEnumerable<T1> first, IEnumerable<T2> second, IEnumerable<T3> third, IEnumerable<T4> fourth, IEnumerable<T5> fifth, IEnumerable<T6> sixth, IEnumerable<T7> seventh, Func<T1, T2, T3, T4, T5, T6, T7, TResult> resultSelector) { if (first == null) throw new ArgumentNullException(nameof(first)); if (second == null) throw new ArgumentNullException(nameof(second)); if (third == null) throw new ArgumentNullException(nameof(third)); if (fourth == null) throw new ArgumentNullException(nameof(fourth)); if (fifth == null) throw new ArgumentNullException(nameof(fifth)); if (sixth == null) throw new ArgumentNullException(nameof(sixth)); if (seventh == null) throw new ArgumentNullException(nameof(seventh)); if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); return _(); IEnumerable<TResult> _() { IEnumerable<T2> secondMemo; IEnumerable<T3> thirdMemo; IEnumerable<T4> fourthMemo; IEnumerable<T5> fifthMemo; IEnumerable<T6> sixthMemo; IEnumerable<T7> seventhMemo; using ((secondMemo = second.Memoize()) as IDisposable) using ((thirdMemo = third.Memoize()) as IDisposable) using ((fourthMemo = fourth.Memoize()) as IDisposable) using ((fifthMemo = fifth.Memoize()) as IDisposable) using ((sixthMemo = sixth.Memoize()) as IDisposable) using ((seventhMemo = seventh.Memoize()) as IDisposable) { foreach (var item1 in first) foreach (var item2 in secondMemo) foreach (var item3 in thirdMemo) foreach (var item4 in fourthMemo) foreach (var item5 in fifthMemo) foreach (var item6 in sixthMemo) foreach (var item7 in seventhMemo) yield return resultSelector(item1, item2, item3, item4, item5, item6, item7); } } } /// <summary> /// Returns the Cartesian product of eight sequences by enumerating all /// possible combinations of one item from each sequence, and applying /// a user-defined projection to the items in a given combination. /// </summary> /// <typeparam name="T1"> /// The type of the elements of <paramref name="first"/>.</typeparam> /// <typeparam name="T2"> /// The type of the elements of <paramref name="second"/>.</typeparam> /// <typeparam name="T3"> /// The type of the elements of <paramref name="third"/>.</typeparam> /// <typeparam name="T4"> /// The type of the elements of <paramref name="fourth"/>.</typeparam> /// <typeparam name="T5"> /// The type of the elements of <paramref name="fifth"/>.</typeparam> /// <typeparam name="T6"> /// The type of the elements of <paramref name="sixth"/>.</typeparam> /// <typeparam name="T7"> /// The type of the elements of <paramref name="seventh"/>.</typeparam> /// <typeparam name="T8"> /// The type of the elements of <paramref name="eighth"/>.</typeparam> /// <typeparam name="TResult"> /// The type of the elements of the result sequence.</typeparam> /// <param name="first">The first sequence of elements.</param> /// <param name="second">The second sequence of elements.</param> /// <param name="third">The third sequence of elements.</param> /// <param name="fourth">The fourth sequence of elements.</param> /// <param name="fifth">The fifth sequence of elements.</param> /// <param name="sixth">The sixth sequence of elements.</param> /// <param name="seventh">The seventh sequence of elements.</param> /// <param name="eighth">The eighth sequence of elements.</param> /// <param name="resultSelector">A projection function that combines /// elements from all of the sequences.</param> /// <returns>A sequence of elements returned by /// <paramref name="resultSelector"/>.</returns> /// <remarks> /// <para> /// The method returns items in the same order as a nested foreach /// loop, but all sequences except for <paramref name="first"/> are /// cached when iterated over. The cache is then re-used for any /// subsequent iterations.</para> /// <para> /// This method uses deferred execution and stream its results.</para> /// </remarks> public static IEnumerable<TResult> Cartesian<T1, T2, T3, T4, T5, T6, T7, T8, TResult>( this IEnumerable<T1> first, IEnumerable<T2> second, IEnumerable<T3> third, IEnumerable<T4> fourth, IEnumerable<T5> fifth, IEnumerable<T6> sixth, IEnumerable<T7> seventh, IEnumerable<T8> eighth, Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult> resultSelector) { if (first == null) throw new ArgumentNullException(nameof(first)); if (second == null) throw new ArgumentNullException(nameof(second)); if (third == null) throw new ArgumentNullException(nameof(third)); if (fourth == null) throw new ArgumentNullException(nameof(fourth)); if (fifth == null) throw new ArgumentNullException(nameof(fifth)); if (sixth == null) throw new ArgumentNullException(nameof(sixth)); if (seventh == null) throw new ArgumentNullException(nameof(seventh)); if (eighth == null) throw new ArgumentNullException(nameof(eighth)); if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); return _(); IEnumerable<TResult> _() { IEnumerable<T2> secondMemo; IEnumerable<T3> thirdMemo; IEnumerable<T4> fourthMemo; IEnumerable<T5> fifthMemo; IEnumerable<T6> sixthMemo; IEnumerable<T7> seventhMemo; IEnumerable<T8> eighthMemo; using ((secondMemo = second.Memoize()) as IDisposable) using ((thirdMemo = third.Memoize()) as IDisposable) using ((fourthMemo = fourth.Memoize()) as IDisposable) using ((fifthMemo = fifth.Memoize()) as IDisposable) using ((sixthMemo = sixth.Memoize()) as IDisposable) using ((seventhMemo = seventh.Memoize()) as IDisposable) using ((eighthMemo = eighth.Memoize()) as IDisposable) { foreach (var item1 in first) foreach (var item2 in secondMemo) foreach (var item3 in thirdMemo) foreach (var item4 in fourthMemo) foreach (var item5 in fifthMemo) foreach (var item6 in sixthMemo) foreach (var item7 in seventhMemo) foreach (var item8 in eighthMemo) yield return resultSelector(item1, item2, item3, item4, item5, item6, item7, item8); } } } } }
// 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.Text; using Xunit; using Xunit.NetCore.Extensions; namespace System.IO.Tests { public class Directory_Delete_str : FileSystemTest { #region Utilities public virtual void Delete(string path) { Directory.Delete(path); } #endregion #region UniversalTests [Fact] public void NullParameters() { Assert.Throws<ArgumentNullException>(() => Delete(null)); } [Fact] public void InvalidParameters() { Assert.Throws<ArgumentException>(() => Delete(string.Empty)); } [Fact] public void ShouldThrowIOExceptionIfContainedFileInUse() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); using (File.Create(Path.Combine(testDir.FullName, GetTestFileName()))) { Assert.Throws<IOException>(() => Delete(testDir.FullName)); } Assert.True(testDir.Exists); } [Fact] public void ShouldThrowIOExceptionForDirectoryWithFiles() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); File.Create(Path.Combine(testDir.FullName, GetTestFileName())).Dispose(); Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); } [Fact] public void DirectoryWithSubdirectories() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.CreateSubdirectory(GetTestFileName()); Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); } [Fact] [OuterLoop] public void DeleteRoot() { Assert.Throws<IOException>(() => Delete(Path.GetPathRoot(Directory.GetCurrentDirectory()))); } [Fact] public void PositiveTest() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Delete(testDir.FullName); Assert.False(testDir.Exists); } [Theory, MemberData(nameof(TrailingCharacters))] public void MissingFile_ThrowsDirectoryNotFound(char trailingChar) { string path = GetTestFilePath() + trailingChar; Assert.Throws<DirectoryNotFoundException>(() => Delete(path)); } [Theory, MemberData(nameof(TrailingCharacters))] public void MissingDirectory_ThrowsDirectoryNotFound(char trailingChar) { string path = Path.Combine(GetTestFilePath(), "file" + trailingChar); Assert.Throws<DirectoryNotFoundException>(() => Delete(path)); } [Fact] public void ShouldThrowIOExceptionDeletingCurrentDirectory() { Assert.Throws<IOException>(() => Delete(Directory.GetCurrentDirectory())); } [ConditionalFact(nameof(CanCreateSymbolicLinks))] public void DeletingSymLinkDoesntDeleteTarget() { var path = GetTestFilePath(); var linkPath = GetTestFilePath(); Directory.CreateDirectory(path); Assert.True(MountHelper.CreateSymbolicLink(linkPath, path, isDirectory: true)); // Both the symlink and the target exist Assert.True(Directory.Exists(path), "path should exist"); Assert.True(Directory.Exists(linkPath), "linkPath should exist"); // Delete the symlink Directory.Delete(linkPath); // Target should still exist Assert.True(Directory.Exists(path), "path should still exist"); Assert.False(Directory.Exists(linkPath), "linkPath should no longer exist"); } [ConditionalFact(nameof(UsingNewNormalization))] public void ExtendedDirectoryWithSubdirectories() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); testDir.CreateSubdirectory(GetTestFileName()); Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); } [ConditionalFact(nameof(LongPathsAreNotBlocked), nameof(UsingNewNormalization))] public void LongPathExtendedDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(IOServices.GetPath(IOInputs.ExtendedPrefix + TestDirectory, characterCount: 500)); Delete(testDir.FullName); Assert.False(testDir.Exists); } #endregion #region PlatformSpecific [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Deleting readonly directory throws IOException public void WindowsDeleteReadOnlyDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.Attributes = FileAttributes.ReadOnly; Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); testDir.Attributes = FileAttributes.Normal; } [ConditionalFact(nameof(UsingNewNormalization))] [PlatformSpecific(TestPlatforms.Windows)] // Deleting extended readonly directory throws IOException public void WindowsDeleteExtendedReadOnlyDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); testDir.Attributes = FileAttributes.ReadOnly; Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); testDir.Attributes = FileAttributes.Normal; } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Deleting readOnly directory succeeds public void UnixDeleteReadOnlyDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.Attributes = FileAttributes.ReadOnly; Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Deleting hidden directory succeeds public void WindowsShouldBeAbleToDeleteHiddenDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.Attributes = FileAttributes.Hidden; Delete(testDir.FullName); Assert.False(testDir.Exists); } [ConditionalFact(nameof(UsingNewNormalization))] [PlatformSpecific(TestPlatforms.Windows)] // Deleting extended hidden directory succeeds public void WindowsShouldBeAbleToDeleteExtendedHiddenDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); testDir.Attributes = FileAttributes.Hidden; Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Deleting hidden directory succeeds public void UnixShouldBeAbleToDeleteHiddenDirectory() { string testDir = "." + GetTestFileName(); Directory.CreateDirectory(Path.Combine(TestDirectory, testDir)); Assert.True(0 != (new DirectoryInfo(Path.Combine(TestDirectory, testDir)).Attributes & FileAttributes.Hidden)); Delete(Path.Combine(TestDirectory, testDir)); Assert.False(Directory.Exists(testDir)); } [Fact] [OuterLoop("Needs sudo access")] [PlatformSpecific(TestPlatforms.Linux)] [Trait(XunitConstants.Category, XunitConstants.RequiresElevation)] public void Unix_NotFoundDirectory_ReadOnlyVolume() { if (PlatformDetection.IsRedHat69) return; // [ActiveIssue(https://github.com/dotnet/corefx/issues/21920)] ReadOnly_FileSystemHelper(readOnlyDirectory => { Assert.Throws<DirectoryNotFoundException>(() => Delete(Path.Combine(readOnlyDirectory, "DoesNotExist"))); }); } #endregion } public class Directory_Delete_str_bool : Directory_Delete_str { #region Utilities public override void Delete(string path) { Directory.Delete(path, false); } public virtual void Delete(string path, bool recursive) { Directory.Delete(path, recursive); } #endregion [Fact] public void RecursiveDelete() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); File.Create(Path.Combine(testDir.FullName, GetTestFileName())).Dispose(); testDir.CreateSubdirectory(GetTestFileName()); Delete(testDir.FullName, true); Assert.False(testDir.Exists); } [Fact] public void RecursiveDeleteWithTrailingSlash() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Delete(testDir.FullName + Path.DirectorySeparatorChar, true); Assert.False(testDir.Exists); } [Fact] [ActiveIssue(24242)] [PlatformSpecific(TestPlatforms.Windows)] [OuterLoop("This test is very slow.")] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Desktop does not have the fix for #22596")] public void RecursiveDelete_DeepNesting() { // Create a 2000 level deep directory and recursively delete from the root. // This number can be dropped if we find it problematic on low memory machines // and/or we can look at skipping in such environments. // // On debug we were overflowing the stack with directories that were under 1000 // levels deep. Testing on a 32GB box I consistently fell over around 1300. // With optimizations to the Delete helper I was able to raise this to around 3200. // Release binaries don't stress the stack nearly as much (10K+ is doable, but can // take 5 minutes on an SSD). string rootDirectory = GetTestFilePath(); StringBuilder sb = new StringBuilder(5000); sb.Append(rootDirectory); for (int i = 0; i < 2000; i++) { sb.Append(@"\a"); } string path = sb.ToString(); Directory.CreateDirectory(path); Delete(rootDirectory, recursive: true); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Recursive delete throws IOException if directory contains in-use file public void RecursiveDelete_ShouldThrowIOExceptionIfContainedFileInUse() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); using (File.Create(Path.Combine(testDir.FullName, GetTestFileName()))) { Assert.Throws<IOException>(() => Delete(testDir.FullName, true)); } Assert.True(testDir.Exists); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using ISITech.Areas.HelpPage.Models; namespace ISITech.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CompareEqualByte() { var test = new SimpleBinaryOpTest__CompareEqualByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareEqualByte { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Byte); private const int Op2ElementCount = VectorSize / sizeof(Byte); private const int RetElementCount = VectorSize / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector256<Byte> _clsVar1; private static Vector256<Byte> _clsVar2; private Vector256<Byte> _fld1; private Vector256<Byte> _fld2; private SimpleBinaryOpTest__DataTable<Byte, Byte, Byte> _dataTable; static SimpleBinaryOpTest__CompareEqualByte() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__CompareEqualByte() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Byte, Byte, Byte>(_data1, _data2, new Byte[RetElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.CompareEqual( Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.CompareEqual( Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.CompareEqual( Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }) .Invoke(null, new object[] { Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.CompareEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr); var result = Avx2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)); var result = Avx2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)); var result = Avx2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__CompareEqualByte(); var result = Avx2.CompareEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.CompareEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Byte> left, Vector256<Byte> right, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { if (result[0] != ((left[0] == right[0]) ? unchecked((byte)(-1)) : 0)) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] == right[i]) ? unchecked((byte)(-1)) : 0)) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.CompareEqual)}<Byte>(Vector256<Byte>, Vector256<Byte>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// ReSharper disable InconsistentNaming // ReSharper disable UnusedParameter.Local namespace IIS.SLSharp.Shaders { public abstract partial class ShaderDefinition { public sealed class mat2 { #region .ctor /// <summary> Initialized all diogonal entries to scale </summary> public mat2(float scale) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2(mat2x3 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2(mat2x4 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2(mat3x2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2(mat3 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2(mat3x4 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2(mat4x2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2(mat4x3 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2(mat4 m) { throw _invalidAccess; } public mat2(vec2 column1, vec2 column2) { throw _invalidAccess; } /// <summary>initialized the matrix with a vec4</summary> public mat2(vec4 compressedMatrix) { throw _invalidAccess; } #endregion /// <summary> /// retrieves the selected column as vector /// </summary> /// <param name="column">zero based column index</param> /// <returns></returns> public vec2 this[int column] { get { throw _invalidAccess; } set { throw _invalidAccess; } } } public sealed class mat2x3 { #region .ctor /// <summary> Initialized all diogonal entries to scale </summary> public mat2x3(float scale) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat2x3(mat2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2x3(mat2x4 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat2x3(mat3x2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2x3(mat3 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2x3(mat3x4 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat2x3(mat4x2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2x3(mat4x3 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2x3(mat4 m) { throw _invalidAccess; } public mat2x3(vec3 column1, vec3 column2) { throw _invalidAccess; } #endregion public vec3 this[int column] { get { throw _invalidAccess; } set { throw _invalidAccess; } } } public sealed class mat2x4 { #region .ctor /// <summary> Initialized all diogonal entries to scale </summary> public mat2x4(float scale) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat2x4(mat2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat2x4(mat2x3 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat2x4(mat3x2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2x4(mat3 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2x4(mat3x4 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat2x4(mat4x2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat2x4(mat4x3 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2x4(mat4 m) { throw _invalidAccess; } public mat2x4(vec4 column1, vec4 column2) { throw _invalidAccess; } #endregion public vec4 this[int column] { get { throw _invalidAccess; } set { throw _invalidAccess; } } } public sealed class mat3x2 { #region .ctor /// <summary> Initialized all diogonal entries to scale </summary> public mat3x2(float scale) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3x2(mat2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3x2(mat2x3 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3x2(mat2x4 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat3x2(mat3 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat3x2(mat3x4 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat3x2(mat4x2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat3x2(mat4x3 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat3x2(mat4 m) { throw _invalidAccess; } public mat3x2(vec2 column1, vec2 column2, vec2 column3) { throw _invalidAccess; } #endregion public vec2 this[int column] { get { throw _invalidAccess; } set { throw _invalidAccess; } } } public sealed class mat3 { #region .ctor /// <summary> Initialized all diogonal entries to scale </summary> public mat3(float scale) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3(mat2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3(mat2x3 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3(mat2x4 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3(mat3x2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat3(mat3x4 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3(mat4x2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat3(mat4x3 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat3(mat4 m) { throw _invalidAccess; } public mat3(vec3 column1, vec3 column2, vec3 column3) { throw _invalidAccess; } #endregion public vec3 this[int column] { get { throw _invalidAccess; } set { throw _invalidAccess; } } } public sealed class mat3x4 { #region .ctor /// <summary> Initialized all diogonal entries to scale </summary> public mat3x4(float scale) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3x4(mat2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3x4(mat2x3 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3x4(mat2x4 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3x4(mat3x2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3x4(mat3 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3x4(mat4x2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3x4(mat4x3 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat3x4(mat4 m) { throw _invalidAccess; } public mat3x4(vec4 column1, vec4 column2, vec4 column3) { throw _invalidAccess; } #endregion public vec4 this[int column] { get { throw _invalidAccess; } set { throw _invalidAccess; } } } public sealed class mat4x2 { #region .ctor /// <summary> Initialized all diogonal entries to scale </summary> public mat4x2(float scale) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x2(mat2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x2(mat2x3 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x2(mat2x4 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x2(mat3x2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x2(mat3 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x2(mat3x4 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat4x2(mat4x3 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat4x2(mat4 m) { throw _invalidAccess; } public mat4x2(vec2 column1, vec2 column2, vec2 column3, vec2 column4) { throw _invalidAccess; } #endregion public vec2 this[int column] { get { throw _invalidAccess; } set { throw _invalidAccess; } } } public sealed class mat4x3 { #region .ctor /// <summary> Initialized all diogonal entries to scale </summary> public mat4x3(float scale) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x3(mat2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x3(mat2x3 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x3(mat2x4 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x3(mat3x2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x3(mat3 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x3(mat3x4 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x3(mat4x2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat4x3(mat4 m) { throw _invalidAccess; } public mat4x3(vec3 column1, vec3 column2, vec3 column3, vec3 column4) { throw _invalidAccess; } #endregion public vec3 this[int column] { get { throw _invalidAccess; } set { throw _invalidAccess; } } } public sealed class mat4 { #region .ctor /// <summary> Initialized all diogonal entries to scale </summary> public mat4(float scale) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4(mat2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4(mat2x3 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4(mat2x4 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4(mat3x2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4(mat3 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4(mat3x4 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4(mat4x2 m) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat4(mat4x3 m) { throw _invalidAccess; } public mat4(vec4 column1, vec4 column2, vec4 column3, vec4 column4) { throw _invalidAccess; } #endregion public vec4 this[int column] { get { throw _invalidAccess; } set { throw _invalidAccess; } } } } } // ReSharper restore InconsistentNaming // ReSharper restore UnusedParameter.Local
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.AddUsing { public partial class AddUsingTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestWhereExtension() { await TestAsync( @"using System ; using System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { var q = args . [|Where|] } } ", @"using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { var q = args . Where } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestSelectExtension() { await TestAsync( @"using System ; using System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { var q = args . [|Select|] } } ", @"using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { var q = args . Select } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestGroupByExtension() { await TestAsync( @"using System ; using System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { var q = args . [|GroupBy|] } } ", @"using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { var q = args . GroupBy } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestJoinExtension() { await TestAsync( @"using System ; using System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { var q = args . [|Join|] } } ", @"using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { var q = args . Join } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task RegressionFor8455() { await TestMissingAsync( @"class C { void M ( ) { int dim = ( int ) Math . [|Min|] ( ) ; } } "); } [WorkItem(772321)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestExtensionWithThePresenceOfTheSameNameNonExtensionMethod() { await TestAsync( @"namespace NS1 { class Program { void Main() { [|new C().Foo(4);|] } } class C { public void Foo(string y) { } } } namespace NS2 { static class CExt { public static void Foo(this NS1.C c, int x) { } } } ", @"using NS2; namespace NS1 { class Program { void Main() { new C().Foo(4); } } class C { public void Foo(string y) { } } } namespace NS2 { static class CExt { public static void Foo(this NS1.C c, int x) { } } } "); } [WorkItem(772321)] [WorkItem(920398)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestExtensionWithThePresenceOfTheSameNameNonExtensionPrivateMethod() { await TestAsync( @"namespace NS1 { class Program { void Main() { [|new C().Foo(4);|] } } class C { private void Foo(int x) { } } } namespace NS2 { static class CExt { public static void Foo(this NS1.C c, int x) { } } } ", @"using NS2; namespace NS1 { class Program { void Main() { new C().Foo(4); } } class C { private void Foo(int x) { } } } namespace NS2 { static class CExt { public static void Foo(this NS1.C c, int x) { } } } "); } [WorkItem(772321)] [WorkItem(920398)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestExtensionWithThePresenceOfTheSameNameExtensionPrivateMethod() { await TestAsync( @"using NS2; namespace NS1 { class Program { void Main() { [|new C().Foo(4);|] } } class C { } } namespace NS2 { static class CExt { private static void Foo(this NS1.C c, int x) { } } } namespace NS3 { static class CExt { public static void Foo(this NS1.C c, int x) { } } } ", @"using NS2; using NS3; namespace NS1 { class Program { void Main() { new C().Foo(4); } } class C { } } namespace NS2 { static class CExt { private static void Foo(this NS1.C c, int x) { } } } namespace NS3 { static class CExt { public static void Foo(this NS1.C c, int x) { } } } "); } [WorkItem(269)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestAddUsingForAddExtentionMethod() { await TestAsync( @"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { [|1|] } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", @"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { 1 } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", parseOptions: null); } [WorkItem(269)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestAddUsingForAddExtentionMethod2() { await TestAsync( @"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { 1 , 2 , [|3|] } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", @"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { 1 , 2 , 3 } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", parseOptions: null); } [WorkItem(269)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestAddUsingForAddExtentionMethod3() { await TestAsync( @"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { 1 , [|2|] , 3 } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", @"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { 1 , 2 , 3 } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", parseOptions: null); } [WorkItem(269)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestAddUsingForAddExtentionMethod4() { await TestAsync( @"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , [|{ 4 , 5 , 6 }|] , { 7 , 8 , 9 } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", @"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", parseOptions: null); } [WorkItem(269)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestAddUsingForAddExtentionMethod5() { await TestAsync( @"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { 4 , 5 , 6 } , [|{ 7 , 8 , 9 }|] } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", @"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", parseOptions: null); } [WorkItem(269)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestAddUsingForAddExtentionMethod6() { await TestAsync( @"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { ""Four"" , ""Five"" , ""Six"" } , [|{ '7' , '8' , '9' }|] } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", @"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { ""Four"" , ""Five"" , ""Six"" } , { '7' , '8' , '9' } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", parseOptions: null); } [WorkItem(269)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestAddUsingForAddExtentionMethod7() { await TestAsync( @"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , [|{ ""Four"" , ""Five"" , ""Six"" }|] , { '7' , '8' , '9' } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", @"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { ""Four"" , ""Five"" , ""Six"" } , { '7' , '8' , '9' } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", parseOptions: null); } [WorkItem(269)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestAddUsingForAddExtentionMethod8() { await TestAsync( @"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { [|{ 1 , 2 , 3 }|] } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", @"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", parseOptions: null); } [WorkItem(269)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestAddUsingForAddExtentionMethod9() { await TestAsync( @"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { [|""This""|] } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", @"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { ""This"" } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } ", parseOptions: null); } [WorkItem(269)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestAddUsingForAddExtentionMethod10() { await TestAsync( @"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { [|{ 1 , 2 , 3 }|] , { ""Four"" , ""Five"" , ""Six"" } , { '7' , '8' , '9' } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } namespace Ext2 { static class Extensions { public static void Add ( this X x , object [ ] i ) { } } } ", @"using System ; using System . Collections ; using Ext ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { ""Four"" , ""Five"" , ""Six"" } , { '7' , '8' , '9' } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } namespace Ext2 { static class Extensions { public static void Add ( this X x , object [ ] i ) { } } } ", parseOptions: null); } [WorkItem(269)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task TestAddUsingForAddExtentionMethod11() { await TestAsync( @"using System ; using System . Collections ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { [|{ 1 , 2 , 3 }|] , { ""Four"" , ""Five"" , ""Six"" } , { '7' , '8' , '9' } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } namespace Ext2 { static class Extensions { public static void Add ( this X x , object [ ] i ) { } } } ", @"using System ; using System . Collections ; using Ext2 ; class X : IEnumerable { public IEnumerator GetEnumerator ( ) { new X { { 1 , 2 , 3 } , { ""Four"" , ""Five"" , ""Six"" } , { '7' , '8' , '9' } } ; return null ; } } namespace Ext { static class Extensions { public static void Add ( this X x , int i ) { } } } namespace Ext2 { static class Extensions { public static void Add ( this X x , object [ ] i ) { } } } ", index: 1, parseOptions: null); } [WorkItem(3818, "https://github.com/dotnet/roslyn/issues/3818")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task InExtensionMethodUnderConditionalAccessExpression() { var initialText = @"<Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <Document FilePath = ""Program""> namespace Sample { class Program { static void Main(string[] args) { string myString = ""Sample""; var other = myString?[|.StringExtension()|].Substring(0); } } } </Document> <Document FilePath = ""Extensions""> namespace Sample.Extensions { public static class StringExtensions { public static string StringExtension(this string s) { return ""Ok""; } } } </Document> </Project> </Workspace>"; var expectedText = @"using Sample.Extensions; namespace Sample { class Program { static void Main(string[] args) { string myString = ""Sample""; var other = myString?.StringExtension().Substring(0); } } }"; await TestAsync(initialText, expectedText); } [WorkItem(3818, "https://github.com/dotnet/roslyn/issues/3818")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task InExtensionMethodUnderMultipleConditionalAccessExpressions() { var initialText = @"<Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <Document FilePath = ""Program""> public class C { public T F&lt;T&gt;(T x) { return F(new C())?.F(new C())?[|.Extn()|]; } } </Document> <Document FilePath = ""Extensions""> namespace Sample.Extensions { public static class Extensions { public static C Extn(this C obj) { return obj.F(new C()); } } } </Document> </Project> </Workspace>"; var expectedText = @"using Sample.Extensions; public class C { public T F<T>(T x) { return F(new C())?.F(new C())?.Extn(); } }"; await TestAsync(initialText, expectedText); } [WorkItem(3818, "https://github.com/dotnet/roslyn/issues/3818")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddUsing)] public async Task InExtensionMethodUnderMultipleConditionalAccessExpressions2() { var initialText = @"<Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <Document FilePath = ""Program""> public class C { public T F&lt;T&gt;(T x) { return F(new C())?.F(new C())[|.Extn()|]?.F(newC()); } } </Document> <Document FilePath = ""Extensions""> namespace Sample.Extensions { public static class Extensions { public static C Extn(this C obj) { return obj.F(new C()); } } } </Document> </Project> </Workspace>"; var expectedText = @"using Sample.Extensions; public class C { public T F<T>(T x) { return F(new C())?.F(new C()).Extn()?.F(newC()); } }"; await TestAsync(initialText, expectedText); } } }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt #nullable enable using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Security; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Builders; namespace NUnit.Framework { /// <summary> /// Indicates the source to be used to provide test fixture instances for a test class. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)] public class TestCaseSourceAttribute : NUnitAttribute, ITestBuilder, IImplyFixture { private readonly NUnitTestCaseBuilder _builder = new NUnitTestCaseBuilder(); #region Constructors /// <summary> /// Construct with the name of the method, property or field that will provide data /// </summary> /// <param name="sourceName">The name of a static method, property or field that will provide data.</param> public TestCaseSourceAttribute(string sourceName) { this.SourceName = sourceName; } /// <summary> /// Construct with a Type and name /// </summary> /// <param name="sourceType">The Type that will provide data</param> /// <param name="sourceName">The name of a static method, property or field that will provide data.</param> /// <param name="methodParams">A set of parameters passed to the method, works only if the Source Name is a method. /// If the source name is a field or property has no effect.</param> public TestCaseSourceAttribute(Type sourceType, string sourceName, object?[]? methodParams) { this.MethodParams = methodParams; this.SourceType = sourceType; this.SourceName = sourceName; } /// <summary> /// Construct with a Type and name /// </summary> /// <param name="sourceType">The Type that will provide data</param> /// <param name="sourceName">The name of a static method, property or field that will provide data.</param> public TestCaseSourceAttribute(Type sourceType, string sourceName) { this.SourceType = sourceType; this.SourceName = sourceName; } /// <summary> /// Construct with a name /// </summary> /// <param name="sourceName">The name of a static method, property or field that will provide data.</param> /// <param name="methodParams">A set of parameters passed to the method, works only if the Source Name is a method. /// If the source name is a field or property has no effect.</param> public TestCaseSourceAttribute(string sourceName, object?[]? methodParams) { this.MethodParams = methodParams; this.SourceName = sourceName; } /// <summary> /// Construct with a Type /// </summary> /// <param name="sourceType">The type that will provide data</param> public TestCaseSourceAttribute(Type sourceType) { this.SourceType = sourceType; } #endregion #region Properties /// <summary> /// A set of parameters passed to the method, works only if the Source Name is a method. /// If the source name is a field or property has no effect. /// </summary> public object?[]? MethodParams { get; } /// <summary> /// The name of a the method, property or field to be used as a source /// </summary> public string? SourceName { get; } /// <summary> /// A Type to be used as a source /// </summary> public Type? SourceType { get; } /// <summary> /// Gets or sets the category associated with every fixture created from /// this attribute. May be a single category or a comma-separated list. /// </summary> public string? Category { get; set; } #endregion #region ITestBuilder Members /// <summary> /// Builds any number of tests from the specified method and context. /// </summary> /// <param name="method">The IMethod for which tests are to be constructed.</param> /// <param name="suite">The suite to which the tests will be added.</param> public IEnumerable<TestMethod> BuildFrom(IMethodInfo method, Test? suite) { int count = 0; foreach (TestCaseParameters parms in GetTestCasesFor(method)) { count++; yield return _builder.BuildTestMethod(method, suite, parms); } // If count > 0, error messages will be shown for each case // but if it's 0, we need to add an extra "test" to show the message. if (count == 0 && method.GetParameters().Length == 0) { var parms = new TestCaseParameters(); parms.RunState = RunState.NotRunnable; parms.Properties.Set(PropertyNames.SkipReason, "TestCaseSourceAttribute may not be used on a method without parameters"); yield return _builder.BuildTestMethod(method, suite, parms); } } #endregion #region Helper Methods [SecuritySafeCritical] private IEnumerable<ITestCaseData> GetTestCasesFor(IMethodInfo method) { List<ITestCaseData> data = new List<ITestCaseData>(); try { IEnumerable? source = ContextUtils.DoIsolated(() => GetTestCaseSource(method)); if (source != null) { foreach (object? item in source) { // First handle two easy cases: // 1. Source is null. This is really an error but if we // throw an exception we simply get an invalid fixture // without good info as to what caused it. Passing a // single null argument will cause an error to be // reported at the test level, in most cases. // 2. User provided an ITestCaseData and we just use it. ITestCaseData? parms = item == null ? new TestCaseParameters(new object?[] { null }) : item as ITestCaseData; if (parms == null) { object?[]? args = null; // 3. An array was passed, it may be an object[] // or possibly some other kind of array, which // TestCaseSource can accept. var array = item as Array; if (array != null) { // If array has the same number of elements as parameters // and it does not fit exactly into single existing parameter // we believe that this array contains arguments, not is a bare // argument itself. var parameters = method.GetParameters(); var argsNeeded = parameters.Length; if (argsNeeded > 0 && argsNeeded == array.Length && parameters[0].ParameterType != array.GetType()) { args = new object?[array.Length]; for (var i = 0; i < array.Length; i++) args[i] = array.GetValue(i); } } if (args == null) { args = new object?[] { item }; } parms = new TestCaseParameters(args); } if (this.Category != null) foreach (string cat in this.Category.Split(new char[] { ',' })) parms.Properties.Add(PropertyNames.Category, cat); data.Add(parms); } } else { data.Clear(); data.Add(new TestCaseParameters(new Exception("The test case source could not be found."))); } } catch (Exception ex) { data.Clear(); data.Add(new TestCaseParameters(ex)); } return data; } private IEnumerable? GetTestCaseSource(IMethodInfo method) { Type sourceType = SourceType ?? method.TypeInfo.Type; // Handle Type implementing IEnumerable separately if (SourceName == null) return Reflect.Construct(sourceType, null) as IEnumerable; MemberInfo[] members = sourceType.GetMemberIncludingFromBase(SourceName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); if (members.Length == 1) { MemberInfo member = members[0]; var field = member as FieldInfo; if (field != null) return field.IsStatic ? (MethodParams == null ? (IEnumerable)field.GetValue(null) : ReturnErrorAsParameter(ParamGivenToField)) : ReturnErrorAsParameter(SourceMustBeStatic); var property = member as PropertyInfo; if (property != null) return property.GetGetMethod(true).IsStatic ? (MethodParams == null ? (IEnumerable)property.GetValue(null, null) : ReturnErrorAsParameter(ParamGivenToProperty)) : ReturnErrorAsParameter(SourceMustBeStatic); var m = member as MethodInfo; if (m != null) return m.IsStatic ? (MethodParams == null || m.GetParameters().Length == MethodParams.Length ? (IEnumerable)m.Invoke(null, MethodParams) : ReturnErrorAsParameter(NumberOfArgsDoesNotMatch)) : ReturnErrorAsParameter(SourceMustBeStatic); } return null; } private static IEnumerable ReturnErrorAsParameter(string errorMessage) { var parms = new TestCaseParameters(); parms.RunState = RunState.NotRunnable; parms.Properties.Set(PropertyNames.SkipReason, errorMessage); return new TestCaseParameters[] { parms }; } private const string SourceMustBeStatic = "The sourceName specified on a TestCaseSourceAttribute must refer to a static field, property or method."; private const string ParamGivenToField = "You have specified a data source field but also given a set of parameters. Fields cannot take parameters, " + "please revise the 3rd parameter passed to the TestCaseSourceAttribute and either remove " + "it or specify a method."; private const string ParamGivenToProperty = "You have specified a data source property but also given a set of parameters. " + "Properties cannot take parameters, please revise the 3rd parameter passed to the " + "TestCaseSource attribute and either remove it or specify a method."; private const string NumberOfArgsDoesNotMatch = "You have given the wrong number of arguments to the method in the TestCaseSourceAttribute" + ", please check the number of parameters passed in the object is correct in the 3rd parameter for the " + "TestCaseSourceAttribute and this matches the number of parameters in the target method and try again."; #endregion } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Ntfs { using System; using System.Collections.Generic; using System.IO; internal class NonResidentAttributeBuffer : NonResidentDataBuffer { private File _file; private NtfsAttribute _attribute; public NonResidentAttributeBuffer(File file, NtfsAttribute attribute) : base(file.Context, CookRuns(attribute), file.IndexInMft == MasterFileTable.MftIndex) { _file = file; _attribute = attribute; switch (attribute.Flags & (AttributeFlags.Compressed | AttributeFlags.Sparse)) { case AttributeFlags.Sparse: _activeStream = new SparseClusterStream(_attribute, _rawStream); break; case AttributeFlags.Compressed: _activeStream = new CompressedClusterStream(_context, _attribute, _rawStream); break; case AttributeFlags.None: _activeStream = _rawStream; break; default: throw new NotImplementedException("Unhandled attribute type '" + attribute.Flags + "'"); } } public override bool CanWrite { get { return _context.RawStream.CanWrite && _file != null; } } public override long Capacity { get { return PrimaryAttributeRecord.DataLength; } } private NonResidentAttributeRecord PrimaryAttributeRecord { get { return _attribute.PrimaryRecord as NonResidentAttributeRecord; } } public void AlignVirtualClusterCount() { _file.MarkMftRecordDirty(); _activeStream.ExpandToClusters(Utilities.Ceil(_attribute.Length, _bytesPerCluster), (NonResidentAttributeRecord)_attribute.LastExtent, false); } public override void SetCapacity(long value) { if (!CanWrite) { throw new IOException("Attempt to change length of file not opened for write"); } if (value == Capacity) { return; } _file.MarkMftRecordDirty(); long newClusterCount = Utilities.Ceil(value, _bytesPerCluster); if (value < Capacity) { Truncate(value); } else { _activeStream.ExpandToClusters(newClusterCount, (NonResidentAttributeRecord)_attribute.LastExtent, true); PrimaryAttributeRecord.AllocatedLength = _cookedRuns.NextVirtualCluster * _bytesPerCluster; } PrimaryAttributeRecord.DataLength = value; if (PrimaryAttributeRecord.InitializedDataLength > value) { PrimaryAttributeRecord.InitializedDataLength = value; } _cookedRuns.CollapseRuns(); } public override void Write(long pos, byte[] buffer, int offset, int count) { if (!CanWrite) { throw new IOException("Attempt to write to file not opened for write"); } if (count == 0) { return; } if (pos + count > Capacity) { SetCapacity(pos + count); } // Write zeros from end of current initialized data to the start of the new write if (pos > PrimaryAttributeRecord.InitializedDataLength) { InitializeData(pos); } int allocatedClusters = 0; long focusPos = pos; while (focusPos < pos + count) { long vcn = focusPos / _bytesPerCluster; long remaining = (pos + count) - focusPos; long clusterOffset = focusPos - (vcn * _bytesPerCluster); if (vcn * _bytesPerCluster != focusPos || remaining < _bytesPerCluster) { // Unaligned or short write int toWrite = (int)Math.Min(remaining, _bytesPerCluster - clusterOffset); _activeStream.ReadClusters(vcn, 1, _ioBuffer, 0); Array.Copy(buffer, offset + (focusPos - pos), _ioBuffer, clusterOffset, toWrite); allocatedClusters += _activeStream.WriteClusters(vcn, 1, _ioBuffer, 0); focusPos += toWrite; } else { // Aligned, full cluster writes... int fullClusters = (int)(remaining / _bytesPerCluster); allocatedClusters += _activeStream.WriteClusters(vcn, fullClusters, buffer, (int)(offset + (focusPos - pos))); focusPos += fullClusters * _bytesPerCluster; } } if (pos + count > PrimaryAttributeRecord.InitializedDataLength) { _file.MarkMftRecordDirty(); PrimaryAttributeRecord.InitializedDataLength = pos + count; } if (pos + count > PrimaryAttributeRecord.DataLength) { _file.MarkMftRecordDirty(); PrimaryAttributeRecord.DataLength = pos + count; } if ((_attribute.Flags & (AttributeFlags.Compressed | AttributeFlags.Sparse)) != 0) { PrimaryAttributeRecord.CompressedDataSize += allocatedClusters * _bytesPerCluster; } _cookedRuns.CollapseRuns(); } public override void Clear(long pos, int count) { if (!CanWrite) { throw new IOException("Attempt to erase bytes from file not opened for write"); } if (count == 0) { return; } if (pos + count > Capacity) { SetCapacity(pos + count); } _file.MarkMftRecordDirty(); // Write zeros from end of current initialized data to the start of the new write if (pos > PrimaryAttributeRecord.InitializedDataLength) { InitializeData(pos); } int releasedClusters = 0; long focusPos = pos; while (focusPos < pos + count) { long vcn = focusPos / _bytesPerCluster; long remaining = (pos + count) - focusPos; long clusterOffset = focusPos - (vcn * _bytesPerCluster); if (vcn * _bytesPerCluster != focusPos || remaining < _bytesPerCluster) { // Unaligned or short write int toClear = (int)Math.Min(remaining, _bytesPerCluster - clusterOffset); if (_activeStream.IsClusterStored(vcn)) { _activeStream.ReadClusters(vcn, 1, _ioBuffer, 0); Array.Clear(_ioBuffer, (int)clusterOffset, toClear); releasedClusters -= _activeStream.WriteClusters(vcn, 1, _ioBuffer, 0); } focusPos += toClear; } else { // Aligned, full cluster clears... int fullClusters = (int)(remaining / _bytesPerCluster); releasedClusters += _activeStream.ClearClusters(vcn, fullClusters); focusPos += fullClusters * _bytesPerCluster; } } if (pos + count > PrimaryAttributeRecord.InitializedDataLength) { PrimaryAttributeRecord.InitializedDataLength = pos + count; } if (pos + count > PrimaryAttributeRecord.DataLength) { PrimaryAttributeRecord.DataLength = pos + count; } if ((_attribute.Flags & (AttributeFlags.Compressed | AttributeFlags.Sparse)) != 0) { PrimaryAttributeRecord.CompressedDataSize -= releasedClusters * _bytesPerCluster; } _cookedRuns.CollapseRuns(); } private static CookedDataRuns CookRuns(NtfsAttribute attribute) { CookedDataRuns result = new CookedDataRuns(); foreach (NonResidentAttributeRecord record in attribute.Records) { if (record.StartVcn != result.NextVirtualCluster) { throw new IOException("Invalid NTFS attribute - non-contiguous data runs"); } result.Append(record.DataRuns, record); } return result; } private void InitializeData(long pos) { long initDataLen = PrimaryAttributeRecord.InitializedDataLength; _file.MarkMftRecordDirty(); int clustersAllocated = 0; while (initDataLen < pos) { long vcn = initDataLen / _bytesPerCluster; if (initDataLen % _bytesPerCluster != 0 || pos - initDataLen < _bytesPerCluster) { int clusterOffset = (int)(initDataLen - (vcn * _bytesPerCluster)); int toClear = (int)Math.Min(_bytesPerCluster - clusterOffset, pos - initDataLen); if (_activeStream.IsClusterStored(vcn)) { _activeStream.ReadClusters(vcn, 1, _ioBuffer, 0); Array.Clear(_ioBuffer, clusterOffset, toClear); clustersAllocated += _activeStream.WriteClusters(vcn, 1, _ioBuffer, 0); } initDataLen += toClear; } else { int numClusters = (int)((pos / _bytesPerCluster) - vcn); clustersAllocated -= _activeStream.ClearClusters(vcn, numClusters); initDataLen += numClusters * _bytesPerCluster; } } PrimaryAttributeRecord.InitializedDataLength = pos; if ((_attribute.Flags & (AttributeFlags.Compressed | AttributeFlags.Sparse)) != 0) { PrimaryAttributeRecord.CompressedDataSize += clustersAllocated * _bytesPerCluster; } } private void Truncate(long value) { long endVcn = Utilities.Ceil(value, _bytesPerCluster); // Release the clusters _activeStream.TruncateToClusters(endVcn); // First, remove any extents that are now redundant. Dictionary<AttributeReference, AttributeRecord> extentCache = new Dictionary<AttributeReference, AttributeRecord>(_attribute.Extents); foreach (var extent in extentCache) { if (extent.Value.StartVcn >= endVcn) { NonResidentAttributeRecord record = (NonResidentAttributeRecord)extent.Value; _file.RemoveAttributeExtent(extent.Key); _attribute.RemoveExtentCacheSafe(extent.Key); } } PrimaryAttributeRecord.LastVcn = Math.Max(0, endVcn - 1); PrimaryAttributeRecord.AllocatedLength = endVcn * _bytesPerCluster; PrimaryAttributeRecord.DataLength = value; PrimaryAttributeRecord.InitializedDataLength = Math.Min(PrimaryAttributeRecord.InitializedDataLength, value); _file.MarkMftRecordDirty(); } } }
using Discord.Audio; using Discord.Rest; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using Model = Discord.API.Channel; using UserModel = Discord.API.User; using VoiceStateModel = Discord.API.VoiceState; namespace Discord.WebSocket { /// <summary> /// Represents a WebSocket-based private group channel. /// </summary> [DebuggerDisplay(@"{DebuggerDisplay,nq}")] public class SocketGroupChannel : SocketChannel, IGroupChannel, ISocketPrivateChannel, ISocketMessageChannel, ISocketAudioChannel { private readonly MessageCache _messages; private readonly ConcurrentDictionary<ulong, SocketVoiceState> _voiceStates; private string _iconId; private ConcurrentDictionary<ulong, SocketGroupUser> _users; /// <inheritdoc /> public string Name { get; private set; } /// <inheritdoc /> public IReadOnlyCollection<SocketMessage> CachedMessages => _messages?.Messages ?? ImmutableArray.Create<SocketMessage>(); public new IReadOnlyCollection<SocketGroupUser> Users => _users.ToReadOnlyCollection(); public IReadOnlyCollection<SocketGroupUser> Recipients => _users.Select(x => x.Value).Where(x => x.Id != Discord.CurrentUser.Id).ToReadOnlyCollection(() => _users.Count - 1); internal SocketGroupChannel(DiscordSocketClient discord, ulong id) : base(discord, id) { if (Discord.MessageCacheSize > 0) _messages = new MessageCache(Discord); _voiceStates = new ConcurrentDictionary<ulong, SocketVoiceState>(ConcurrentHashSet.DefaultConcurrencyLevel, 5); _users = new ConcurrentDictionary<ulong, SocketGroupUser>(ConcurrentHashSet.DefaultConcurrencyLevel, 5); } internal static SocketGroupChannel Create(DiscordSocketClient discord, ClientState state, Model model) { var entity = new SocketGroupChannel(discord, model.Id); entity.Update(state, model); return entity; } internal override void Update(ClientState state, Model model) { if (model.Name.IsSpecified) Name = model.Name.Value; if (model.Icon.IsSpecified) _iconId = model.Icon.Value; if (model.Recipients.IsSpecified) UpdateUsers(state, model.Recipients.Value); } private void UpdateUsers(ClientState state, UserModel[] models) { var users = new ConcurrentDictionary<ulong, SocketGroupUser>(ConcurrentHashSet.DefaultConcurrencyLevel, (int)(models.Length * 1.05)); for (int i = 0; i < models.Length; i++) users[models[i].Id] = SocketGroupUser.Create(this, state, models[i]); _users = users; } /// <inheritdoc /> public Task LeaveAsync(RequestOptions options = null) => ChannelHelper.DeleteAsync(this, Discord, options); /// <exception cref="NotSupportedException">Voice is not yet supported for group channels.</exception> public Task<IAudioClient> ConnectAsync() { throw new NotSupportedException("Voice is not yet supported for group channels."); } //Messages /// <inheritdoc /> public SocketMessage GetCachedMessage(ulong id) => _messages?.Get(id); /// <summary> /// Gets a message from this message channel. /// </summary> /// <remarks> /// This method follows the same behavior as described in <see cref="IMessageChannel.GetMessageAsync"/>. /// Please visit its documentation for more details on this method. /// </remarks> /// <param name="id">The snowflake identifier of the message.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents an asynchronous get operation for retrieving the message. The task result contains /// the retrieved message; <c>null</c> if no message is found with the specified identifier. /// </returns> public async Task<IMessage> GetMessageAsync(ulong id, RequestOptions options = null) { IMessage msg = _messages?.Get(id); if (msg == null) msg = await ChannelHelper.GetMessageAsync(this, Discord, id, options).ConfigureAwait(false); return msg; } /// <summary> /// Gets the last N messages from this message channel. /// </summary> /// <remarks> /// This method follows the same behavior as described in <see cref="IMessageChannel.GetMessagesAsync(int, CacheMode, RequestOptions)"/>. /// Please visit its documentation for more details on this method. /// </remarks> /// <param name="limit">The numbers of message to be gotten from.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// Paged collection of messages. /// </returns> public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null) => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, null, Direction.Before, limit, CacheMode.AllowDownload, options); /// <summary> /// Gets a collection of messages in this channel. /// </summary> /// <remarks> /// This method follows the same behavior as described in <see cref="IMessageChannel.GetMessagesAsync(ulong, Direction, int, CacheMode, RequestOptions)"/>. /// Please visit its documentation for more details on this method. /// </remarks> /// <param name="fromMessageId">The ID of the starting message to get the messages from.</param> /// <param name="dir">The direction of the messages to be gotten from.</param> /// <param name="limit">The numbers of message to be gotten from.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// Paged collection of messages. /// </returns> public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null) => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessageId, dir, limit, CacheMode.AllowDownload, options); /// <summary> /// Gets a collection of messages in this channel. /// </summary> /// <remarks> /// This method follows the same behavior as described in <see cref="IMessageChannel.GetMessagesAsync(IMessage, Direction, int, CacheMode, RequestOptions)"/>. /// Please visit its documentation for more details on this method. /// </remarks> /// <param name="fromMessage">The starting message to get the messages from.</param> /// <param name="dir">The direction of the messages to be gotten from.</param> /// <param name="limit">The numbers of message to be gotten from.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// Paged collection of messages. /// </returns> public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null) => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessage.Id, dir, limit, CacheMode.AllowDownload, options); /// <inheritdoc /> public IReadOnlyCollection<SocketMessage> GetCachedMessages(int limit = DiscordConfig.MaxMessagesPerBatch) => SocketChannelHelper.GetCachedMessages(this, Discord, _messages, null, Direction.Before, limit); /// <inheritdoc /> public IReadOnlyCollection<SocketMessage> GetCachedMessages(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch) => SocketChannelHelper.GetCachedMessages(this, Discord, _messages, fromMessageId, dir, limit); /// <inheritdoc /> public IReadOnlyCollection<SocketMessage> GetCachedMessages(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch) => SocketChannelHelper.GetCachedMessages(this, Discord, _messages, fromMessage.Id, dir, limit); /// <inheritdoc /> public Task<IReadOnlyCollection<RestMessage>> GetPinnedMessagesAsync(RequestOptions options = null) => ChannelHelper.GetPinnedMessagesAsync(this, Discord, options); /// <inheritdoc /> /// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception> public Task<RestUserMessage> SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null) => ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, allowedMentions, messageReference, options); /// <inheritdoc /> public Task<RestUserMessage> SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) => ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, allowedMentions, messageReference, options, isSpoiler); /// <inheritdoc /> public Task<RestUserMessage> SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) => ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, allowedMentions, messageReference, options, isSpoiler); /// <inheritdoc /> public Task DeleteMessageAsync(ulong messageId, RequestOptions options = null) => ChannelHelper.DeleteMessageAsync(this, messageId, Discord, options); /// <inheritdoc /> public Task DeleteMessageAsync(IMessage message, RequestOptions options = null) => ChannelHelper.DeleteMessageAsync(this, message.Id, Discord, options); /// <inheritdoc /> public Task TriggerTypingAsync(RequestOptions options = null) => ChannelHelper.TriggerTypingAsync(this, Discord, options); /// <inheritdoc /> public IDisposable EnterTypingState(RequestOptions options = null) => ChannelHelper.EnterTypingState(this, Discord, options); internal void AddMessage(SocketMessage msg) => _messages?.Add(msg); internal SocketMessage RemoveMessage(ulong id) => _messages?.Remove(id); //Users /// <summary> /// Gets a user from this group. /// </summary> /// <param name="id">The snowflake identifier of the user.</param> /// <returns> /// A WebSocket-based group user associated with the snowflake identifier. /// </returns> public new SocketGroupUser GetUser(ulong id) { if (_users.TryGetValue(id, out SocketGroupUser user)) return user; return null; } internal SocketGroupUser GetOrAddUser(UserModel model) { if (_users.TryGetValue(model.Id, out SocketGroupUser user)) return user; else { var privateUser = SocketGroupUser.Create(this, Discord.State, model); privateUser.GlobalUser.AddRef(); _users[privateUser.Id] = privateUser; return privateUser; } } internal SocketGroupUser RemoveUser(ulong id) { if (_users.TryRemove(id, out SocketGroupUser user)) { user.GlobalUser.RemoveRef(Discord); return user; } return null; } //Voice States internal SocketVoiceState AddOrUpdateVoiceState(ClientState state, VoiceStateModel model) { var voiceChannel = state.GetChannel(model.ChannelId.Value) as SocketVoiceChannel; var voiceState = SocketVoiceState.Create(voiceChannel, model); _voiceStates[model.UserId] = voiceState; return voiceState; } internal SocketVoiceState? GetVoiceState(ulong id) { if (_voiceStates.TryGetValue(id, out SocketVoiceState voiceState)) return voiceState; return null; } internal SocketVoiceState? RemoveVoiceState(ulong id) { if (_voiceStates.TryRemove(id, out SocketVoiceState voiceState)) return voiceState; return null; } /// <summary> /// Returns the name of the group. /// </summary> public override string ToString() => Name; private string DebuggerDisplay => $"{Name} ({Id}, Group)"; internal new SocketGroupChannel Clone() => MemberwiseClone() as SocketGroupChannel; //SocketChannel /// <inheritdoc /> internal override IReadOnlyCollection<SocketUser> GetUsersInternal() => Users; /// <inheritdoc /> internal override SocketUser GetUserInternal(ulong id) => GetUser(id); //ISocketPrivateChannel /// <inheritdoc /> IReadOnlyCollection<SocketUser> ISocketPrivateChannel.Recipients => Recipients; //IPrivateChannel /// <inheritdoc /> IReadOnlyCollection<IUser> IPrivateChannel.Recipients => Recipients; //IMessageChannel /// <inheritdoc /> async Task<IMessage> IMessageChannel.GetMessageAsync(ulong id, CacheMode mode, RequestOptions options) { if (mode == CacheMode.AllowDownload) return await GetMessageAsync(id, options).ConfigureAwait(false); else return GetCachedMessage(id); } /// <inheritdoc /> IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options) => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, null, Direction.Before, limit, mode, options); /// <inheritdoc /> IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(ulong fromMessageId, Direction dir, int limit, CacheMode mode, RequestOptions options) => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessageId, dir, limit, mode, options); /// <inheritdoc /> IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(IMessage fromMessage, Direction dir, int limit, CacheMode mode, RequestOptions options) => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessage.Id, dir, limit, mode, options); /// <inheritdoc /> async Task<IReadOnlyCollection<IMessage>> IMessageChannel.GetPinnedMessagesAsync(RequestOptions options) => await GetPinnedMessagesAsync(options).ConfigureAwait(false); /// <inheritdoc /> async Task<IUserMessage> IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions, MessageReference messageReference) => await SendFileAsync(filePath, text, isTTS, embed, options, isSpoiler, allowedMentions, messageReference).ConfigureAwait(false); /// <inheritdoc /> async Task<IUserMessage> IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions, MessageReference messageReference) => await SendFileAsync(stream, filename, text, isTTS, embed, options, isSpoiler, allowedMentions, messageReference).ConfigureAwait(false); /// <inheritdoc /> async Task<IUserMessage> IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options, AllowedMentions allowedMentions, MessageReference messageReference) => await SendMessageAsync(text, isTTS, embed, options, allowedMentions, messageReference).ConfigureAwait(false); //IAudioChannel /// <inheritdoc /> /// <exception cref="NotSupportedException">Connecting to a group channel is not supported.</exception> Task<IAudioClient> IAudioChannel.ConnectAsync(bool selfDeaf, bool selfMute, bool external) { throw new NotSupportedException(); } Task IAudioChannel.DisconnectAsync() { throw new NotSupportedException(); } //IChannel /// <inheritdoc /> Task<IUser> IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) => Task.FromResult<IUser>(GetUser(id)); /// <inheritdoc /> IAsyncEnumerable<IReadOnlyCollection<IUser>> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options) => ImmutableArray.Create<IReadOnlyCollection<IUser>>(Users).ToAsyncEnumerable(); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace System.Numerics.Tests { public class BigIntegerConstructorTest { private static int s_samples = 10; private static Random s_random = new Random(100); [Fact] public static void RunCtorInt32Tests() { // ctor(Int32): Int32.MinValue VerifyCtorInt32(Int32.MinValue); // ctor(Int32): -1 VerifyCtorInt32((Int32)(-1)); // ctor(Int32): 0 VerifyCtorInt32((Int32)0); // ctor(Int32): 1 VerifyCtorInt32((Int32)1); // ctor(Int32): Int32.MaxValue VerifyCtorInt32(Int32.MaxValue); // ctor(Int32): Random Positive for (int i = 0; i < s_samples; ++i) { VerifyCtorInt32((Int32)s_random.Next(1, Int32.MaxValue)); } // ctor(Int32): Random Negative for (int i = 0; i < s_samples; ++i) { VerifyCtorInt32((Int32)s_random.Next(Int32.MinValue, 0)); } } private static void VerifyCtorInt32(Int32 value) { BigInteger bigInteger = new BigInteger(value); Assert.Equal(value, bigInteger); Assert.Equal(0, String.CompareOrdinal(value.ToString(), bigInteger.ToString())); Assert.Equal(value, (Int32)bigInteger); if (value != Int32.MaxValue) { Assert.Equal((Int32)(value + 1), (Int32)(bigInteger + 1)); } if (value != Int32.MinValue) { Assert.Equal((Int32)(value - 1), (Int32)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } [Fact] public static void RunCtorInt64Tests() { // ctor(Int64): Int64.MinValue VerifyCtorInt64(Int64.MinValue); // ctor(Int64): Int32.MinValue-1 VerifyCtorInt64(((Int64)Int32.MinValue) - 1); // ctor(Int64): Int32.MinValue VerifyCtorInt64((Int64)Int32.MinValue); // ctor(Int64): -1 VerifyCtorInt64((Int64)(-1)); // ctor(Int64): 0 VerifyCtorInt64((Int64)0); // ctor(Int64): 1 VerifyCtorInt64((Int64)1); // ctor(Int64): Int32.MaxValue VerifyCtorInt64((Int64)Int32.MaxValue); // ctor(Int64): Int32.MaxValue+1 VerifyCtorInt64(((Int64)Int32.MaxValue) + 1); // ctor(Int64): Int64.MaxValue VerifyCtorInt64(Int64.MaxValue); // ctor(Int64): Random Positive for (int i = 0; i < s_samples; ++i) { VerifyCtorInt64((Int64)(Int64.MaxValue * s_random.NextDouble())); } // ctor(Int64): Random Negative for (int i = 0; i < s_samples; ++i) { VerifyCtorInt64((Int64)(Int64.MaxValue * s_random.NextDouble()) - Int64.MaxValue); } } private static void VerifyCtorInt64(Int64 value) { BigInteger bigInteger = new BigInteger(value); Assert.Equal(value, bigInteger); Assert.Equal(0, String.CompareOrdinal(value.ToString(), bigInteger.ToString())); Assert.Equal(value, (Int64)bigInteger); if (value != Int64.MaxValue) { Assert.Equal((Int64)(value + 1), (Int64)(bigInteger + 1)); } if (value != Int64.MinValue) { Assert.Equal((Int64)(value - 1), (Int64)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } [Fact] public static void RunCtorUInt32Tests() { // ctor(UInt32): UInt32.MinValue VerifyCtorUInt32(UInt32.MinValue); // ctor(UInt32): 0 VerifyCtorUInt32((UInt32)0); // ctor(UInt32): 1 VerifyCtorUInt32((UInt32)1); // ctor(UInt32): Int32.MaxValue VerifyCtorUInt32((UInt32)Int32.MaxValue); // ctor(UInt32): Int32.MaxValue+1 VerifyCtorUInt32(((UInt32)Int32.MaxValue) + 1); // ctor(UInt32): UInt32.MaxValue VerifyCtorUInt32(UInt32.MaxValue); // ctor(UInt32): Random Positive for (int i = 0; i < s_samples; ++i) { VerifyCtorUInt32((UInt32)(UInt32.MaxValue * s_random.NextDouble())); } } private static void VerifyCtorUInt32(UInt32 value) { BigInteger bigInteger = new BigInteger(value); Assert.Equal(value, bigInteger); Assert.Equal(0, String.CompareOrdinal(value.ToString(), bigInteger.ToString())); Assert.Equal(value, (UInt32)bigInteger); if (value != UInt32.MaxValue) { Assert.Equal((UInt32)(value + 1), (UInt32)(bigInteger + 1)); } if (value != UInt32.MinValue) { Assert.Equal((UInt32)(value - 1), (UInt32)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } [Fact] public static void RunCtorUInt64Tests() { // ctor(UInt64): UInt64.MinValue VerifyCtorUInt64(UInt64.MinValue); // ctor(UInt64): 0 VerifyCtorUInt64((UInt64)0); // ctor(UInt64): 1 VerifyCtorUInt64((UInt64)1); // ctor(UInt64): Int32.MaxValue VerifyCtorUInt64((UInt64)Int32.MaxValue); // ctor(UInt64): Int32.MaxValue+1 VerifyCtorUInt64(((UInt64)Int32.MaxValue) + 1); // ctor(UInt64): UInt64.MaxValue VerifyCtorUInt64(UInt64.MaxValue); // ctor(UInt64): Random Positive for (int i = 0; i < s_samples; ++i) { VerifyCtorUInt64((UInt64)(UInt64.MaxValue * s_random.NextDouble())); } } private static void VerifyCtorUInt64(UInt64 value) { BigInteger bigInteger = new BigInteger(value); Assert.Equal(value, bigInteger); Assert.Equal(0, String.CompareOrdinal(value.ToString(), bigInteger.ToString())); Assert.Equal(value, (UInt64)bigInteger); if (value != UInt64.MaxValue) { Assert.Equal((UInt64)(value + 1), (UInt64)(bigInteger + 1)); } if (value != UInt64.MinValue) { Assert.Equal((UInt64)(value - 1), (UInt64)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == value); } [Fact] public static void RunCtorSingleTests() { // ctor(Single): Single.Minvalue VerifyCtorSingle(Single.MinValue); // ctor(Single): Int32.MinValue-1 VerifyCtorSingle(((Single)Int32.MinValue) - 1); // ctor(Single): Int32.MinValue VerifyCtorSingle(((Single)Int32.MinValue)); // ctor(Single): Int32.MinValue+1 VerifyCtorSingle(((Single)Int32.MinValue) + 1); // ctor(Single): -1 VerifyCtorSingle((Single)(-1)); // ctor(Single): 0 VerifyCtorSingle((Single)0); // ctor(Single): 1 VerifyCtorSingle((Single)1); // ctor(Single): Int32.MaxValue-1 VerifyCtorSingle(((Single)Int32.MaxValue) - 1); // ctor(Single): Int32.MaxValue VerifyCtorSingle(((Single)Int32.MaxValue)); // ctor(Single): Int32.MaxValue+1 VerifyCtorSingle(((Single)Int32.MaxValue) + 1); // ctor(Single): Single.MaxValue VerifyCtorSingle(Single.MaxValue); // ctor(Single): Random Positive for (int i = 0; i < s_samples; i++) { VerifyCtorSingle((Single)(Single.MaxValue * s_random.NextDouble())); } // ctor(Single): Random Negative for (int i = 0; i < s_samples; i++) { VerifyCtorSingle(((Single)(Single.MaxValue * s_random.NextDouble())) - Single.MaxValue); } // ctor(Single): Small Random Positive with fractional part for (int i = 0; i < s_samples; i++) { VerifyCtorSingle((Single)(s_random.Next(0, 100) + s_random.NextDouble())); } // ctor(Single): Small Random Negative with fractional part for (int i = 0; i < s_samples; i++) { VerifyCtorSingle(((Single)(s_random.Next(-100, 0) - s_random.NextDouble()))); } // ctor(Single): Large Random Positive with fractional part for (int i = 0; i < s_samples; i++) { VerifyCtorSingle((Single)((Single.MaxValue * s_random.NextDouble()) + s_random.NextDouble())); } // ctor(Single): Large Random Negative with fractional part for (int i = 0; i < s_samples; i++) { VerifyCtorSingle(((Single)((-(Single.MaxValue - 1) * s_random.NextDouble()) - s_random.NextDouble()))); } // ctor(Single): Single.Epsilon VerifyCtorSingle(Single.Epsilon); // ctor(Single): Single.NegativeInfinity Assert.Throws<OverflowException>(() => new BigInteger(Single.NegativeInfinity)); // ctor(Single): Single.PositiveInfinity Assert.Throws<OverflowException>(() => { BigInteger temp = new BigInteger(Single.PositiveInfinity); }); // ctor(Single): Single.NaN Assert.Throws<OverflowException>(() => { BigInteger temp = new BigInteger(Single.NaN); }); // ctor(Single): Single.NaN 2 Assert.Throws<OverflowException>(() => { BigInteger temp = new BigInteger(ConvertInt32ToSingle(0x7FC00000)); }); // ctor(Single): Smallest Exponent VerifyCtorSingle((Single)Math.Pow(2, -126)); // ctor(Single): Largest Exponent VerifyCtorSingle((Single)Math.Pow(2, 127)); // ctor(Single): Largest number less than 1 Single value = 0; for (int i = 1; i <= 24; ++i) { value += (Single)(Math.Pow(2, -i)); } VerifyCtorSingle(value); // ctor(Single): Smallest number greater than 1 value = (Single)(1 + Math.Pow(2, -23)); VerifyCtorSingle(value); // ctor(Single): Largest number less than 2 value = 0; for (int i = 1; i <= 23; ++i) { value += (Single)(Math.Pow(2, -i)); } value += 1; VerifyCtorSingle(value); } private static void VerifyCtorSingle(Single value) { BigInteger bigInteger = new BigInteger(value); Single expectedValue; if (value < 0) { expectedValue = (Single)Math.Ceiling(value); } else { expectedValue = (Single)Math.Floor(value); } Assert.Equal(expectedValue, (Single)bigInteger); // Single can only accurately represent integers between -16777216 and 16777216 exclusive. // ToString starts to become inaccurate at this point. if (expectedValue < 16777216 && -16777216 < expectedValue) { Assert.True(expectedValue.ToString("G9").Equals(bigInteger.ToString(), StringComparison.OrdinalIgnoreCase), "Single.ToString() and BigInteger.ToString() not equal"); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == expectedValue); } [Fact] public static void RunCtorDoubleTests() { // ctor(Double): Double.Minvalue VerifyCtorDouble(Double.MinValue); // ctor(Double): Single.Minvalue VerifyCtorDouble((Double)Single.MinValue); // ctor(Double): Int64.MinValue-1 VerifyCtorDouble(((Double)Int64.MinValue) - 1); // ctor(Double): Int64.MinValue VerifyCtorDouble(((Double)Int64.MinValue)); // ctor(Double): Int64.MinValue+1 VerifyCtorDouble(((Double)Int64.MinValue) + 1); // ctor(Double): Int32.MinValue-1 VerifyCtorDouble(((Double)Int32.MinValue) - 1); // ctor(Double): Int32.MinValue VerifyCtorDouble(((Double)Int32.MinValue)); // ctor(Double): Int32.MinValue+1 VerifyCtorDouble(((Double)Int32.MinValue) + 1); // ctor(Double): -1 VerifyCtorDouble((Double)(-1)); // ctor(Double): 0 VerifyCtorDouble((Double)0); // ctor(Double): 1 VerifyCtorDouble((Double)1); // ctor(Double): Int32.MaxValue-1 VerifyCtorDouble(((Double)Int32.MaxValue) - 1); // ctor(Double): Int32.MaxValue VerifyCtorDouble(((Double)Int32.MaxValue)); // ctor(Double): Int32.MaxValue+1 VerifyCtorDouble(((Double)Int32.MaxValue) + 1); // ctor(Double): Int64.MaxValue-1 VerifyCtorDouble(((Double)Int64.MaxValue) - 1); // ctor(Double): Int64.MaxValue VerifyCtorDouble(((Double)Int64.MaxValue)); // ctor(Double): Int64.MaxValue+1 VerifyCtorDouble(((Double)Int64.MaxValue) + 1); // ctor(Double): Single.MaxValue VerifyCtorDouble((Double)Single.MaxValue); // ctor(Double): Double.MaxValue VerifyCtorDouble(Double.MaxValue); // ctor(Double): Random Positive for (int i = 0; i < s_samples; i++) { VerifyCtorDouble((Double)(Double.MaxValue * s_random.NextDouble())); } // ctor(Double): Random Negative for (int i = 0; i < s_samples; i++) { VerifyCtorDouble((Double.MaxValue * s_random.NextDouble()) - Double.MaxValue); } // ctor(Double): Small Random Positive with fractional part for (int i = 0; i < s_samples; i++) { VerifyCtorDouble((Double)(s_random.Next(0, 100) + s_random.NextDouble())); } // ctor(Double): Small Random Negative with fractional part for (int i = 0; i < s_samples; i++) { VerifyCtorDouble(((Double)(s_random.Next(-100, 0) - s_random.NextDouble()))); } // ctor(Double): Large Random Positive with fractional part for (int i = 0; i < s_samples; i++) { VerifyCtorDouble((Double)((Int64.MaxValue / 100 * s_random.NextDouble()) + s_random.NextDouble())); } // ctor(Double): Large Random Negative with fractional part for (int i = 0; i < s_samples; i++) { VerifyCtorDouble(((Double)((-(Int64.MaxValue / 100) * s_random.NextDouble()) - s_random.NextDouble()))); } // ctor(Double): Double.Epsilon VerifyCtorDouble(Double.Epsilon); // ctor(Double): Double.NegativeInfinity Assert.Throws<OverflowException>(() => { BigInteger temp = new BigInteger(Double.NegativeInfinity); }); // ctor(Double): Double.PositiveInfinity Assert.Throws<OverflowException>(() => { BigInteger temp = new BigInteger(Double.PositiveInfinity); }); // ctor(Double): Double.NaN Assert.Throws<OverflowException>(() => { BigInteger temp = new BigInteger(Double.NaN); }); // ctor(Double): Double.NaN 2 Assert.Throws<OverflowException>(() => { BigInteger temp = new BigInteger(ConvertInt64ToDouble(0x7FF8000000000000)); }); // ctor(Double): Smallest Exponent VerifyCtorDouble((Double)Math.Pow(2, -1022)); // ctor(Double): Largest Exponent VerifyCtorDouble((Double)Math.Pow(2, 1023)); // ctor(Double): Largest number less than 1 Double value = 0; for (int i = 1; i <= 53; ++i) { value += (Double)(Math.Pow(2, -i)); } VerifyCtorDouble(value); // ctor(Double): Smallest number greater than 1 value = (Double)(1 + Math.Pow(2, -52)); VerifyCtorDouble(value); // ctor(Double): Largest number less than 2 value = 0; for (int i = 1; i <= 52; ++i) { value += (Double)(Math.Pow(2, -i)); } value += 2; VerifyCtorDouble(value); } private static void VerifyCtorDouble(Double value) { BigInteger bigInteger = new BigInteger(value); Double expectedValue; if (value < 0) { expectedValue = (Double)Math.Ceiling(value); } else { expectedValue = (Double)Math.Floor(value); } Assert.Equal(expectedValue, (Double)bigInteger); // Single can only accurately represent integers between -16777216 and 16777216 exclusive. // ToString starts to become inaccurate at this point. if (expectedValue < 9007199254740992 && -9007199254740992 < expectedValue) { Assert.True(expectedValue.ToString("G17").Equals(bigInteger.ToString(), StringComparison.OrdinalIgnoreCase), "Double.ToString() and BigInteger.ToString() not equal"); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == expectedValue); } [Fact] public static void RunCtorDecimalTests() { Decimal value; // ctor(Decimal): Decimal.MinValue VerifyCtorDecimal(Decimal.MinValue); // ctor(Decimal): -1 VerifyCtorDecimal(-1); // ctor(Decimal): 0 VerifyCtorDecimal(0); // ctor(Decimal): 1 VerifyCtorDecimal(1); // ctor(Decimal): Decimal.MaxValue VerifyCtorDecimal(Decimal.MaxValue); // ctor(Decimal): Random Positive for (int i = 0; i < s_samples; i++) { value = new Decimal( s_random.Next(Int32.MinValue, Int32.MaxValue), s_random.Next(Int32.MinValue, Int32.MaxValue), s_random.Next(Int32.MinValue, Int32.MaxValue), false, (byte)s_random.Next(0, 29)); VerifyCtorDecimal(value); } // ctor(Decimal): Random Negative for (int i = 0; i < s_samples; i++) { value = new Decimal( s_random.Next(Int32.MinValue, Int32.MaxValue), s_random.Next(Int32.MinValue, Int32.MaxValue), s_random.Next(Int32.MinValue, Int32.MaxValue), true, (byte)s_random.Next(0, 29)); VerifyCtorDecimal(value); } // ctor(Decimal): Smallest Exponent unchecked { value = new Decimal(1, 0, 0, false, 0); } VerifyCtorDecimal(value); // ctor(Decimal): Largest Exponent and zero integer unchecked { value = new Decimal(0, 0, 0, false, 28); } VerifyCtorDecimal(value); // ctor(Decimal): Largest Exponent and non zero integer unchecked { value = new Decimal(1, 0, 0, false, 28); } VerifyCtorDecimal(value); // ctor(Decimal): Largest number less than 1 value = 1 - new Decimal(1, 0, 0, false, 28); VerifyCtorDecimal(value); // ctor(Decimal): Smallest number greater than 1 value = 1 + new Decimal(1, 0, 0, false, 28); VerifyCtorDecimal(value); // ctor(Decimal): Largest number less than 2 value = 2 - new Decimal(1, 0, 0, false, 28); VerifyCtorDecimal(value); } private static void VerifyCtorDecimal(Decimal value) { BigInteger bigInteger = new BigInteger(value); Decimal expectedValue; if (value < 0) { expectedValue = Math.Ceiling(value); } else { expectedValue = Math.Floor(value); } Assert.True(expectedValue.ToString().Equals(bigInteger.ToString(), StringComparison.OrdinalIgnoreCase), "Decimal.ToString() and BigInteger.ToString()"); Assert.Equal(expectedValue, (Decimal)bigInteger); if (expectedValue != Math.Floor(Decimal.MaxValue)) { Assert.Equal((Decimal)(expectedValue + 1), (Decimal)(bigInteger + 1)); } if (expectedValue != Math.Ceiling(Decimal.MinValue)) { Assert.Equal((Decimal)(expectedValue - 1), (Decimal)(bigInteger - 1)); } VerifyBigIntegerUsingIdentities(bigInteger, 0 == expectedValue); } [Fact] public static void RunCtorByteArrayTests() { UInt64 tempUInt64; byte[] tempByteArray; // ctor(byte[]): array is null Assert.Throws<ArgumentNullException>(() => { BigInteger bigInteger = new BigInteger((byte[])null); }); // ctor(byte[]): array is empty VerifyCtorByteArray(new byte[0], 0); // ctor(byte[]): array is 1 byte tempUInt64 = (UInt32)s_random.Next(0, 256); tempByteArray = BitConverter.GetBytes(tempUInt64); if (tempByteArray[0] > 127) { VerifyCtorByteArray(new byte[] { tempByteArray[0] }); VerifyCtorByteArray(new byte[] { tempByteArray[0], 0 }, tempUInt64); } else { VerifyCtorByteArray(new byte[] { tempByteArray[0] }, tempUInt64); } // ctor(byte[]): Small array with all zeros VerifyCtorByteArray(new byte[] { 0, 0, 0, 0 }); // ctor(byte[]): Large array with all zeros VerifyCtorByteArray( new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }); // ctor(byte[]): Small array with all ones VerifyCtorByteArray(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF }); // ctor(byte[]): Large array with all ones VerifyCtorByteArray( new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }); // ctor(byte[]): array with a lot of leading zeros for (int i = 0; i < s_samples; i++) { tempUInt64 = (UInt32)s_random.Next(Int32.MinValue, Int32.MaxValue); tempByteArray = BitConverter.GetBytes(tempUInt64); VerifyCtorByteArray( new byte[] { tempByteArray[0], tempByteArray[1], tempByteArray[2], tempByteArray[3], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, tempUInt64); } // ctor(byte[]): array 4 bytes for (int i = 0; i < s_samples; i++) { tempUInt64 = (UInt32)s_random.Next(Int32.MinValue, Int32.MaxValue); tempByteArray = BitConverter.GetBytes(tempUInt64); if (tempUInt64 > Int32.MaxValue) { VerifyCtorByteArray( new byte[] { tempByteArray[0], tempByteArray[1], tempByteArray[2], tempByteArray[3] }); VerifyCtorByteArray( new byte[] { tempByteArray[0], tempByteArray[1], tempByteArray[2], tempByteArray[3], 0 }, tempUInt64); } else { VerifyCtorByteArray( new byte[] { tempByteArray[0], tempByteArray[1], tempByteArray[2], tempByteArray[3] }, tempUInt64); } } // ctor(byte[]): array 5 bytes for (int i = 0; i < s_samples; i++) { tempUInt64 = (UInt32)s_random.Next(Int32.MinValue, Int32.MaxValue); tempUInt64 <<= 8; tempUInt64 += (UInt64)s_random.Next(0, 256); tempByteArray = BitConverter.GetBytes(tempUInt64); if (tempUInt64 >= (UInt64)0x00080000) { VerifyCtorByteArray( new byte[] { tempByteArray[0], tempByteArray[1], tempByteArray[2], tempByteArray[3], tempByteArray[4] }); VerifyCtorByteArray( new byte[] { tempByteArray[0], tempByteArray[1], tempByteArray[2], tempByteArray[3], tempByteArray[4], 0 }, tempUInt64); } else { VerifyCtorByteArray( new byte[] { tempByteArray[0], tempByteArray[1], tempByteArray[2], tempByteArray[3], tempByteArray[4] }, tempUInt64); } } // ctor(byte[]): array 8 bytes for (int i = 0; i < s_samples; i++) { tempUInt64 = (UInt32)s_random.Next(Int32.MinValue, Int32.MaxValue); tempUInt64 <<= 32; tempUInt64 += (UInt32)s_random.Next(Int32.MinValue, Int32.MaxValue); tempByteArray = BitConverter.GetBytes(tempUInt64); if (tempUInt64 > Int64.MaxValue) { VerifyCtorByteArray( new byte[] { tempByteArray[0], tempByteArray[1], tempByteArray[2], tempByteArray[3], tempByteArray[4], tempByteArray[5], tempByteArray[6], tempByteArray[7] }); VerifyCtorByteArray( new byte[] { tempByteArray[0], tempByteArray[1], tempByteArray[2], tempByteArray[3], tempByteArray[4], tempByteArray[5], tempByteArray[6], tempByteArray[7], 0 }, tempUInt64); } else { VerifyCtorByteArray( new byte[] { tempByteArray[0], tempByteArray[1], tempByteArray[2], tempByteArray[3], tempByteArray[4], tempByteArray[5], tempByteArray[6], tempByteArray[7] }, tempUInt64); } } // ctor(byte[]): array 9 bytes for (int i = 0; i < s_samples; i++) { VerifyCtorByteArray( new byte[] { (byte)s_random.Next(0, 256), (byte)s_random.Next(0, 256), (byte)s_random.Next(0, 256), (byte)s_random.Next(0, 256), (byte)s_random.Next(0, 256), (byte)s_random.Next(0, 256), (byte)s_random.Next(0, 256), (byte)s_random.Next(0, 256), (byte)s_random.Next(0, 256) }); } // ctor(byte[]): array is UInt32.MaxValue VerifyCtorByteArray(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0 }, UInt32.MaxValue); // ctor(byte[]): array is UInt32.MaxValue + 1 VerifyCtorByteArray(new byte[] { 0, 0, 0, 0, 1 }, (UInt64)UInt32.MaxValue + 1); // ctor(byte[]): array is UInt64.MaxValue VerifyCtorByteArray(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0 }, UInt64.MaxValue); // ctor(byte[]): UInt64.MaxValue + 1 VerifyCtorByteArray( new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 1 }); // ctor(byte[]): UInt64.MaxValue + 2^64 VerifyCtorByteArray( new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 1 }); // ctor(byte[]): array is random > UInt64 for (int i = 0; i < s_samples; i++) { tempByteArray = new byte[s_random.Next(0, 1024)]; for (int arrayIndex = 0; arrayIndex < tempByteArray.Length; ++arrayIndex) { tempByteArray[arrayIndex] = (byte)s_random.Next(0, 256); } VerifyCtorByteArray(tempByteArray); } // ctor(byte[]): array is large for (int i = 0; i < s_samples; i++) { tempByteArray = new byte[s_random.Next(16384, 2097152)]; for (int arrayIndex = 0; arrayIndex < tempByteArray.Length; ++arrayIndex) { tempByteArray[arrayIndex] = (byte)s_random.Next(0, 256); } VerifyCtorByteArray(tempByteArray); } } private static void VerifyCtorByteArray(byte[] value, UInt64 expectedValue) { BigInteger bigInteger = new BigInteger(value); Assert.Equal(expectedValue, bigInteger); Assert.True(expectedValue.ToString().Equals(bigInteger.ToString(), StringComparison.OrdinalIgnoreCase), "UInt64.ToString() and BigInteger.ToString()"); Assert.Equal(expectedValue, (UInt64)bigInteger); if (expectedValue != UInt64.MaxValue) { Assert.Equal((UInt64)(expectedValue + 1), (UInt64)(bigInteger + 1)); } if (expectedValue != UInt64.MinValue) { Assert.Equal((UInt64)(expectedValue - 1), (UInt64)(bigInteger - 1)); } VerifyCtorByteArray(value); } private static void VerifyCtorByteArray(byte[] value) { BigInteger bigInteger; byte[] roundTrippedByteArray; bool isZero = MyBigIntImp.IsZero(value); bigInteger = new BigInteger(value); roundTrippedByteArray = bigInteger.ToByteArray(); for (int i = Math.Min(value.Length, roundTrippedByteArray.Length) - 1; 0 <= i; --i) { Assert.True(value[i] == roundTrippedByteArray[i], String.Format("Round Tripped ByteArray at {0}", i)); } if (value.Length < roundTrippedByteArray.Length) { for (int i = value.Length; i < roundTrippedByteArray.Length; ++i) { Assert.True(0 == roundTrippedByteArray[i], String.Format("Round Tripped ByteArray is larger than the original array and byte is non zero at {0}", i)); } } else if (value.Length > roundTrippedByteArray.Length) { for (int i = roundTrippedByteArray.Length; i < value.Length; ++i) { Assert.False((((0 != value[i]) && ((roundTrippedByteArray[roundTrippedByteArray.Length - 1] & 0x80) == 0)) || ((0xFF != value[i]) && ((roundTrippedByteArray[roundTrippedByteArray.Length - 1] & 0x80) != 0))), String.Format("Round Tripped ByteArray is smaller than the original array and byte is non zero at {0}", i)); } } if (value.Length < 8) { byte[] newvalue = new byte[8]; for (int i = 0; i < 8; i++) { if (bigInteger < 0) { newvalue[i] = 0xFF; } else { newvalue[i] = 0; } } for (int i = 0; i < value.Length; i++) { newvalue[i] = value[i]; } value = newvalue; } else if (value.Length > 8) { int newlength = value.Length; for (; newlength > 8; newlength--) { if (bigInteger < 0) { if ((value[newlength - 1] != 0xFF) | ((value[newlength - 2] & 0x80) == 0)) { break; } } else { if ((value[newlength - 1] != 0) | ((value[newlength - 2] & 0x80) != 0)) { break; } } } byte[] newvalue = new byte[newlength]; for (int i = 0; i < newlength; i++) { newvalue[i] = value[i]; } value = newvalue; } if (IsOutOfRangeInt64(value)) { // Try subtracting a value from the BigInteger that will allow it to be represented as an Int64 byte[] tempByteArray; BigInteger tempBigInteger; bool isNeg = ((value[value.Length - 1] & 0x80) != 0); tempByteArray = new byte[value.Length]; Array.Copy(value, 8, tempByteArray, 8, value.Length - 8); tempBigInteger = bigInteger - (new BigInteger(tempByteArray)); tempByteArray = new byte[8]; Array.Copy(value, 0, tempByteArray, 0, 8); if (!(((tempByteArray[7] & 0x80) == 0) ^ isNeg)) { tempByteArray[7] ^= 0x80; tempBigInteger = tempBigInteger + (new BigInteger(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0x80 })); } if (isNeg & (tempBigInteger > 0)) { tempBigInteger = tempBigInteger + (new BigInteger(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0xFF })); } Assert.Equal(BitConverter.ToInt64(tempByteArray, 0), (Int64)tempBigInteger); } else { Assert.Equal(BitConverter.ToInt64(value, 0), (Int64)bigInteger); } if (IsOutOfRangeUInt64(value)) { // Try subtracting a value from the BigInteger that will allow it to be represented as an UInt64 byte[] tempByteArray; BigInteger tempBigInteger; bool isNeg = ((value[value.Length - 1] & 0x80) != 0); tempByteArray = new byte[value.Length]; Array.Copy(value, 8, tempByteArray, 8, value.Length - 8); tempBigInteger = bigInteger - (new BigInteger(tempByteArray)); tempByteArray = new byte[8]; Array.Copy(value, 0, tempByteArray, 0, 8); if ((tempByteArray[7] & 0x80) != 0) { tempByteArray[7] &= 0x7f; if (tempBigInteger < 0) { tempBigInteger = tempBigInteger - (new BigInteger(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0x80 })); } else { tempBigInteger = tempBigInteger + (new BigInteger(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0x80 })); } } Assert.Equal(BitConverter.ToUInt64(tempByteArray, 0), (UInt64)tempBigInteger); } else { Assert.Equal(BitConverter.ToUInt64(value, 0), (UInt64)bigInteger); } VerifyBigIntegerUsingIdentities(bigInteger, isZero); } private static Single ConvertInt32ToSingle(Int32 value) { return BitConverter.ToSingle(BitConverter.GetBytes(value), 0); } private static Double ConvertInt64ToDouble(Int64 value) { return BitConverter.ToDouble(BitConverter.GetBytes(value), 0); } private static void VerifyBigIntegerUsingIdentities(BigInteger bigInteger, bool isZero) { BigInteger tempBigInteger = new BigInteger(bigInteger.ToByteArray()); Assert.Equal(bigInteger, tempBigInteger); if (isZero) { Assert.Equal(BigInteger.Zero, bigInteger); } else { Assert.NotEqual(BigInteger.Zero, bigInteger); Assert.Equal(BigInteger.One, bigInteger / bigInteger); } // (x + 1) - 1 = x Assert.Equal(bigInteger, ((bigInteger + BigInteger.One) - BigInteger.One)); // (x + 1) - x = 1 Assert.Equal(BigInteger.One, ((bigInteger + BigInteger.One) - bigInteger)); // x - x = 0 Assert.Equal(BigInteger.Zero, (bigInteger - bigInteger)); // x + x = 2x Assert.Equal((2 * bigInteger), (bigInteger + bigInteger)); // x/1 = x Assert.Equal(bigInteger, (bigInteger / BigInteger.One)); // 1 * x = x Assert.Equal(bigInteger, (BigInteger.One * bigInteger)); } private static bool IsOutOfRangeUInt64(byte[] value) { if (value.Length == 0) { return false; } if ((0x80 & value[value.Length - 1]) != 0) { return true; } byte zeroValue = 0; if (value.Length <= 8) { return false; } for (int i = 8; i < value.Length; ++i) { if (zeroValue != value[i]) { return true; } } return false; } private static bool IsOutOfRangeInt64(byte[] value) { if (value.Length == 0) { return false; } bool isNeg = ((0x80 & value[value.Length - 1]) != 0); byte zeroValue = 0; if (isNeg) { zeroValue = 0xFF; } if (value.Length < 8) { return false; } for (int i = 8; i < value.Length; i++) { if (zeroValue != value[i]) { return true; } } return (!((0 == (0x80 & value[7])) ^ isNeg)); } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Reflection; using System.Text.RegularExpressions; using System.Xml; using Nini.Config; using OpenMetaverse; using Aurora.Framework; using Aurora.Framework.Capabilities; using Aurora.Simulation.Base; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using FriendInfo = OpenSim.Services.Interfaces.FriendInfo; using Aurora.DataManager; namespace OpenSim.Services.LLLoginService { public class LLLoginService : ILoginService, IService { private static bool Initialized = false; // Global Textures private const string sunTexture = "cce0f112-878f-4586-a2e2-a8f104bba271"; private const string cloudTexture = "dc4b9f0b-d008-45c6-96a4-01dd947ac621"; private const string moonTexture = "ec4b9f0b-d008-45c6-96a4-01dd947ac621"; protected IUserAccountService m_UserAccountService; protected IAgentInfoService m_agentInfoService; protected IAuthenticationService m_AuthenticationService; protected IInventoryService m_InventoryService; protected IGridService m_GridService; protected ISimulationService m_SimulationService; protected ILibraryService m_LibraryService; protected IFriendsService m_FriendsService; protected IAvatarService m_AvatarService; protected IAssetService m_AssetService; protected ICapsService m_CapsService; protected IAvatarAppearanceArchiver m_ArchiveService; protected IRegistryCore m_registry; protected string m_DefaultRegionName; protected string m_WelcomeMessage; protected string m_WelcomeMessageURL; protected bool m_RequireInventory; protected int m_MinLoginLevel; protected bool m_AllowRemoteSetLoginLevel; protected IConfig m_loginServerConfig; protected IConfigSource m_config; protected bool m_AllowAnonymousLogin = false; protected bool m_AllowDuplicateLogin = false; protected string m_DefaultUserAvatarArchive = "DefaultAvatar.aa"; protected string m_DefaultHomeRegion = ""; protected ArrayList eventCategories = new ArrayList(); protected ArrayList classifiedCategories = new ArrayList(); protected List<ILoginModule> LoginModules = new List<ILoginModule>(); private string m_forceUserToWearFolderName; private string m_forceUserToWearFolderOwnerUUID; public int MinLoginLevel { get { return m_MinLoginLevel; } } public void Initialize(IConfigSource config, IRegistryCore registry) { m_config = config; m_loginServerConfig = config.Configs["LoginService"]; IConfig handlersConfig = config.Configs["Handlers"]; if (handlersConfig == null || handlersConfig.GetString("LoginHandler", "") != "LLLoginService") return; m_forceUserToWearFolderName = m_loginServerConfig.GetString("forceUserToWearFolderName", ""); m_forceUserToWearFolderOwnerUUID = m_loginServerConfig.GetString("forceUserToWearFolderOwner", ""); m_DefaultHomeRegion = m_loginServerConfig.GetString("DefaultHomeRegion", ""); m_DefaultUserAvatarArchive = m_loginServerConfig.GetString("DefaultAvatarArchiveForNewUser", m_DefaultUserAvatarArchive); m_AllowAnonymousLogin = m_loginServerConfig.GetBoolean("AllowAnonymousLogin", false); m_AllowDuplicateLogin = m_loginServerConfig.GetBoolean("AllowDuplicateLogin", false); LLLoginResponseRegister.RegisterValue("AllowFirstLife", m_loginServerConfig.GetBoolean("AllowFirstLifeInProfile", true) ? "Y" : "N"); LLLoginResponseRegister.RegisterValue("MaxAgentGroups", m_loginServerConfig.GetInt("MaxAgentGroups", 100)); LLLoginResponseRegister.RegisterValue("VoiceServerType", m_loginServerConfig.GetString("VoiceServerType", "vivox")); ReadEventValues(m_loginServerConfig); ReadClassifiedValues(m_loginServerConfig); LLLoginResponseRegister.RegisterValue("AllowExportPermission", m_loginServerConfig.GetBoolean("AllowUsageOfExportPermissions", true)); m_DefaultRegionName = m_loginServerConfig.GetString("DefaultRegion", String.Empty); m_WelcomeMessage = m_loginServerConfig.GetString("WelcomeMessage", ""); m_WelcomeMessage = m_WelcomeMessage.Replace("\\n", "\n"); m_WelcomeMessageURL = m_loginServerConfig.GetString("CustomizedMessageURL", ""); if (m_WelcomeMessageURL != "") { WebClient client = new WebClient(); m_WelcomeMessage = client.DownloadString(m_WelcomeMessageURL); } LLLoginResponseRegister.RegisterValue("Message", m_WelcomeMessage); m_RequireInventory = m_loginServerConfig.GetBoolean("RequireInventory", true); m_AllowRemoteSetLoginLevel = m_loginServerConfig.GetBoolean("AllowRemoteSetLoginLevel", false); m_MinLoginLevel = m_loginServerConfig.GetInt("MinLoginLevel", 0); LLLoginResponseRegister.RegisterValue("SunTexture", m_loginServerConfig.GetString("SunTexture", sunTexture)); LLLoginResponseRegister.RegisterValue("MoonTexture", m_loginServerConfig.GetString("MoonTexture", moonTexture)); LLLoginResponseRegister.RegisterValue("CloudTexture", m_loginServerConfig.GetString("CloudTexture", cloudTexture)); registry.RegisterModuleInterface<ILoginService>(this); m_registry = registry; } public void Start(IConfigSource config, IRegistryCore registry) { m_UserAccountService = registry.RequestModuleInterface<IUserAccountService>().InnerService; m_agentInfoService = registry.RequestModuleInterface<IAgentInfoService>().InnerService; m_AuthenticationService = registry.RequestModuleInterface<IAuthenticationService>(); m_InventoryService = registry.RequestModuleInterface<IInventoryService>(); m_GridService = registry.RequestModuleInterface<IGridService>(); m_AvatarService = registry.RequestModuleInterface<IAvatarService>().InnerService; m_FriendsService = registry.RequestModuleInterface<IFriendsService>(); m_SimulationService = registry.RequestModuleInterface<ISimulationService>(); m_AssetService = registry.RequestModuleInterface<IAssetService>().InnerService; m_LibraryService = registry.RequestModuleInterface<ILibraryService>(); m_CapsService = registry.RequestModuleInterface<ICapsService>(); m_ArchiveService = registry.RequestModuleInterface<IAvatarAppearanceArchiver>(); if (!Initialized) { Initialized = true; RegisterCommands(); } LoginModules = AuroraModuleLoader.PickupModules<ILoginModule>(); foreach (ILoginModule module in LoginModules) { module.Initialize(this, m_config, registry); } MainConsole.Instance.DebugFormat("[LLOGIN SERVICE]: Starting..."); } public void FinishedStartup() { IConfig handlersConfig = m_config.Configs["Handlers"]; if (handlersConfig == null || handlersConfig.GetString("LoginHandler", "") != "LLLoginService") return; IGridInfo gridInfo = m_registry.RequestModuleInterface<IGridInfo>(); if (gridInfo != null) { LLLoginResponseRegister.RegisterValue("TutorialURL", gridInfo.GridTutorialURI); //LLLoginResponseRegister.RegisterValue("OpenIDURL", gridInfo.GridOpenIDURI); LLLoginResponseRegister.RegisterValue("SnapshotConfigURL", gridInfo.GridSnapshotConfigURI); LLLoginResponseRegister.RegisterValue("HelpURL", gridInfo.GridHelpURI); LLLoginResponseRegister.RegisterValue("MapTileURL", gridInfo.GridMapTileURI); LLLoginResponseRegister.RegisterValue("WebProfileURL", gridInfo.GridWebProfileURI); LLLoginResponseRegister.RegisterValue("SearchURL", gridInfo.GridSearchURI); LLLoginResponseRegister.RegisterValue("DestinationURL", gridInfo.GridDestinationURI); LLLoginResponseRegister.RegisterValue("MarketPlaceURL", gridInfo.GridMarketplaceURI); } } public void ReadEventValues(IConfig config) { SetEventCategories((Int32)DirectoryManager.EventCategories.Discussion, "Discussion"); SetEventCategories((Int32)DirectoryManager.EventCategories.Sports, "Sports"); SetEventCategories((Int32)DirectoryManager.EventCategories.LiveMusic, "Live Music"); SetEventCategories((Int32)DirectoryManager.EventCategories.Commercial, "Commercial"); SetEventCategories((Int32)DirectoryManager.EventCategories.Nightlife, "Nightlife/Entertainment"); SetEventCategories((Int32)DirectoryManager.EventCategories.Games, "Games/Contests"); SetEventCategories((Int32)DirectoryManager.EventCategories.Pageants, "Pageants"); SetEventCategories((Int32)DirectoryManager.EventCategories.Education, "Education"); SetEventCategories((Int32)DirectoryManager.EventCategories.Arts, "Arts and Culture"); SetEventCategories((Int32)DirectoryManager.EventCategories.Charity, "Charity/Support Groups"); SetEventCategories((Int32)DirectoryManager.EventCategories.Miscellaneous, "Miscellaneous"); } public void ReadClassifiedValues(IConfig config) { AddClassifiedCategory((Int32)DirectoryManager.ClassifiedCategories.Shopping, "Shopping"); AddClassifiedCategory((Int32)DirectoryManager.ClassifiedCategories.LandRental, "Land Rental"); AddClassifiedCategory((Int32)DirectoryManager.ClassifiedCategories.PropertyRental, "Property Rental"); AddClassifiedCategory((Int32)DirectoryManager.ClassifiedCategories.SpecialAttraction, "Special Attraction"); AddClassifiedCategory((Int32)DirectoryManager.ClassifiedCategories.NewProducts, "New Products"); AddClassifiedCategory((Int32)DirectoryManager.ClassifiedCategories.Employment, "Employment"); AddClassifiedCategory((Int32)DirectoryManager.ClassifiedCategories.Wanted, "Wanted"); AddClassifiedCategory((Int32)DirectoryManager.ClassifiedCategories.Service, "Service"); AddClassifiedCategory((Int32)DirectoryManager.ClassifiedCategories.Personal, "Personal"); } public void SetEventCategories(Int32 value, string categoryName) { Hashtable hash = new Hashtable(); hash["category_name"] = categoryName; hash["category_id"] = value; eventCategories.Add(hash); } public void AddClassifiedCategory(Int32 ID, string categoryName) { Hashtable hash = new Hashtable(); hash["category_name"] = categoryName; hash["category_id"] = ID; classifiedCategories.Add(hash); } public Hashtable SetLevel(string firstName, string lastName, string passwd, int level, IPEndPoint clientIP) { Hashtable response = new Hashtable(); response["success"] = "false"; if (!m_AllowRemoteSetLoginLevel) return response; try { UserAccount account = m_UserAccountService.GetUserAccount(null, firstName, lastName); if (account == null) { MainConsole.Instance.InfoFormat("[LLOGIN SERVICE]: Set Level failed, user {0} {1} not found", firstName, lastName); return response; } if (account.UserLevel < 200) { MainConsole.Instance.InfoFormat("[LLOGIN SERVICE]: Set Level failed, reason: user level too low"); return response; } // // Authenticate this user // // We don't support clear passwords here // string token = m_AuthenticationService.Authenticate(account.PrincipalID, "UserAccount", passwd, 30); UUID secureSession = UUID.Zero; if ((token == string.Empty) || (token != string.Empty && !UUID.TryParse(token, out secureSession))) { MainConsole.Instance.InfoFormat("[LLOGIN SERVICE]: SetLevel failed, reason: authentication failed"); return response; } } catch (Exception e) { MainConsole.Instance.Error("[LLOGIN SERVICE]: SetLevel failed, exception " + e); return response; } m_MinLoginLevel = level; MainConsole.Instance.InfoFormat("[LLOGIN SERVICE]: Login level set to {0} by {1} {2}", level, firstName, lastName); response["success"] = true; return response; } public bool VerifyClient(UUID AgentID, string name, string authType, string passwd) { MainConsole.Instance.InfoFormat("[LLOGIN SERVICE]: Login verification request for {0}", AgentID == UUID.Zero ? name : AgentID.ToString()); // // Get the account and check that it exists // UserAccount account = AgentID != UUID.Zero ? m_UserAccountService.GetUserAccount(null, AgentID) : m_UserAccountService.GetUserAccount(null, name); if (account == null) { return false; } IAgentInfo agent = null; IAgentConnector agentData = DataManager.RequestPlugin<IAgentConnector>(); if (agentData != null) { agent = agentData.GetAgent(account.PrincipalID); } if (agent == null) { agentData.CreateNewAgent(account.PrincipalID); agent = agentData.GetAgent(account.PrincipalID); } foreach (ILoginModule module in LoginModules) { object data; if (module.Login(null, account, agent, authType, passwd, out data) != null) { return false; } } return true; } public LoginResponse Login(UUID AgentID, string Name, string authType, string passwd, string startLocation, string clientVersion, string channel, string mac, string id0, IPEndPoint clientIP, Hashtable requestData) { LoginResponse response; UUID session = UUID.Random(); UUID secureSession = UUID.Zero; UserAccount account = AgentID != UUID.Zero ? m_UserAccountService.GetUserAccount(null, AgentID) : m_UserAccountService.GetUserAccount(null, Name); if (account == null && m_AllowAnonymousLogin) { m_UserAccountService.CreateUser(Name, passwd.StartsWith("$1$") ? passwd.Remove(0, 3):passwd, ""); account = m_UserAccountService.GetUserAccount(null, Name); } if (account == null) { MainConsole.Instance.InfoFormat("[LLOGIN SERVICE]: Login failed for user {0}: no account found", Name); return LLFailedLoginResponse.AccountProblem; } if (account.UserLevel < 0)//No allowing anyone less than 0 return LLFailedLoginResponse.PermanentBannedProblem; if (account.UserLevel < m_MinLoginLevel) { MainConsole.Instance.InfoFormat("[LLOGIN SERVICE]: Login failed for user {1}, reason: login is blocked for user level {0}", account.UserLevel, account.Name); return LLFailedLoginResponse.LoginBlockedProblem; } IAgentInfo agent = null; IAgentConnector agentData = DataManager.RequestPlugin<IAgentConnector>(); if (agentData != null) agent = agentData.GetAgent(account.PrincipalID); if (agent == null) { agentData.CreateNewAgent(account.PrincipalID); agent = agentData.GetAgent(account.PrincipalID); } requestData["ip"] = clientIP.ToString(); foreach (ILoginModule module in LoginModules) { object data; if ((response = module.Login(requestData, account, agent, authType, passwd, out data)) != null) return response; if (data != null) secureSession = (UUID)data;//TODO: NEED TO FIND BETTER WAY TO GET THIS DATA } MainConsole.Instance.InfoFormat("[LLOGIN SERVICE]: Login request for {0} from {1} with user agent {2} starting in {3}", Name, clientIP.Address, clientVersion, startLocation); try { string DisplayName = account.Name; AvatarAppearance avappearance = null; bool newAvatar = false; IProfileConnector profileData = DataManager.RequestPlugin<IProfileConnector>(); // // Get the user's inventory // if (m_RequireInventory && m_InventoryService == null) { MainConsole.Instance.WarnFormat("[LLOGIN SERVICE]: Login failed for user {0}, reason: inventory service not set up", account.Name); return LLFailedLoginResponse.InventoryProblem; } List<InventoryFolderBase> inventorySkel = m_InventoryService.GetInventorySkeleton(account.PrincipalID); if (m_RequireInventory && ((inventorySkel == null) || (inventorySkel.Count == 0))) { List<InventoryItemBase> defaultItems; m_InventoryService.CreateUserInventory(account.PrincipalID, m_DefaultUserAvatarArchive == "", out defaultItems); inventorySkel = m_InventoryService.GetInventorySkeleton(account.PrincipalID); if (m_RequireInventory && ((inventorySkel == null) || (inventorySkel.Count == 0))) { MainConsole.Instance.InfoFormat("[LLOGIN SERVICE]: Login failed for user {0}, reason: unable to retrieve user inventory", account.Name); return LLFailedLoginResponse.InventoryProblem; } if (defaultItems.Count > 0) { avappearance = new AvatarAppearance(account.PrincipalID); avappearance.SetWearable((int)WearableType.Shape, new AvatarWearable(defaultItems[0].ID, defaultItems[0].AssetID)); avappearance.SetWearable((int)WearableType.Skin, new AvatarWearable(defaultItems[1].ID, defaultItems[1].AssetID)); avappearance.SetWearable((int)WearableType.Hair, new AvatarWearable(defaultItems[2].ID, defaultItems[2].AssetID)); avappearance.SetWearable((int)WearableType.Eyes, new AvatarWearable(defaultItems[3].ID, defaultItems[3].AssetID)); avappearance.SetWearable((int)WearableType.Shirt, new AvatarWearable(defaultItems[4].ID, defaultItems[4].AssetID)); avappearance.SetWearable((int)WearableType.Pants, new AvatarWearable(defaultItems[5].ID, defaultItems[5].AssetID)); m_AvatarService.SetAvatar(account.PrincipalID, new AvatarData(avappearance)); newAvatar = true; } } if (profileData != null) { IUserProfileInfo UPI = profileData.GetUserProfile(account.PrincipalID); if (UPI == null) { profileData.CreateNewProfile(account.PrincipalID); UPI = profileData.GetUserProfile(account.PrincipalID); UPI.AArchiveName = m_DefaultUserAvatarArchive; UPI.IsNewUser = true; //profileData.UpdateUserProfile(UPI); //It gets hit later by the next thing } //Find which is set, if any string archiveName = (UPI.AArchiveName != "" && UPI.AArchiveName != " ") ? UPI.AArchiveName : m_DefaultUserAvatarArchive; if (UPI.IsNewUser && archiveName != "") { AvatarAppearance appearance = m_ArchiveService.LoadAvatarArchive(archiveName, account.Name); UPI.AArchiveName = ""; m_AvatarService.SetAppearance(account.PrincipalID, appearance); } if (UPI.IsNewUser) { UPI.IsNewUser = false; profileData.UpdateUserProfile(UPI); } if (UPI.DisplayName != "") DisplayName = UPI.DisplayName; } // Get active gestures List<InventoryItemBase> gestures = m_InventoryService.GetActiveGestures(account.PrincipalID); //MainConsole.Instance.DebugFormat("[LLOGIN SERVICE]: {0} active gestures", gestures.Count); //Reset logged in to true if the user was crashed, but don't fire the logged in event yet m_agentInfoService.SetLoggedIn(account.PrincipalID.ToString(), true, false, UUID.Zero); //Lock it as well m_agentInfoService.LockLoggedInStatus(account.PrincipalID.ToString(), true); //Now get the logged in status, then below make sure to kill the previous agent if we crashed before UserInfo guinfo = m_agentInfoService.GetUserInfo(account.PrincipalID.ToString()); // // Clear out any existing CAPS the user may have // if (m_CapsService != null) { IAgentProcessing agentProcessor = m_registry.RequestModuleInterface<IAgentProcessing>(); if (agentProcessor != null) { IClientCapsService clientCaps = m_CapsService.GetClientCapsService(account.PrincipalID); if (clientCaps != null) { IRegionClientCapsService rootRegionCaps = clientCaps.GetRootCapsService(); if (rootRegionCaps != null) agentProcessor.LogoutAgent(rootRegionCaps, !m_AllowDuplicateLogin); } } else m_CapsService.RemoveCAPS(account.PrincipalID); } // // Change Online status and get the home region // GridRegion home = null; if (guinfo != null && (guinfo.HomeRegionID != UUID.Zero) && m_GridService != null) home = m_GridService.GetRegionByUUID(account.AllScopeIDs, guinfo.HomeRegionID); if (guinfo == null || guinfo.HomeRegionID == UUID.Zero) //Give them a default home and last { if(guinfo == null) guinfo = new UserInfo { UserID = account.PrincipalID.ToString() }; GridRegion DefaultRegion = null, FallbackRegion = null, SafeRegion = null; if (m_GridService != null) { if (m_DefaultHomeRegion != "") { DefaultRegion = m_GridService.GetRegionByName(account.AllScopeIDs, m_DefaultHomeRegion); if (DefaultRegion != null) guinfo.HomeRegionID = guinfo.CurrentRegionID = DefaultRegion.RegionID; } if (guinfo.HomeRegionID == UUID.Zero) { List<GridRegion> DefaultRegions = m_GridService.GetDefaultRegions(account.AllScopeIDs); DefaultRegion = DefaultRegions.Count == 0 ? null : DefaultRegions[0]; if (DefaultRegion != null) guinfo.HomeRegionID = guinfo.CurrentRegionID = DefaultRegion.RegionID; if (guinfo.HomeRegionID == UUID.Zero) { List<GridRegion> Fallback = m_GridService.GetFallbackRegions(account.AllScopeIDs, 0, 0); FallbackRegion = Fallback.Count == 0 ? null : Fallback[0]; if (FallbackRegion != null) guinfo.HomeRegionID = guinfo.CurrentRegionID = FallbackRegion.RegionID; if (guinfo.HomeRegionID == UUID.Zero) { List<GridRegion> Safe = m_GridService.GetSafeRegions(account.AllScopeIDs, 0, 0); SafeRegion = Safe.Count == 0 ? null : Safe[0]; if (SafeRegion != null) guinfo.HomeRegionID = guinfo.CurrentRegionID = SafeRegion.RegionID; } } } } guinfo.CurrentPosition = guinfo.HomePosition = new Vector3(128, 128, 25); guinfo.HomeLookAt = guinfo.CurrentLookAt = new Vector3(0, 0, 0); m_agentInfoService.SetLastPosition(guinfo.UserID, guinfo.CurrentRegionID, guinfo.CurrentPosition, guinfo.CurrentLookAt); m_agentInfoService.SetHomePosition(guinfo.UserID, guinfo.HomeRegionID, guinfo.HomePosition, guinfo.HomeLookAt); MainConsole.Instance.Info("[LLLoginService]: User did not have a home, set to " + (DefaultRegion == null ? "(no region found)" : DefaultRegion.RegionName)); } // // Find the destination region/grid // string where = string.Empty; Vector3 position = Vector3.Zero; Vector3 lookAt = Vector3.Zero; TeleportFlags tpFlags = TeleportFlags.ViaLogin; GridRegion destination = FindDestination(account, guinfo, session, startLocation, home, out tpFlags, out where, out position, out lookAt); if (destination == null) { MainConsole.Instance.InfoFormat("[LLOGIN SERVICE]: Login failed for user {0}, reason: destination not found", account.Name); return LLFailedLoginResponse.DeadRegionProblem; } // // Get the avatar // if (m_AvatarService != null) { if(avappearance == null) avappearance = m_AvatarService.GetAppearance(account.PrincipalID); if (avappearance == null) { //Create an appearance for the user if one doesn't exist if (m_DefaultUserAvatarArchive != "") { MainConsole.Instance.Error("[LLoginService]: Cannot find an appearance for user " + account.Name + ", loading the default avatar from " + m_DefaultUserAvatarArchive + "."); avappearance = m_ArchiveService.LoadAvatarArchive(m_DefaultUserAvatarArchive, account.Name); m_AvatarService.SetAvatar(account.PrincipalID, new AvatarData(avappearance)); } else { MainConsole.Instance.Error("[LLoginService]: Cannot find an appearance for user " + account.Name + ", setting to the default avatar."); avappearance = new AvatarAppearance(account.PrincipalID); m_AvatarService.SetAvatar(account.PrincipalID, new AvatarData(avappearance)); } } else { //Verify that all assets exist now for (int i = 0; i < avappearance.Wearables.Length; i++) { bool messedUp = false; foreach (KeyValuePair<UUID, UUID> item in avappearance.Wearables[i].GetItems()) { AssetBase asset = m_AssetService.Get(item.Value.ToString()); if (asset == null) { InventoryItemBase invItem = m_InventoryService.GetItem(new InventoryItemBase(item.Value)); if (invItem == null) { MainConsole.Instance.Warn("[LLOGIN SERVICE]: Missing avatar appearance asset for user " + account.Name + " for item " + item.Value + ", asset should be " + item.Key + "!"); messedUp = true; } } } if (messedUp) avappearance.Wearables[i] = AvatarWearable.DefaultWearables[i]; } if (!newAvatar) { //Also verify that all baked texture indices exist foreach (byte BakedTextureIndex in AvatarAppearance.BAKE_INDICES) { if (BakedTextureIndex == 19) //Skirt isn't used unless you have a skirt continue; if (avappearance.Texture.GetFace(BakedTextureIndex).TextureID == AppearanceManager.DEFAULT_AVATAR_TEXTURE) { MainConsole.Instance.Warn("[LLOGIN SERVICE]: Bad texture index for user " + account.Name + " for " + BakedTextureIndex + "!"); avappearance = new AvatarAppearance(account.PrincipalID); m_AvatarService.SetAvatar(account.PrincipalID, new AvatarData(avappearance)); break; } } } } } else avappearance = new AvatarAppearance(account.PrincipalID); if ((m_forceUserToWearFolderName != "") && (m_forceUserToWearFolderOwnerUUID.Length == 36)) { UUID userThatOwnersFolder; if (UUID.TryParse(m_forceUserToWearFolderOwnerUUID, out userThatOwnersFolder)) { avappearance = WearFolder(avappearance, account.PrincipalID, userThatOwnersFolder); } } avappearance = FixCurrentOutFitFolder(account.PrincipalID, avappearance); // // Instantiate/get the simulation interface and launch an agent at the destination // string reason = "", seedCap = ""; AgentCircuitData aCircuit = LaunchAgentAtGrid(destination, tpFlags, account, avappearance, session, secureSession, position, where, clientIP, out where, out reason, out seedCap, out destination); if (aCircuit == null) { MainConsole.Instance.InfoFormat("[LLOGIN SERVICE]: Login failed for user {1}, reason: {0}", reason, account.Name); return new LLFailedLoginResponse(LoginResponseEnum.InternalError, reason, false); } // Get Friends list List<FriendInfo> friendsList = new List<FriendInfo>(); if (m_FriendsService != null) friendsList = m_FriendsService.GetFriends(account.PrincipalID); //Set them as logged in now, they are ready, and fire the logged in event now, as we're all done m_agentInfoService.SetLastPosition(account.PrincipalID.ToString(), destination.RegionID, position, lookAt); m_agentInfoService.LockLoggedInStatus(account.PrincipalID.ToString(), false); //Unlock it now m_agentInfoService.SetLoggedIn(account.PrincipalID.ToString(), true, true, destination.RegionID); // // Finally, fill out the response and return it // string MaturityRating = "A"; string MaxMaturity = "A"; if (agent != null) { MaturityRating = agent.MaturityRating == 0 ? "P" : agent.MaturityRating == 1 ? "M" : "A"; MaxMaturity = agent.MaxMaturity == 0 ? "P" : agent.MaxMaturity == 1 ? "M" : "A"; } response = new LLLoginResponse(account, aCircuit, guinfo, destination, inventorySkel, friendsList.ToArray(), m_InventoryService, m_LibraryService, where, startLocation, position, lookAt, gestures, home, clientIP, MaxMaturity, MaturityRating, eventCategories, classifiedCategories, seedCap, m_config, DisplayName); MainConsole.Instance.InfoFormat("[LLOGIN SERVICE]: All clear. Sending login response to client to login to region " + destination.RegionName + ", tried to login to " + startLocation + " at " + position.ToString() + "."); AddLoginSuccessNotification(account); return response; } catch (Exception e) { MainConsole.Instance.WarnFormat("[LLOGIN SERVICE]: Exception processing login for {0} : {1}", Name, e); if (account != null) { //Revert their logged in status if we got that far m_agentInfoService.LockLoggedInStatus(account.PrincipalID.ToString(), false); //Unlock it now m_agentInfoService.SetLoggedIn(account.PrincipalID.ToString(), false, false, UUID.Zero); } return LLFailedLoginResponse.InternalError; } } private void AddLoginSuccessNotification(UserAccount account) { if (MainConsole.NotificationService == null) return; MainConsole.NotificationService.AddNotification(AlertLevel.Low, account.Name + " has logged in successfully.", "LLLoginService", (messages) => { return messages.Count + " users have logged in successfully."; }); } protected GridRegion FindDestination(UserAccount account, UserInfo pinfo, UUID sessionID, string startLocation, GridRegion home, out TeleportFlags tpFlags, out string where, out Vector3 position, out Vector3 lookAt) { where = "home"; position = new Vector3(128, 128, 25); lookAt = new Vector3(0, 1, 0); tpFlags = TeleportFlags.ViaLogin; if (m_GridService == null) return null; if (startLocation.Equals("home")) { tpFlags |= TeleportFlags.ViaLandmark; // logging into home region if (pinfo == null) return null; GridRegion region = null; bool tryDefaults = false; if (home == null) { MainConsole.Instance.WarnFormat( "[LLOGIN SERVICE]: User {0} {1} tried to login to a 'home' start location but they have none set", account.FirstName, account.LastName); tryDefaults = true; } else { region = home; position = pinfo.HomePosition; lookAt = pinfo.HomeLookAt; } if (tryDefaults) { tpFlags &= ~TeleportFlags.ViaLandmark; List<GridRegion> defaults = m_GridService.GetDefaultRegions(account.AllScopeIDs); if (defaults != null && defaults.Count > 0) { region = defaults[0]; where = "safe"; } else { List<GridRegion> fallbacks = m_GridService.GetFallbackRegions(account.AllScopeIDs, 0, 0); if (fallbacks != null && fallbacks.Count > 0) { region = fallbacks[0]; where = "safe"; } else { //Try to find any safe region List<GridRegion> safeRegions = m_GridService.GetSafeRegions(account.AllScopeIDs, 0, 0); if (safeRegions != null && safeRegions.Count > 0) { region = safeRegions[0]; where = "safe"; } else { MainConsole.Instance.WarnFormat("[LLOGIN SERVICE]: User {0} {1} does not have a valid home and this grid does not have default locations. Attempting to find random region", account.FirstName, account.LastName); defaults = m_GridService.GetRegionsByName(account.AllScopeIDs, "", 0, 1); if (defaults != null && defaults.Count > 0) { region = defaults[0]; where = "safe"; } } } } } return region; } if (startLocation.Equals("last")) { tpFlags |= TeleportFlags.ViaLandmark; // logging into last visited region where = "last"; if (pinfo == null) return null; GridRegion region = null; if (pinfo.CurrentRegionID.Equals(UUID.Zero) || (region = m_GridService.GetRegionByUUID(account.AllScopeIDs, pinfo.CurrentRegionID)) == null) { tpFlags &= ~TeleportFlags.ViaLandmark; List<GridRegion> defaults = m_GridService.GetDefaultRegions(account.AllScopeIDs); if (defaults != null && defaults.Count > 0) { region = defaults[0]; where = "safe"; } else { defaults = m_GridService.GetFallbackRegions(account.AllScopeIDs, 0, 0); if (defaults != null && defaults.Count > 0) { region = defaults[0]; where = "safe"; } else { defaults = m_GridService.GetSafeRegions(account.AllScopeIDs, 0, 0); if (defaults != null && defaults.Count > 0) { region = defaults[0]; where = "safe"; } } } } else { position = pinfo.CurrentPosition; if (position.X < 0) position.X = 0; if (position.Y < 0) position.Y = 0; if (position.Z < 0) position.Z = 0; if (position.X > region.RegionSizeX) position.X = region.RegionSizeX; if (position.Y > region.RegionSizeY) position.Y = region.RegionSizeY; lookAt = pinfo.CurrentLookAt; } return region; } else { // free uri form // e.g. New Moon&135&46 New Moon@osgrid.org:8002&153&34 where = "url"; Regex reURI = new Regex(@"^uri:(?<region>[^&]+)&(?<x>\d+)&(?<y>\d+)&(?<z>\d+)$"); Match uriMatch = reURI.Match(startLocation); position = new Vector3(float.Parse(uriMatch.Groups["x"].Value, Culture.NumberFormatInfo), float.Parse(uriMatch.Groups["y"].Value, Culture.NumberFormatInfo), float.Parse(uriMatch.Groups["z"].Value, Culture.NumberFormatInfo)); string regionName = uriMatch.Groups["region"].ToString(); if (!regionName.Contains("@")) { List<GridRegion> regions = m_GridService.GetRegionsByName(account.AllScopeIDs, regionName, 0, 1); if ((regions == null) || (regions.Count == 0)) { MainConsole.Instance.InfoFormat( "[LLLOGIN SERVICE]: Got Custom Login URI {0}, can't locate region {1}. Trying defaults.", startLocation, regionName); regions = m_GridService.GetDefaultRegions(account.AllScopeIDs); if (regions != null && regions.Count > 0) { where = "safe"; return regions[0]; } List<GridRegion> fallbacks = m_GridService.GetFallbackRegions(account.AllScopeIDs, 0, 0); if (fallbacks != null && fallbacks.Count > 0) { where = "safe"; return fallbacks[0]; } //Try to find any safe region List<GridRegion> safeRegions = m_GridService.GetSafeRegions(account.AllScopeIDs, 0, 0); if (safeRegions != null && safeRegions.Count > 0) { where = "safe"; return safeRegions[0]; } MainConsole.Instance.InfoFormat( "[LLLOGIN SERVICE]: Got Custom Login URI {0}, Grid does not have any available regions.", startLocation); return null; } return regions[0]; } //This is so that you can login to other grids via IWC (or HG), example"RegionTest@testingserver.com:8002". All this really needs to do is inform the other grid that we have a user who wants to connect. IWC allows users to login by default to other regions (without the host names), but if one is provided and we don't have a link, we need to create one here. string[] parts = regionName.Split(new char[] { '@' }); if (parts.Length < 2) { MainConsole.Instance.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, can't locate region {1}", startLocation, regionName); return null; } // Valid specification of a remote grid regionName = parts[0]; string domainLocator = parts[1]; //Try now that we removed the domain locator GridRegion region = m_GridService.GetRegionByName(account.AllScopeIDs, regionName); if (region != null && region.RegionName == regionName) //Make sure the region name is right too... it could just be a similar name return region; ICommunicationService service = m_registry.RequestModuleInterface<ICommunicationService>(); if (service != null) { region = service.GetRegionForGrid(regionName, domainLocator); if (region != null) return region; } List<GridRegion> defaults = m_GridService.GetDefaultRegions(account.AllScopeIDs); if (defaults != null && defaults.Count > 0) { where = "safe"; return defaults[0]; } else { List<GridRegion> fallbacks = m_GridService.GetFallbackRegions(account.AllScopeIDs, 0, 0); if (fallbacks != null && fallbacks.Count > 0) { where = "safe"; return fallbacks[0]; } else { //Try to find any safe region List<GridRegion> safeRegions = m_GridService.GetSafeRegions(account.AllScopeIDs, 0, 0); if (safeRegions != null && safeRegions.Count > 0) { where = "safe"; return safeRegions[0]; } MainConsole.Instance.InfoFormat( "[LLLOGIN SERVICE]: Got Custom Login URI {0}, Grid does not have any available regions.", startLocation); return null; } } } } protected AgentCircuitData LaunchAgentAtGrid(GridRegion destination, TeleportFlags tpFlags, UserAccount account, AvatarAppearance appearance, UUID session, UUID secureSession, Vector3 position, string currentWhere, IPEndPoint clientIP, out string where, out string reason, out string seedCap, out GridRegion dest) { where = currentWhere; reason = string.Empty; uint circuitCode = 0; AgentCircuitData aCircuit = null; dest = destination; #region Launch Agent circuitCode = (uint)Util.RandomClass.Next(); aCircuit = MakeAgent(destination, account, appearance, session, secureSession, circuitCode, position, clientIP); aCircuit.teleportFlags = (uint)tpFlags; LoginAgentArgs args = m_registry.RequestModuleInterface<IAgentProcessing>(). LoginAgent(destination, aCircuit); aCircuit.OtherInformation = args.CircuitData.OtherInformation; aCircuit.CapsPath = args.CircuitData.CapsPath; aCircuit.RegionUDPPort = args.CircuitData.RegionUDPPort; reason = args.Reason; reason = ""; seedCap = args.SeedCap; bool success = args.Success; if (!success && m_GridService != null) { //Remove the landmark flag (landmark is used for ignoring the landing points in the region) aCircuit.teleportFlags &= ~(uint)TeleportFlags.ViaLandmark; m_GridService.SetRegionUnsafe(destination.RegionID); // Make sure the client knows this isn't where they wanted to land where = "safe"; // Try the default regions List<GridRegion> defaultRegions = m_GridService.GetDefaultRegions(account.AllScopeIDs); if (defaultRegions != null) { success = TryFindGridRegionForAgentLogin(defaultRegions, account, appearance, session, secureSession, circuitCode, position, clientIP, aCircuit, out seedCap, out reason, out dest); } if (!success) { // Try the fallback regions List<GridRegion> fallbacks = m_GridService.GetFallbackRegions(account.AllScopeIDs, destination.RegionLocX, destination.RegionLocY); if (fallbacks != null) { success = TryFindGridRegionForAgentLogin(fallbacks, account, appearance, session, secureSession, circuitCode, position, clientIP, aCircuit, out seedCap, out reason, out dest); } if (!success) { //Try to find any safe region List<GridRegion> safeRegions = m_GridService.GetSafeRegions(account.AllScopeIDs, destination.RegionLocX, destination.RegionLocY); if (safeRegions != null) { success = TryFindGridRegionForAgentLogin(safeRegions, account, appearance, session, secureSession, circuitCode, position, clientIP, aCircuit, out seedCap, out reason, out dest); if (!success) reason = "No Region Found"; } } } } #endregion if (success) { //Set the region to safe since we got there m_GridService.SetRegionSafe(destination.RegionID); return aCircuit; } return null; } protected bool TryFindGridRegionForAgentLogin(List<GridRegion> regions, UserAccount account, AvatarAppearance appearance, UUID session, UUID secureSession, uint circuitCode, Vector3 position, IPEndPoint clientIP, AgentCircuitData aCircuit, out string seedCap, out string reason, out GridRegion destination) { LoginAgentArgs args = null; foreach (GridRegion r in regions) { args = m_registry.RequestModuleInterface<IAgentProcessing>(). LoginAgent(r, aCircuit); if (args.Success) { aCircuit = MakeAgent(r, account, appearance, session, secureSession, circuitCode, position, clientIP); destination = r; reason = args.Reason; seedCap = args.SeedCap; return true; } m_GridService.SetRegionUnsafe(r.RegionID); } if (args != null) { seedCap = args.SeedCap; reason = args.Reason; } else { seedCap = ""; reason = ""; } destination = null; return false; } protected AgentCircuitData MakeAgent(GridRegion region, UserAccount account, AvatarAppearance appearance, UUID session, UUID secureSession, uint circuit, Vector3 position, IPEndPoint clientIP) { AgentCircuitData aCircuit = new AgentCircuitData { AgentID = account.PrincipalID, Appearance = appearance ?? new AvatarAppearance(account.PrincipalID), CapsPath = CapsUtil.GetRandomCapsObjectPath(), child = false, circuitcode = circuit, SecureSessionID = secureSession, SessionID = session, startpos = position, IPAddress = clientIP.Address.ToString(), ClientIPEndPoint = clientIP }; // the first login agent is root return aCircuit; } #region Console Commands protected void RegisterCommands() { if (MainConsole.Instance == null) return; MainConsole.Instance.Commands.AddCommand("login level", "login level <level>", "Set the minimum user level to log in", HandleLoginCommand); MainConsole.Instance.Commands.AddCommand("login reset", "login reset", "Reset the login level to allow all users", HandleLoginCommand); MainConsole.Instance.Commands.AddCommand("login text", "login text <text>", "Set the text users will see on login", HandleLoginCommand); } protected void HandleLoginCommand(string[] cmd) { string subcommand = cmd[1]; switch (subcommand) { case "level": // Set the minimum level to allow login // Useful to allow grid update without worrying about users. // or fixing critical issues // if (cmd.Length > 2) Int32.TryParse(cmd[2], out m_MinLoginLevel); break; case "reset": m_MinLoginLevel = 0; break; case "text": if (cmd.Length > 2) m_WelcomeMessage = cmd[2]; break; } } #endregion #region Force Wear public AvatarAppearance WearFolder(AvatarAppearance avappearance, UUID user, UUID folderOwnerID) { InventoryFolderBase Folder2Wear = m_InventoryService.GetFolderByOwnerAndName(folderOwnerID, m_forceUserToWearFolderName); if (Folder2Wear != null) { List<InventoryItemBase> itemsInFolder = m_InventoryService.GetFolderItems(UUID.Zero, Folder2Wear.ID); InventoryFolderBase appearanceFolder = m_InventoryService.GetFolderForType(user, InventoryType.Wearable, AssetType.Clothing); InventoryFolderBase folderForAppearance = new InventoryFolderBase(UUID.Random(), "GridWear", user, -1, appearanceFolder.ID, 1); List<InventoryFolderBase> userFolders = m_InventoryService.GetFolderFolders(user, appearanceFolder.ID); bool alreadyThere = false; List<UUID> items2RemoveFromAppearence = new List<UUID>(); List<UUID> toDelete = new List<UUID>(); foreach (InventoryFolderBase folder in userFolders) { if (folder.Name == folderForAppearance.Name) { List<InventoryItemBase> itemsInCurrentFolder = m_InventoryService.GetFolderItems(UUID.Zero, folder.ID); foreach (InventoryItemBase itemBase in itemsInCurrentFolder) { items2RemoveFromAppearence.Add(itemBase.AssetID); items2RemoveFromAppearence.Add(itemBase.ID); toDelete.Add(itemBase.ID); } folderForAppearance = folder; alreadyThere = true; m_InventoryService.DeleteItems(user, toDelete); break; } } if (!alreadyThere) m_InventoryService.AddFolder(folderForAppearance); else { // we have to remove all the old items if they are currently wearing them for (int i = 0; i < avappearance.Wearables.Length; i++) { AvatarWearable wearable = avappearance.Wearables[i]; for (int ii = 0; ii < wearable.Count; ii++) { if (items2RemoveFromAppearence.Contains(wearable[ii].ItemID)) { avappearance.Wearables[i] = AvatarWearable.DefaultWearables[i]; break; } } } List<AvatarAttachment> attachments = avappearance.GetAttachments(); foreach (AvatarAttachment attachment in attachments) { if ((items2RemoveFromAppearence.Contains(attachment.AssetID)) || (items2RemoveFromAppearence.Contains(attachment.ItemID))) { avappearance.DetachAttachment(attachment.ItemID); } } } // ok, now we have a empty folder, lets add the items foreach (InventoryItemBase itemBase in itemsInFolder) { InventoryItemBase newcopy = m_InventoryService.InnerGiveInventoryItem(user, folderOwnerID, itemBase, folderForAppearance.ID, true); if (newcopy.InvType == (int) InventoryType.Object) { AssetBase attobj = m_AssetService.Get(newcopy.AssetID.ToString()); if (attobj != null) { string xmlData = Utils.BytesToString(attobj.Data); XmlDocument doc = new XmlDocument(); try { doc.LoadXml(xmlData); } catch { continue; } if (doc.FirstChild.OuterXml.StartsWith("<groups>") || (doc.FirstChild.NextSibling != null && doc.FirstChild.NextSibling.OuterXml.StartsWith("<groups>"))) continue; string xml = ""; if ((doc.FirstChild.NodeType == XmlNodeType.XmlDeclaration) && (doc.FirstChild.NextSibling != null)) xml = doc.FirstChild.NextSibling.OuterXml; else xml = doc.FirstChild.OuterXml; doc.LoadXml(xml); if (doc.DocumentElement == null) continue; XmlNodeList xmlNodeList = doc.DocumentElement.SelectNodes("//State"); int attchspot; if ((xmlNodeList != null) && (int.TryParse(xmlNodeList[0].InnerText, out attchspot))) { AvatarAttachment a = new AvatarAttachment(attchspot, newcopy.ID, newcopy.AssetID); Dictionary<int, List<AvatarAttachment>> ac = avappearance.Attachments; if (!ac.ContainsKey(attchspot)) ac[attchspot] = new List<AvatarAttachment>(); ac[attchspot].Add(a); avappearance.Attachments = ac; } } } m_InventoryService.AddItem(newcopy); } } return avappearance; } public AvatarAppearance FixCurrentOutFitFolder(UUID user, AvatarAppearance avappearance) { InventoryFolderBase CurrentOutFitFolder = m_InventoryService.GetFolderForType(user, 0, AssetType.CurrentOutfitFolder); if (CurrentOutFitFolder == null) return avappearance; List<InventoryItemBase> ic = m_InventoryService.GetFolderItems(user, CurrentOutFitFolder.ID); List<UUID> brokenLinks = new List<UUID>(); List<UUID> OtherStuff = new List<UUID>(); foreach (var i in ic) { InventoryItemBase linkedItem = null; if ((linkedItem = m_InventoryService.GetItem(new InventoryItemBase(i.AssetID))) == null) brokenLinks.Add(i.ID); else if (linkedItem.ID == AvatarWearable.DEFAULT_EYES_ITEM || linkedItem.ID == AvatarWearable.DEFAULT_BODY_ITEM || linkedItem.ID == AvatarWearable.DEFAULT_HAIR_ITEM || linkedItem.ID == AvatarWearable.DEFAULT_PANTS_ITEM || linkedItem.ID == AvatarWearable.DEFAULT_SHIRT_ITEM || linkedItem.ID == AvatarWearable.DEFAULT_SKIN_ITEM) brokenLinks.Add(i.ID); //Default item link, needs removed else if (!OtherStuff.Contains(i.AssetID)) OtherStuff.Add(i.AssetID); } for (int i = 0; i < avappearance.Wearables.Length; i++) { AvatarWearable wearable = avappearance.Wearables[i]; for (int ii = 0; ii < wearable.Count; ii++) { if (!OtherStuff.Contains(wearable[ii].ItemID)) { InventoryItemBase linkedItem2 = null; if ((linkedItem2 = m_InventoryService.GetItem(new InventoryItemBase(wearable[ii].ItemID))) != null) { InventoryItemBase linkedItem3 = (InventoryItemBase)linkedItem2.Clone(); linkedItem3.AssetID = linkedItem2.ID; linkedItem3.AssetType = (int)AssetType.Link; linkedItem3.ID = UUID.Random(); linkedItem3.CurrentPermissions = linkedItem2.NextPermissions; linkedItem3.EveryOnePermissions = linkedItem2.NextPermissions; linkedItem3.Folder = CurrentOutFitFolder.ID; m_InventoryService.AddItem(linkedItem3); } else { avappearance.Wearables[i] = AvatarWearable.DefaultWearables[i]; } } } } List<UUID> items2UnAttach = new List<UUID>(); foreach (KeyValuePair<int, List<AvatarAttachment>> attachmentSpot in avappearance.Attachments) { foreach (AvatarAttachment attachment in attachmentSpot.Value) { if (!OtherStuff.Contains(attachment.ItemID)) { InventoryItemBase linkedItem2 = null; if ((linkedItem2 = m_InventoryService.GetItem(new InventoryItemBase(attachment.ItemID))) != null) { InventoryItemBase linkedItem3 = (InventoryItemBase)linkedItem2.Clone(); linkedItem3.AssetID = linkedItem2.ID; linkedItem3.AssetType = (int)AssetType.Link; linkedItem3.ID = UUID.Random(); linkedItem3.CurrentPermissions = linkedItem2.NextPermissions; linkedItem3.EveryOnePermissions = linkedItem2.NextPermissions; linkedItem3.Folder = CurrentOutFitFolder.ID; m_InventoryService.AddItem(linkedItem3); } else items2UnAttach.Add(attachment.ItemID); } } } foreach (UUID uuid in items2UnAttach) { avappearance.DetachAttachment(uuid); } if (brokenLinks.Count != 0) m_InventoryService.DeleteItems(user, brokenLinks); return avappearance; } #endregion } }
using UnityEngine; using System.Collections; public class BoidController : MonoBehaviour { private BoidGroupController parent; // Object that reigns over entire group private float averageDistance = 0.0f; // Average distance between all sub-group members private int nearby = 0; // Number of nearby entities (determines sub group size) private Vector3 groupCenter; // Position vector of subgroup center private Vector3 groupVelocity; // Velocity vector of average subgroup velocity private Vector3 velocity; // Velocity vector for this entity private Vector3 v4; // Velocity vector for boid rule 4 private Vector3 v5; // Velocity vector for boid rule 5 private Vector3 v6; // Velocity vector for boid rule 6 private Vector3[] crystalSites; // Position vectors of all crystal sites around boid private bool[] siteLock; private Vector3 nearestSite; private BoidController nSParent; private int index = 0; private static Vector3[] calculatedSites; private static bool calculated = false; private static int count = 0; private float crystalAngleRad = 0; private BoidController nearestBoid; private double accumulator = 0; private double updateInterval = 1.0d/30.0d; void Start () { parent = transform.parent.GetComponent<BoidGroupController>(); velocity = new Vector3( Random.Range( -1.0f, 1.0f ), Random.Range( -1.0f, 1.0f ), Random.Range( -1.0f, 1.0f ) ); /* * Declares whether or not boid should be locked to a 2D space */ if (parent.crystalSites > 0) { crystalAngleRad = 360 / parent.crystalSites; } nearestSite = this.transform.position; nearestBoid = this; if ( parent.Grid2D ) { transform.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ | RigidbodyConstraints.FreezeRotationY; if ( calculated == false ) { calculatedSites = calculate2DSites(); calculated = true; } } else { if ( calculated == false ) { calculatedSites = calculate3DSites(); calculated = true; } } crystalSites = new Vector3[count]; siteLock = new bool[count]; this.gameObject.layer = parent.gameObject.layer; } // Update is called once per frame void Update () { if ( Time.deltaTime > 0.04 ) { accumulator += 0.04; } else { accumulator += Time.deltaTime; } while ( accumulator >= updateInterval ) { updateVelocity (); Move (); updateSites (); this.transform.LookAt(this.transform.position + this.velocity); accumulator -= updateInterval; } } void LateUpdate () { // updateSites (); updateLines (); } public void Move () { velocity += v5; if ( parent.Grid2D ) { velocity.y = 0; } transform.Translate( velocity, Space.World); } public void updateVelocity () { v4 = boidRuleFour(); velocity = velocity + mainRules() + v4 + v6 + boidRuleFive () + boidRuleSix () + boidRuleSeven (); if ( parent.Grid2D ) { velocity.y = 0; } limitVelocity(); } public void updateSites() { for ( int i = 0; i < count; i++ ) { Vector3 temp = calculatedSites[i]; /*temp = rotateY ( temp, (Mathf.PI * this.transform.eulerAngles.y)/180 ); temp = rotateX ( temp, (Mathf.PI * this.transform.eulerAngles.x)/180 ); temp = rotateZ ( temp, (Mathf.PI * this.transform.eulerAngles.z)/180 );*/ crystalSites[i] = this.transform.position + temp; } } public void updateLines() { if (parent.sitePoints) { float tempLength = 0.5f; for ( int i = 0; i < count; i++ ) { Debug.DrawLine( crystalSites[i] + new Vector3(-1f * tempLength, 0f * tempLength, -1f * tempLength), crystalSites[i] + new Vector3( 1f * tempLength, 0f * tempLength, 1f * tempLength ), Color.red, 0, true ); Debug.DrawLine( crystalSites[i] + new Vector3(1f * tempLength, 0f * tempLength, -1f * tempLength), crystalSites[i] + new Vector3( -1f * tempLength, 0f * tempLength, 1f * tempLength ), Color.red, 0, true ); } } if ( parent.siteLines ) { Debug.DrawLine(this.transform.position, nearestSite, Color.green, 0, true); } if ( parent.boidLines && nSParent != null ) { Debug.DrawLine(this.transform.position, nSParent.transform.position, Color.magenta, 0, true); } } /* * Calculates velocity vector of current boid. * 3 Main rules + X extra rules * Rule 1) Move boids to center of group * Rule 2) Move boids away from eachother if they get too close * Rule 3) Set boid velocities based on surrounding boids * extras: * Rule 4) (different function) keep boids contained within a set boundary * Rule 5) Keep groups of different types of boids separate * Rule 6) Keep boids in a crystalized formation */ public Vector3 mainRules () { /* * Check for nearby boids using an OverlapSphere collider */ Collider[] nearBoids = Physics.OverlapSphere( this.transform.position, parent.maxSubGroupDistance ); groupVelocity = new Vector3(); groupCenter = new Vector3(); Vector3 separationVector = new Vector3(); v5 = new Vector3(); v6 = new Vector3(); nearby = 0; averageDistance = 0.0f; bool first = true; for ( int i = 0; i < nearBoids.Length; i++ ) { BoidController boid = nearBoids[i].GetComponent<BoidController>(); if ( boid != null ) { bool isVisible = true; if (boid != this) { Vector3 temp = boid.transform.position - transform.position; temp = temp / temp.magnitude; float angle = Vector3.Angle(this.transform.forward, temp); if(angle >= parent.maxVisibilityAngle) { isVisible = false; } } if (isVisible && boid.getParent() == parent && boid != this ) { if ( first ) { nearestBoid = boid; first = false; } groupVelocity = groupVelocity + boid.getVelocity(); nearby++; averageDistance = averageDistance + Vector3.Distance( boid.transform.position, this.transform.position ); groupCenter = groupCenter + boid.transform.position; if ( ( Vector3.Distance( nearestBoid.transform.position, this.transform.position ) > Vector3.Distance( boid.transform.position, this.transform.position ) || nearestBoid == this ) && boid != this && boid.hasFreeSites()) { nearestBoid = boid; } if ( Vector3.Distance( boid.transform.position, this.transform.position ) < parent.minDistance ) { separationVector = separationVector - ( boid.transform.position - this.transform.position ); //separationVector = (separationVector - (boid.transform.position - this.transform.position)) * (parent.minDistance - Vector3.Magnitude(boid.transform.position - this.transform.position))/(parent.minDistance); } } else { if ( Vector3.Distance ( boid.transform.position, this.transform.position ) < parent.minDistance ) { v5 = v5 - ( boid.transform.position - this.transform.position ); } } } } v5 = v5*parent.interGroupSeparationWeight; if ( nearestBoid != null && parent.crystalFormationWeight > 0 && parent.crystalSites > 0 ) { Vector3[] nearestSites = nearestBoid.getCrystalSites(); if (nSParent != null) { nSParent.unlockSite(index); } if (nSParent == null || nSParent == this) { nearestSite = nearestSites[0]; nSParent = nearestBoid; for ( int i = 1; i < count; i++ ) { if ( Vector3.Distance( nearestSites[i], this.transform.position ) < Vector3.Distance( nearestSite, this.transform.position ) && nearestBoid.isLocked(i) == false) { nearestSite = nearestSites[i]; index = i; } } } else { nearestSite = nSParent.getCrystalSites()[index]; bool temp = true; for ( int i = 0; i < count; i++ ) { if ( temp ) { if ( parent.crystalSiteWeight * Vector3.Distance( nearestSites[i], this.transform.position ) < Vector3.Distance( nearestSite, this.transform.position ) && nearestBoid.isLocked(i) == false ) { temp = false; nearestSite = nearestSites[i]; index = i; nSParent = nearestBoid; } } else { if ( Vector3.Distance( nearestSites[i], this.transform.position ) < Vector3.Distance( nearestSite, this.transform.position ) && nearestBoid.isLocked(i) == false) { nearestSite = nearestSites[i]; index = i; nSParent = nearestBoid; } } } } if ( nSParent != null && nSParent != this ) { nSParent.lockSite(index); } if ( nSParent != this ) { v6 = ( nearestSite - transform.position ) * Vector3.Distance( nearestSite, this.transform.position ) / parent.crystalDistance; } } if ( parent.generateNoise ) { float tempr = Random.value; int rand = 0; if ( tempr > parent.noiseAmount ) { rand = 1; } if ( rand == 1 ) { v6 = v6 * parent.crystalFormationWeight; } else { v6 = Vector3.zero; } } else { v6 = v6 * parent.crystalFormationWeight; } if ( nearby == 0 ) { return separationVector; } else { groupVelocity = groupVelocity / nearby; groupCenter = groupCenter / nearby; averageDistance = averageDistance / nearby; return ( ( groupVelocity - this.velocity) / 8 ) * parent.alignmentWeight + ( ( groupCenter - transform.position ) / 50 ) *parent.cohesionWeight + separationVector * parent.intraGroupSeparationWeight; } } /* * Keep boids enclosed in a set boundary space */ public Vector3 boidRuleFour () { Vector3 temp = new Vector3(); if ( this.transform.position.x < parent.xMin ) { temp.x = parent.wallBounceSpeed; } else if ( this.transform.position.x > parent.xMax ) { temp.x = -parent.wallBounceSpeed; } if ( this.transform.position.y < parent.yMin ) { temp.y = parent.wallBounceSpeed; } else if ( this.transform.position.y > parent.yMax ) { temp.y = -parent.wallBounceSpeed; } if ( this.transform.position.z < parent.zMin ) { temp.z = parent.wallBounceSpeed; } else if ( this.transform.position.z > parent.zMax ) { temp.z = -parent.wallBounceSpeed; } return temp; } /* * Avoid predators */ private Vector3 boidRuleFive () { Collider[] nearBoids = Physics.OverlapSphere( this.transform.position, parent.predatorDistance, parent.predatorLayer ); Vector3 temp = Vector3.zero; for ( int i = 0; i < nearBoids.Length; i++ ) { BoidController boid = nearBoids[i].GetComponent<BoidController>(); temp = temp - ( boid.transform.position - this.transform.position ); } temp = temp * parent.avoidPredatorWeight; return temp; } /* * Attack prey */ private Vector3 boidRuleSix () { Collider[] nearBoids = Physics.OverlapSphere( this.transform.position, parent.predatorDistance, parent.preyLayer ); Vector3 temp = Vector3.zero; BoidController closest = null; if (nearBoids.Length > 0) { closest = nearBoids[0].GetComponent<BoidController>(); } for ( int i = 1; i < nearBoids.Length; i++ ) { BoidController boid = nearBoids[i].GetComponent<BoidController>(); if (Vector3.Distance(this.transform.position, boid.transform.position) < Vector3.Distance(this.transform.position, closest.transform.position)) { closest = boid; } } if (closest != null) { temp = closest.transform.position - this.transform.position; } temp = temp * parent.attackPreyWeight; return temp; } private Vector3 boidRuleSeven () { Vector3 vel = Vector3.zero; if ( parent.goalNodes.Length != 0 ) { GameObject temp = parent.goalNodes [0]; for ( int i = 1; i < parent.goalNodes.Length; i++ ) { if (Vector3.Distance(this.transform.position, temp.transform.position) > Vector3.Distance(this.transform.position, parent.goalNodes[i].transform.position)) { temp = parent.goalNodes[i]; } } vel = temp.transform.position - this.transform.position; } return vel * parent.goalWeight; } /* * Limit velocity of current boid to a max set value */ private void limitVelocity () { if ( Vector3.Magnitude( this.velocity ) > parent.maxSpeed ) { this.velocity = ( this.velocity / Vector3.Magnitude( this.velocity ) ) * parent.maxSpeed; } } /* * Rotates a position vector around the x-axis by some angle */ private Vector3 rotateX ( Vector3 v, float angle ) { float sin = Mathf.Sin( angle ); float cos = Mathf.Cos( angle ); float ty = v.y; float tz = v.z; v.y = ( cos * ty ) - ( sin * tz ); v.z = ( cos * tz ) + ( sin * ty ); return v; } /* * Rotates a position vector around the y-axis by some angle */ private Vector3 rotateY ( Vector3 v, float angle ) { float sin = Mathf.Sin( angle ); float cos = Mathf.Cos( angle ); float tx = v.x; float tz = v.z; v.x = ( cos * tx ) + ( sin * tz ); v.z = ( cos * tz ) - ( sin * tx ); return v; } /* * Rotates a position vector around the z-axis by some angle */ private Vector3 rotateZ ( Vector3 v, float angle ) { float sin = Mathf.Sin( angle ); float cos = Mathf.Cos( angle ); float tx = v.x; float ty = v.y; v.x = ( cos * tx ) - ( sin * ty ); v.y = ( cos * ty ) + ( sin * tx ); return v; } private Vector3[] calculate2DSites () { int siteNo = parent.crystalSites; count = parent.crystalSites; Vector3[] siteCoords = new Vector3[siteNo]; if ( siteNo == 0 ) { return siteCoords; } float theta = 0; for ( int i = 0; i < siteNo; i++ ) { Vector3 rotationPos = new Vector3( parent.crystalDistance, 0f, 0f ); rotationPos = rotateY( rotationPos, theta ); siteCoords[i] = rotationPos; theta += crystalAngleRad * Mathf.Deg2Rad; } return siteCoords; } private Vector3[] calculate3DSites () { int siteNo = parent.crystalSites; ArrayList temp = new ArrayList(); Vector3[] siteCoords; if ( siteNo == 0 ) { return new Vector3[0]; } float thetaY = 0f; float thetaZ = 0f; float CARY = 0f; float CARZ = 0f; if ( parent.crystalSites % 2 == 0 ) { CARY = 360 / (parent.crystalSites / 2); CARZ = 360 / (parent.crystalSites / 2); } else { CARY = 360 / ( ( ( parent.crystalSites - 1 ) / 2 + 1 ) ); CARZ = 360 / ( ( parent.crystalSites - 1 ) / 2 ); } for ( int i = 0; i < siteNo; i++ ) { if ( i%2 == 0 ) { Vector3 rotationPos = new Vector3( parent.crystalDistance, 0f, 0f ); rotationPos = rotateY( rotationPos, thetaY ); bool tempBool = false; for ( int j = 0; j < temp.Count; j++ ) { if ( (Vector3) temp[j] == rotationPos ) { tempBool = true; break; } } if ( !tempBool ) { temp.Add( rotationPos ); } thetaY += CARY * Mathf.Deg2Rad; } else { Vector3 rotationPos = new Vector3( parent.crystalDistance, 0f, 0f ); rotationPos = rotateZ( rotationPos, thetaZ ); bool tempBool = false; for ( int j = 0; j < temp.Count; j++ ) { if ( (Vector3) temp[j] == rotationPos ) { tempBool = true; break; } } if ( !tempBool ) { temp.Add(rotationPos); } thetaZ += CARZ * Mathf.Deg2Rad; } } count = temp.Count; siteCoords = new Vector3[temp.Count]; for ( int i = 0; i < temp.Count; i++ ) { siteCoords[i] = (Vector3) temp[i]; } return siteCoords; } public Vector3 getVelocity () { return velocity; } public BoidGroupController getParent () { return parent; } public Vector3[] getCrystalSites () { return crystalSites; } public bool isLocked ( int index ) { return siteLock[index]; } public void lockSite ( int index ) { siteLock[index] = true; } public void unlockSite ( int index ) { siteLock[index] = false; } public bool hasFreeSites() { bool temp = false; for ( int i = 0; i < count; i++ ) { if ( isLocked(i) == false ) { temp = true; break; } } return temp; } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Text; using Epi.Analysis; using Epi.Windows.Dialogs; using Epi.Windows.Analysis; namespace Epi.Windows.Analysis.Dialogs { /// <summary> /// Dialog for Match command /// </summary> public partial class MatchDialog : CommandDesignDialog { #region Constructor /// <summary> /// Default constructor - NOT TO BE USED FOR INSTANTIATION /// </summary> [Obsolete("Use of default constructor not allowed", true)] public MatchDialog() { InitializeComponent(); } /// <summary> /// /// </summary> /// <param name="frm"></param> public MatchDialog(Epi.Windows.Analysis.Forms.AnalysisMainForm frm) : base(frm) { InitializeComponent(); Construct(); } #endregion Constructors #region Private Properties string strExposure = ""; string strOutcome = ""; string strWeight = ""; #endregion Private Properties #region Private Methods private void Construct() { if (!this.DesignMode) { this.btnOK.Click += new System.EventHandler(this.btnOK_Click); this.btnSaveOnly.Click += new System.EventHandler(this.btnSaveOnly_Click); } } #endregion Private Methods #region Event Handlers private void btnClear_Click(object sender, System.EventArgs e) { cmbOutcomeVar.Items.Clear(); cmbExpVar.Items.Clear(); cmbWeight.Items.Clear(); lbxMatchVars.Items.Clear(); MatchDialog_Load(this, null); } /// <summary> /// Event handler for some unimportant that has changed so that OK button can be conditioned /// </summary> /// <param name="sender">Object that fired the event</param> /// <param name="e">.NET supplied event parameters</param> private void SomethingChanged(object sender, EventArgs e) { CheckForInputSufficiency(); } /// <summary> /// Handles the SelectedIndexChanged event /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbOutcomeVar_SelectedIndexChanged(object sender, EventArgs e) { if (cmbOutcomeVar.SelectedIndex >= 0) { //Get the old variable chosen that was saved to the txt string. string strOld = strOutcome; string strNew = cmbOutcomeVar.Text; //make sure it isn't "" or the same as the new variable picked. if ((strOld.Length != 0) && (strOld != strNew)) { //add the former variable chosen back into the other lists //cmbOutcomeVar.Items.Add(strOld); cmbExpVar.Items.Add(strOld); cmbMatchVar.Items.Add(strOld); cmbWeight.Items.Add(strOld); } //record the new variable and remove it from the other lists strOutcome = strNew; //cmbOutcomeVar.Items.Remove(strNew); cmbExpVar.Items.Remove(strNew); cmbMatchVar.Items.Remove(strNew); cmbWeight.Items.Remove(strNew); } CheckForInputSufficiency(); } /// <summary> /// Handles the SelectedIndexChanged event /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbExpVar_SelectedIndexChanged(object sender, EventArgs e) { if (cmbExpVar.SelectedIndex >= 0) { //Get the old variable chosen that was saved to the txt string. string strOld = strExposure; string strNew = cmbExpVar.Text; //make sure it isn't "" or the same as the new variable picked. if ((strOld.Length != 0) && (strOld != strNew)) { //add the former variable chosen back into the other lists cmbOutcomeVar.Items.Add(strOld); //cmbExpVar.Items.Add(strOld); cmbMatchVar.Items.Add(strOld); cmbWeight.Items.Add(strOld); } //record the new variable and remove it from the other lists strExposure = strNew; cmbOutcomeVar.Items.Remove(strNew); //cmbExpVar.Items.Remove(strNew); cmbMatchVar.Items.Remove(strNew); cmbWeight.Items.Remove(strNew); } CheckForInputSufficiency(); } /// <summary> /// Handles the Attach Event for the form, fills all of the dialogs with a list of variables. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void MatchDialog_Load(object sender, EventArgs e) { VariableType scopeWord = VariableType.DataSource | VariableType.DataSourceRedefined | VariableType.Standard | VariableType.Global | VariableType.Permanent; FillVariableCombo(cmbOutcomeVar, scopeWord); cmbOutcomeVar.SelectedIndex = -1; FillVariableCombo(cmbExpVar, scopeWord); cmbExpVar.SelectedIndex = -1; FillVariableCombo(cmbMatchVar, scopeWord); cmbExpVar.SelectedIndex = -1; FillVariableCombo(cmbWeight, scopeWord); cmbWeight.SelectedIndex = -1; } /// <summary> /// Handles the Selected Index Change event for lbxMatchVars. /// Moves the variable name back to the comboboxes /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void lbxMatchVars_SelectedIndexChanged(object sender, EventArgs e) { if (lbxMatchVars.SelectedIndex >= 0) // prevent the remove below from re-entering { string s = this.lbxMatchVars.SelectedItem.ToString(); lbxMatchVars.Items.Remove(s); //remove square brackets before adding back to DDLs char[] cTrimParens = { '[', ']' }; s = s.Trim(cTrimParens); cmbExpVar.Items.Add(s); cmbOutcomeVar.Items.Add(s); cmbWeight.Items.Add(s); cmbMatchVar.Items.Add(s); CheckForInputSufficiency(); } } private void cmbMatchVar_SelectedIndexChanged(object sender, EventArgs e) { if (cmbMatchVar.Text != string.Empty) { string s = cmbMatchVar.Text; lbxMatchVars.Items.Add(FieldNameNeedsBrackets(s) ? Util.InsertInSquareBrackets(s) : s); cmbExpVar.Items.Remove(s); cmbOutcomeVar.Items.Remove(s); cmbMatchVar.Items.Remove(s); cmbWeight.Items.Remove(s); CheckForInputSufficiency(); } } #endregion //Event Handlers #region Protected Methods /// <summary> /// Validates user input /// </summary> /// <returns>true if there is no error; else false</returns> protected override bool ValidateInput() { base.ValidateInput(); if (string.IsNullOrEmpty(cmbOutcomeVar.Text.Trim())) { ErrorMessages.Add(SharedStrings.EMPTY_VARNAME); } if (string.IsNullOrEmpty(this.cmbExpVar.Text.Trim())) { ErrorMessages.Add(SharedStrings.EMPTY_VARNAME); } if (this.cbxMatch.Checked && lbxMatchVars.Items.Count < 1) { ErrorMessages.Add(SharedStrings.EMPTY_VARNAME); } return (ErrorMessages.Count == 0); } /// <summary> /// Generates user command /// </summary> protected override void GenerateCommand() { StringBuilder sb = new StringBuilder(); if (cbxMatch.Checked) { sb.Append(CommandNames.MATCH); } else { sb.Append(CommandNames.TABLES); } sb.Append(StringLiterals.SPACE); sb.Append(cmbExpVar.Text); sb.Append(StringLiterals.SPACE); sb.Append(FieldNameNeedsBrackets(cmbOutcomeVar.Text) ? Util.InsertInSquareBrackets(cmbOutcomeVar.Text) : cmbOutcomeVar.Text); sb.Append(StringLiterals.SPACE); if (cbxMatch.Checked) { sb.Append(CommandNames.MATCHVAR); sb.Append(StringLiterals.EQUAL); foreach (string s in lbxMatchVars.Items) { sb.Append(s); sb.Append(StringLiterals.SPACE); } } else if (lbxMatchVars.Items.Count > 0) { sb.Append(CommandNames.STRATAVAR); sb.Append(StringLiterals.EQUAL); foreach (string s in this.lbxMatchVars.Items) { sb.Append(s); sb.Append(StringLiterals.SPACE); } } CommandText = sb.ToString(); } /// <summary> /// Sets enabled property of OK and Save Only /// </summary> public override void CheckForInputSufficiency() { bool inputValid = ValidateInput(); btnOK.Enabled = inputValid; btnSaveOnly.Enabled = inputValid; } #endregion Protected Methods } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Internal.TypeSystem; using Internal.IL; namespace Internal.IL { internal partial class ILImporter { private BasicBlock[] _basicBlocks; // Maps IL offset to basic block private BasicBlock _currentBasicBlock; private int _currentOffset; private BasicBlock _pendingBasicBlocks; // // IL stream reading // private byte ReadILByte() { if (_currentOffset >= _ilBytes.Length) ReportMethodEndInsideInstruction(); return _ilBytes[_currentOffset++]; } private UInt16 ReadILUInt16() { if (_currentOffset + 1 >= _ilBytes.Length) ReportMethodEndInsideInstruction(); UInt16 val = (UInt16)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8)); _currentOffset += 2; return val; } private UInt32 ReadILUInt32() { if (_currentOffset + 3 >= _ilBytes.Length) ReportMethodEndInsideInstruction(); UInt32 val = (UInt32)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8) + (_ilBytes[_currentOffset + 2] << 16) + (_ilBytes[_currentOffset + 3] << 24)); _currentOffset += 4; return val; } private int ReadILToken() { return (int)ReadILUInt32(); } private ulong ReadILUInt64() { ulong value = ReadILUInt32(); value |= (((ulong)ReadILUInt32()) << 32); return value; } private unsafe float ReadILFloat() { uint value = ReadILUInt32(); return *(float*)(&value); } private unsafe double ReadILDouble() { ulong value = ReadILUInt64(); return *(double*)(&value); } private void SkipIL(int bytes) { if (_currentOffset + (bytes - 1) >= _ilBytes.Length) ReportMethodEndInsideInstruction(); _currentOffset += bytes; } // // Basic block identification // private void FindBasicBlocks() { _basicBlocks = new BasicBlock[_ilBytes.Length]; CreateBasicBlock(0); FindJumpTargets(); FindEHTargets(); } private BasicBlock CreateBasicBlock(int offset) { BasicBlock basicBlock = _basicBlocks[offset]; if (basicBlock == null) { basicBlock = new BasicBlock() { StartOffset = offset }; _basicBlocks[offset] = basicBlock; } return basicBlock; } private void FindJumpTargets() { _currentOffset = 0; while (_currentOffset < _ilBytes.Length) { MarkInstructionBoundary(); ILOpcode opCode = (ILOpcode)ReadILByte(); again: switch (opCode) { case ILOpcode.ldarg_s: case ILOpcode.ldarga_s: case ILOpcode.starg_s: case ILOpcode.ldloc_s: case ILOpcode.ldloca_s: case ILOpcode.stloc_s: case ILOpcode.ldc_i4_s: case ILOpcode.unaligned: case ILOpcode.no: SkipIL(1); break; case ILOpcode.ldarg: case ILOpcode.ldarga: case ILOpcode.starg: case ILOpcode.ldloc: case ILOpcode.ldloca: case ILOpcode.stloc: SkipIL(2); break; case ILOpcode.ldc_i4: case ILOpcode.ldc_r4: SkipIL(4); break; case ILOpcode.ldc_i8: case ILOpcode.ldc_r8: SkipIL(8); break; case ILOpcode.jmp: case ILOpcode.call: case ILOpcode.calli: case ILOpcode.callvirt: case ILOpcode.cpobj: case ILOpcode.ldobj: case ILOpcode.ldstr: case ILOpcode.newobj: case ILOpcode.castclass: case ILOpcode.isinst: case ILOpcode.unbox: case ILOpcode.ldfld: case ILOpcode.ldflda: case ILOpcode.stfld: case ILOpcode.ldsfld: case ILOpcode.ldsflda: case ILOpcode.stsfld: case ILOpcode.stobj: case ILOpcode.box: case ILOpcode.newarr: case ILOpcode.ldelema: case ILOpcode.ldelem: case ILOpcode.stelem: case ILOpcode.unbox_any: case ILOpcode.refanyval: case ILOpcode.mkrefany: case ILOpcode.ldtoken: case ILOpcode.ldftn: case ILOpcode.ldvirtftn: case ILOpcode.initobj: case ILOpcode.constrained: case ILOpcode.sizeof_: SkipIL(4); break; case ILOpcode.prefix1: opCode = (ILOpcode)(0x100 + ReadILByte()); goto again; case ILOpcode.br_s: case ILOpcode.leave_s: { int delta = (sbyte)ReadILByte(); int target = _currentOffset + delta; if ((uint)target < (uint)_basicBlocks.Length) CreateBasicBlock(target); else ReportInvalidBranchTarget(target); } break; case ILOpcode.brfalse_s: case ILOpcode.brtrue_s: case ILOpcode.beq_s: case ILOpcode.bge_s: case ILOpcode.bgt_s: case ILOpcode.ble_s: case ILOpcode.blt_s: case ILOpcode.bne_un_s: case ILOpcode.bge_un_s: case ILOpcode.bgt_un_s: case ILOpcode.ble_un_s: case ILOpcode.blt_un_s: { int delta = (sbyte)ReadILByte(); int target = _currentOffset + delta; if ((uint)target < (uint)_basicBlocks.Length) CreateBasicBlock(target); else ReportInvalidBranchTarget(target); CreateBasicBlock(_currentOffset); } break; case ILOpcode.br: case ILOpcode.leave: { int delta = (int)ReadILUInt32(); int target = _currentOffset + delta; if ((uint)target < (uint)_basicBlocks.Length) CreateBasicBlock(target); else ReportInvalidBranchTarget(target); } break; case ILOpcode.brfalse: case ILOpcode.brtrue: case ILOpcode.beq: case ILOpcode.bge: case ILOpcode.bgt: case ILOpcode.ble: case ILOpcode.blt: case ILOpcode.bne_un: case ILOpcode.bge_un: case ILOpcode.bgt_un: case ILOpcode.ble_un: case ILOpcode.blt_un: { int delta = (int)ReadILUInt32(); int target = _currentOffset + delta; if ((uint)target < (uint)_basicBlocks.Length) CreateBasicBlock(target); else ReportInvalidBranchTarget(target); CreateBasicBlock(_currentOffset); } break; case ILOpcode.switch_: { uint count = ReadILUInt32(); int jmpBase = _currentOffset + (int)(4 * count); for (uint i = 0; i < count; i++) { int delta = (int)ReadILUInt32(); int target = jmpBase + delta; if ((uint)target < (uint)_basicBlocks.Length) CreateBasicBlock(target); else ReportInvalidBranchTarget(target); } CreateBasicBlock(_currentOffset); } break; default: continue; } } } private void FindEHTargets() { for (int i = 0; i < _exceptionRegions.Length; i++) { var r = _exceptionRegions[i]; CreateBasicBlock(r.ILRegion.TryOffset).TryStart = true; if (r.ILRegion.Kind == ILExceptionRegionKind.Filter) CreateBasicBlock(r.ILRegion.FilterOffset).FilterStart = true; CreateBasicBlock(r.ILRegion.HandlerOffset).HandlerStart = true; } } // // Basic block importing // private void ImportBasicBlocks() { _pendingBasicBlocks = _basicBlocks[0]; _basicBlocks[0].State = BasicBlock.ImportState.IsPending; while (_pendingBasicBlocks != null) { BasicBlock basicBlock = _pendingBasicBlocks; _pendingBasicBlocks = basicBlock.Next; StartImportingBasicBlock(basicBlock); ImportBasicBlock(basicBlock); EndImportingBasicBlock(basicBlock); } } private void MarkBasicBlock(BasicBlock basicBlock) { if (basicBlock.State == BasicBlock.ImportState.Unmarked) { // Link basicBlock.Next = _pendingBasicBlocks; _pendingBasicBlocks = basicBlock; basicBlock.State = BasicBlock.ImportState.IsPending; } } private void ImportBasicBlock(BasicBlock basicBlock) { _currentBasicBlock = basicBlock; _currentOffset = basicBlock.StartOffset; for (;;) { StartImportingInstruction(); ILOpcode opCode = (ILOpcode)ReadILByte(); again: switch (opCode) { case ILOpcode.nop: ImportNop(); break; case ILOpcode.break_: ImportBreak(); break; case ILOpcode.ldarg_0: case ILOpcode.ldarg_1: case ILOpcode.ldarg_2: case ILOpcode.ldarg_3: ImportLoadVar(opCode - ILOpcode.ldarg_0, true); break; case ILOpcode.ldloc_0: case ILOpcode.ldloc_1: case ILOpcode.ldloc_2: case ILOpcode.ldloc_3: ImportLoadVar(opCode - ILOpcode.ldloc_0, false); break; case ILOpcode.stloc_0: case ILOpcode.stloc_1: case ILOpcode.stloc_2: case ILOpcode.stloc_3: ImportStoreVar(opCode - ILOpcode.stloc_0, false); break; case ILOpcode.ldarg_s: ImportLoadVar(ReadILByte(), true); break; case ILOpcode.ldarga_s: ImportAddressOfVar(ReadILByte(), true); break; case ILOpcode.starg_s: ImportStoreVar(ReadILByte(), true); break; case ILOpcode.ldloc_s: ImportLoadVar(ReadILByte(), false); break; case ILOpcode.ldloca_s: ImportAddressOfVar(ReadILByte(), false); break; case ILOpcode.stloc_s: ImportStoreVar(ReadILByte(), false); break; case ILOpcode.ldnull: ImportLoadNull(); break; case ILOpcode.ldc_i4_m1: ImportLoadInt(-1, StackValueKind.Int32); break; case ILOpcode.ldc_i4_0: case ILOpcode.ldc_i4_1: case ILOpcode.ldc_i4_2: case ILOpcode.ldc_i4_3: case ILOpcode.ldc_i4_4: case ILOpcode.ldc_i4_5: case ILOpcode.ldc_i4_6: case ILOpcode.ldc_i4_7: case ILOpcode.ldc_i4_8: ImportLoadInt(opCode - ILOpcode.ldc_i4_0, StackValueKind.Int32); break; case ILOpcode.ldc_i4_s: ImportLoadInt((sbyte)ReadILByte(), StackValueKind.Int32); break; case ILOpcode.ldc_i4: ImportLoadInt((int)ReadILUInt32(), StackValueKind.Int32); break; case ILOpcode.ldc_i8: ImportLoadInt((long)ReadILUInt64(), StackValueKind.Int64); break; case ILOpcode.ldc_r4: ImportLoadFloat(ReadILFloat()); break; case ILOpcode.ldc_r8: ImportLoadFloat(ReadILDouble()); break; case ILOpcode.dup: ImportDup(); break; case ILOpcode.pop: ImportPop(); break; case ILOpcode.jmp: ImportJmp(ReadILToken()); EndImportingInstruction(); return; case ILOpcode.call: ImportCall(opCode, ReadILToken()); break; case ILOpcode.calli: ImportCalli(ReadILToken()); break; case ILOpcode.ret: ImportReturn(); EndImportingInstruction(); return; case ILOpcode.br_s: case ILOpcode.brfalse_s: case ILOpcode.brtrue_s: case ILOpcode.beq_s: case ILOpcode.bge_s: case ILOpcode.bgt_s: case ILOpcode.ble_s: case ILOpcode.blt_s: case ILOpcode.bne_un_s: case ILOpcode.bge_un_s: case ILOpcode.bgt_un_s: case ILOpcode.ble_un_s: case ILOpcode.blt_un_s: { int delta = (sbyte)ReadILByte(); ImportBranch(opCode + (ILOpcode.br - ILOpcode.br_s), _basicBlocks[_currentOffset + delta], (opCode != ILOpcode.br_s) ? _basicBlocks[_currentOffset] : null); } EndImportingInstruction(); return; case ILOpcode.br: case ILOpcode.brfalse: case ILOpcode.brtrue: case ILOpcode.beq: case ILOpcode.bge: case ILOpcode.bgt: case ILOpcode.ble: case ILOpcode.blt: case ILOpcode.bne_un: case ILOpcode.bge_un: case ILOpcode.bgt_un: case ILOpcode.ble_un: case ILOpcode.blt_un: { int delta = (int)ReadILUInt32(); ImportBranch(opCode, _basicBlocks[_currentOffset + delta], (opCode != ILOpcode.br) ? _basicBlocks[_currentOffset] : null); } EndImportingInstruction(); return; case ILOpcode.switch_: { uint count = ReadILUInt32(); int jmpBase = _currentOffset + (int)(4 * count); int[] jmpDelta = new int[count]; for (uint i = 0; i < count; i++) jmpDelta[i] = (int)ReadILUInt32(); ImportSwitchJump(jmpBase, jmpDelta, _basicBlocks[_currentOffset]); } EndImportingInstruction(); return; case ILOpcode.ldind_i1: ImportLoadIndirect(WellKnownType.SByte); break; case ILOpcode.ldind_u1: ImportLoadIndirect(WellKnownType.Byte); break; case ILOpcode.ldind_i2: ImportLoadIndirect(WellKnownType.Int16); break; case ILOpcode.ldind_u2: ImportLoadIndirect(WellKnownType.UInt16); break; case ILOpcode.ldind_i4: ImportLoadIndirect(WellKnownType.Int32); break; case ILOpcode.ldind_u4: ImportLoadIndirect(WellKnownType.UInt32); break; case ILOpcode.ldind_i8: ImportLoadIndirect(WellKnownType.Int64); break; case ILOpcode.ldind_i: ImportLoadIndirect(WellKnownType.IntPtr); break; case ILOpcode.ldind_r4: ImportLoadIndirect(WellKnownType.Single); break; case ILOpcode.ldind_r8: ImportLoadIndirect(WellKnownType.Double); break; case ILOpcode.ldind_ref: ImportLoadIndirect(null); break; case ILOpcode.stind_ref: ImportStoreIndirect(null); break; case ILOpcode.stind_i1: ImportStoreIndirect(WellKnownType.SByte); break; case ILOpcode.stind_i2: ImportStoreIndirect(WellKnownType.Int16); break; case ILOpcode.stind_i4: ImportStoreIndirect(WellKnownType.Int32); break; case ILOpcode.stind_i8: ImportStoreIndirect(WellKnownType.Int64); break; case ILOpcode.stind_r4: ImportStoreIndirect(WellKnownType.Single); break; case ILOpcode.stind_r8: ImportStoreIndirect(WellKnownType.Double); break; case ILOpcode.add: case ILOpcode.sub: case ILOpcode.mul: case ILOpcode.div: case ILOpcode.div_un: case ILOpcode.rem: case ILOpcode.rem_un: case ILOpcode.and: case ILOpcode.or: case ILOpcode.xor: ImportBinaryOperation(opCode); break; case ILOpcode.shl: case ILOpcode.shr: case ILOpcode.shr_un: ImportShiftOperation(opCode); break; case ILOpcode.neg: case ILOpcode.not: ImportUnaryOperation(opCode); break; case ILOpcode.conv_i1: ImportConvert(WellKnownType.SByte, false, false); break; case ILOpcode.conv_i2: ImportConvert(WellKnownType.Int16, false, false); break; case ILOpcode.conv_i4: ImportConvert(WellKnownType.Int32, false, false); break; case ILOpcode.conv_i8: ImportConvert(WellKnownType.Int64, false, false); break; case ILOpcode.conv_r4: ImportConvert(WellKnownType.Single, false, false); break; case ILOpcode.conv_r8: ImportConvert(WellKnownType.Double, false, false); break; case ILOpcode.conv_u4: ImportConvert(WellKnownType.UInt32, false, false); break; case ILOpcode.conv_u8: ImportConvert(WellKnownType.UInt64, false, false); break; case ILOpcode.callvirt: ImportCall(opCode, ReadILToken()); break; case ILOpcode.cpobj: ImportCpOpj(ReadILToken()); break; case ILOpcode.ldobj: ImportLoadIndirect(ReadILToken()); break; case ILOpcode.ldstr: ImportLoadString(ReadILToken()); break; case ILOpcode.newobj: ImportCall(opCode, ReadILToken()); break; case ILOpcode.castclass: case ILOpcode.isinst: ImportCasting(opCode, ReadILToken()); break; case ILOpcode.conv_r_un: ImportConvert(WellKnownType.Double, false, true); break; case ILOpcode.unbox: ImportUnbox(ReadILToken(), opCode); break; case ILOpcode.throw_: ImportThrow(); EndImportingInstruction(); return; case ILOpcode.ldfld: ImportLoadField(ReadILToken(), false); break; case ILOpcode.ldflda: ImportAddressOfField(ReadILToken(), false); break; case ILOpcode.stfld: ImportStoreField(ReadILToken(), false); break; case ILOpcode.ldsfld: ImportLoadField(ReadILToken(), true); break; case ILOpcode.ldsflda: ImportAddressOfField(ReadILToken(), true); break; case ILOpcode.stsfld: ImportStoreField(ReadILToken(), true); break; case ILOpcode.stobj: ImportStoreIndirect(ReadILToken()); break; case ILOpcode.conv_ovf_i1_un: ImportConvert(WellKnownType.SByte, true, true); break; case ILOpcode.conv_ovf_i2_un: ImportConvert(WellKnownType.Int16, true, true); break; case ILOpcode.conv_ovf_i4_un: ImportConvert(WellKnownType.Int32, true, true); break; case ILOpcode.conv_ovf_i8_un: ImportConvert(WellKnownType.Int64, true, true); break; case ILOpcode.conv_ovf_u1_un: ImportConvert(WellKnownType.Byte, true, true); break; case ILOpcode.conv_ovf_u2_un: ImportConvert(WellKnownType.UInt16, true, true); break; case ILOpcode.conv_ovf_u4_un: ImportConvert(WellKnownType.UInt32, true, true); break; case ILOpcode.conv_ovf_u8_un: ImportConvert(WellKnownType.UInt64, true, true); break; case ILOpcode.conv_ovf_i_un: ImportConvert(WellKnownType.IntPtr, true, true); break; case ILOpcode.conv_ovf_u_un: ImportConvert(WellKnownType.UIntPtr, true, true); break; case ILOpcode.box: ImportBox(ReadILToken()); break; case ILOpcode.newarr: ImportNewArray(ReadILToken()); break; case ILOpcode.ldlen: ImportLoadLength(); break; case ILOpcode.ldelema: ImportAddressOfElement(ReadILToken()); break; case ILOpcode.ldelem_i1: ImportLoadElement(WellKnownType.SByte); break; case ILOpcode.ldelem_u1: ImportLoadElement(WellKnownType.Byte); break; case ILOpcode.ldelem_i2: ImportLoadElement(WellKnownType.Int16); break; case ILOpcode.ldelem_u2: ImportLoadElement(WellKnownType.UInt16); break; case ILOpcode.ldelem_i4: ImportLoadElement(WellKnownType.Int32); break; case ILOpcode.ldelem_u4: ImportLoadElement(WellKnownType.UInt32); break; case ILOpcode.ldelem_i8: ImportLoadElement(WellKnownType.Int64); break; case ILOpcode.ldelem_i: ImportLoadElement(WellKnownType.IntPtr); break; case ILOpcode.ldelem_r4: ImportLoadElement(WellKnownType.Single); break; case ILOpcode.ldelem_r8: ImportLoadElement(WellKnownType.Double); break; case ILOpcode.ldelem_ref: ImportLoadElement(null); break; case ILOpcode.stelem_i: ImportStoreElement(WellKnownType.IntPtr); break; case ILOpcode.stelem_i1: ImportStoreElement(WellKnownType.SByte); break; case ILOpcode.stelem_i2: ImportStoreElement(WellKnownType.Int16); break; case ILOpcode.stelem_i4: ImportStoreElement(WellKnownType.Int32); break; case ILOpcode.stelem_i8: ImportStoreElement(WellKnownType.Int64); break; case ILOpcode.stelem_r4: ImportStoreElement(WellKnownType.Single); break; case ILOpcode.stelem_r8: ImportStoreElement(WellKnownType.Double); break; case ILOpcode.stelem_ref: ImportStoreElement(null); break; case ILOpcode.ldelem: ImportLoadElement(ReadILToken()); break; case ILOpcode.stelem: ImportStoreElement(ReadILToken()); break; case ILOpcode.unbox_any: ImportUnbox(ReadILToken(), opCode); break; case ILOpcode.conv_ovf_i1: ImportConvert(WellKnownType.SByte, true, false); break; case ILOpcode.conv_ovf_u1: ImportConvert(WellKnownType.Byte, true, false); break; case ILOpcode.conv_ovf_i2: ImportConvert(WellKnownType.Int16, true, false); break; case ILOpcode.conv_ovf_u2: ImportConvert(WellKnownType.UInt16, true, false); break; case ILOpcode.conv_ovf_i4: ImportConvert(WellKnownType.Int32, true, false); break; case ILOpcode.conv_ovf_u4: ImportConvert(WellKnownType.UInt32, true, false); break; case ILOpcode.conv_ovf_i8: ImportConvert(WellKnownType.Int64, true, false); break; case ILOpcode.conv_ovf_u8: ImportConvert(WellKnownType.UInt64, true, false); break; case ILOpcode.refanyval: ImportRefAnyVal(ReadILToken()); break; case ILOpcode.ckfinite: ImportCkFinite(); break; case ILOpcode.mkrefany: ImportMkRefAny(ReadILToken()); break; case ILOpcode.ldtoken: ImportLdToken(ReadILToken()); break; case ILOpcode.conv_u2: ImportConvert(WellKnownType.UInt16, false, false); break; case ILOpcode.conv_u1: ImportConvert(WellKnownType.Byte, false, false); break; case ILOpcode.conv_i: ImportConvert(WellKnownType.IntPtr, false, false); break; case ILOpcode.conv_ovf_i: ImportConvert(WellKnownType.IntPtr, true, false); break; case ILOpcode.conv_ovf_u: ImportConvert(WellKnownType.UIntPtr, true, false); break; case ILOpcode.add_ovf: case ILOpcode.add_ovf_un: case ILOpcode.mul_ovf: case ILOpcode.mul_ovf_un: case ILOpcode.sub_ovf: case ILOpcode.sub_ovf_un: ImportBinaryOperation(opCode); break; case ILOpcode.endfinally: //both endfinally and endfault ImportEndFinally(); EndImportingInstruction(); return; case ILOpcode.leave: { int delta = (int)ReadILUInt32(); ImportLeave(_basicBlocks[_currentOffset + delta]); } EndImportingInstruction(); return; case ILOpcode.leave_s: { int delta = (sbyte)ReadILByte(); ImportLeave(_basicBlocks[_currentOffset + delta]); } EndImportingInstruction(); return; case ILOpcode.stind_i: ImportStoreIndirect(WellKnownType.IntPtr); break; case ILOpcode.conv_u: ImportConvert(WellKnownType.UIntPtr, false, false); break; case ILOpcode.prefix1: opCode = (ILOpcode)(0x100 + ReadILByte()); goto again; case ILOpcode.arglist: ImportArgList(); break; case ILOpcode.ceq: case ILOpcode.cgt: case ILOpcode.cgt_un: case ILOpcode.clt: case ILOpcode.clt_un: ImportCompareOperation(opCode); break; case ILOpcode.ldftn: case ILOpcode.ldvirtftn: ImportLdFtn(ReadILToken(), opCode); break; case ILOpcode.ldarg: ImportLoadVar(ReadILUInt16(), true); break; case ILOpcode.ldarga: ImportAddressOfVar(ReadILUInt16(), true); break; case ILOpcode.starg: ImportStoreVar(ReadILUInt16(), true); break; case ILOpcode.ldloc: ImportLoadVar(ReadILUInt16(), false); break; case ILOpcode.ldloca: ImportAddressOfVar(ReadILUInt16(), false); break; case ILOpcode.stloc: ImportStoreVar(ReadILUInt16(), false); break; case ILOpcode.localloc: ImportLocalAlloc(); break; case ILOpcode.endfilter: ImportEndFilter(); EndImportingInstruction(); return; case ILOpcode.unaligned: ImportUnalignedPrefix(ReadILByte()); continue; case ILOpcode.volatile_: ImportVolatilePrefix(); continue; case ILOpcode.tail: ImportTailPrefix(); continue; case ILOpcode.initobj: ImportInitObj(ReadILToken()); break; case ILOpcode.constrained: ImportConstrainedPrefix(ReadILToken()); continue; case ILOpcode.cpblk: ImportCpBlk(); break; case ILOpcode.initblk: ImportInitBlk(); break; case ILOpcode.no: ImportNoPrefix(ReadILByte()); continue; case ILOpcode.rethrow: ImportRethrow(); EndImportingInstruction(); return; case ILOpcode.sizeof_: ImportSizeOf(ReadILToken()); break; case ILOpcode.refanytype: ImportRefAnyType(); break; case ILOpcode.readonly_: ImportReadOnlyPrefix(); continue; default: ReportInvalidInstruction(opCode); EndImportingInstruction(); return; } EndImportingInstruction(); // Check if control falls through the end of method. if (_currentOffset == _basicBlocks.Length) { ReportFallthroughAtEndOfMethod(); return; } BasicBlock nextBasicBlock = _basicBlocks[_currentOffset]; if (nextBasicBlock != null) { ImportFallthrough(nextBasicBlock); return; } } } private void ImportLoadIndirect(WellKnownType wellKnownType) { ImportLoadIndirect(GetWellKnownType(wellKnownType)); } private void ImportStoreIndirect(WellKnownType wellKnownType) { ImportStoreIndirect(GetWellKnownType(wellKnownType)); } private void ImportLoadElement(WellKnownType wellKnownType) { ImportLoadElement(GetWellKnownType(wellKnownType)); } private void ImportStoreElement(WellKnownType wellKnownType) { ImportStoreElement(GetWellKnownType(wellKnownType)); } } }
namespace Microsoft.Protocols.TestSuites.MS_ASPROV { using System.Net; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; using Response = Microsoft.Protocols.TestSuites.Common.Response; /// <summary> /// This scenario is designed to test the acknowledge phase of Provision command. /// </summary> [TestClass] public class S01_AcknowledgePolicySettings : TestSuiteBase { #region Class initialize and clean up /// <summary> /// Initialize the class. /// </summary> /// <param name="testContext">VSTS test context.</param> [ClassInitialize] public static void ClassInitialize(TestContext testContext) { TestClassBase.Initialize(testContext); } /// <summary> /// Clear the class. /// </summary> [ClassCleanup] public static void ClassCleanup() { TestClassBase.Cleanup(); } #endregion /// <summary> /// This test case is intended to validate the acknowledgement phase of Provision. /// </summary> [TestCategory("MSASPROV"), TestMethod()] public void MSASPROV_S01_TC01_AcknowledgeSecurityPolicySettings() { #region Switch current user to the user who has custom policy settings. // Switch to the user who has been configured with custom policy. this.SwitchUser(this.User2Information, false); #endregion #region Download the policy settings. // Download the policy settings. ProvisionResponse provisionResponse = this.CallProvisionCommand(string.Empty, "MS-EAS-Provisioning-WBXML", "1"); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R394"); // Verify MS-ASPROV requirement: MS-ASPROV_R394 // The value of Status is 1, so this requirement can be captured. Site.CaptureRequirementIfAreEqual<byte>( 1, provisionResponse.ResponseData.Status, 394, @"[In Status (Provision)] Value 1 means Success."); string temporaryPolicyKey = provisionResponse.ResponseData.Policies.Policy.PolicyKey; // Get the policy element from the Provision response. Response.ProvisionPoliciesPolicy policy = provisionResponse.ResponseData.Policies.Policy; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R310"); // Verify MS-ASPROV requirement: MS-ASPROV_R310 // The PolicyType, PolicyKey, Status and Data elements are not null, so this requirement can be captured. Site.CaptureRequirementIfIsTrue( policy.Data != null && policy.PolicyKey != null && policy.PolicyType != null && policy.Status != 0, 310, @"[In Policy] In the initial Provision command response, the Policy element has only the following child elements: PolicyType (section 2.2.2.42) (required) PolicyKey (section 2.2.2.41) (required) Status (section 2.2.2.53) (required) Data (section 2.2.2.23) ( required)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R417"); // Verify MS-ASPROV requirement: MS-ASPROV_R417 // The PolicyType, PolicyKey, Status and Data elements are not null, so this requirement can be captured. Site.CaptureRequirementIfIsTrue( policy.Data != null && policy.PolicyKey != null && policy.PolicyType != null && policy.Status != 0, 417, @"[In Abstract Data Model] In order 1, the server response contains the policy type, policy key, data, and status code."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R378"); // Verify MS-ASPROV requirement: MS-ASPROV_R378 // The value of Status is 1, so this requirement can be captured. Site.CaptureRequirementIfAreEqual<byte>( 1, policy.Status, 378, @"[In Status (Policy)] Value 1 means Success."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R209"); // Verify MS-ASPROV requirement: MS-ASPROV_R209 // The Data element is not null, so this requirement can be captured. Site.CaptureRequirementIfIsNotNull( policy.Data, 209, @"[In Data (container Data Type)] It [Data element] is a required child element of the Policy element (section 2.2.2.40) in responses to initial Provision command requests, as specified in section 3.2.5.1.1."); // Because the user is not allowe to download attachment. // So if AttachmentsEnabled element is false then R206 will be verified. this.Site.CaptureRequirementIfAreEqual<bool>( false, policy.Data.EASProvisionDoc.AttachmentsEnabled, 206, @"[In AttachmentsEnabled] Value 0 means Attachments are not allowed to be downloaded."); // Because if the Data element is a container Data type, then the Data element should contain the EASProvisionDoc element. // So if the Data element contain the EASProvisionDoc element and the PolicyType element is set to "MS-EAS-Provisioning-WBXML", then R888 will be verified. this.Site.CaptureRequirementIfIsTrue( policy.Data.EASProvisionDoc != null && policy.PolicyType == "MS-EAS-Provisioning-WBXML", 888, @"[In Data (container Data Type)] This element [Data (container Data Type)] requires that the PolicyType element (section 2.2.2.42) is set to ""MS-EAS-Provisioning-WBXML""."); this.Site.CaptureRequirementIfIsTrue( !string.IsNullOrEmpty(policy.PolicyKey), 486, @"[In Provision Command] The server generates, stores, and sends the policy key when it responds to a Provision command request for policy settings."); #endregion #region Acknowledge the policy settings. // Acknowledge the policy settings. provisionResponse = this.CallProvisionCommand(temporaryPolicyKey, "MS-EAS-Provisioning-WBXML", "1"); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R678"); // Verify MS-ASPROV requirement: MS-ASPROV_R678 // The value of Status is 1, so this requirement can be captured. Site.CaptureRequirementIfAreEqual<byte>( 1, provisionResponse.ResponseData.Status, 678, @"[In Provision Command Errors] [The meaning of status value] 1 [is] Success."); bool isR441Verified = provisionResponse.ResponseData.Policies != null && provisionResponse.ResponseData.Status == 1; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R441"); // Verify MS-ASPROV requirement: MS-ASPROV_R441 // The Policies element is not null and the value of Status is 1, so this requirement can be captured. Site.CaptureRequirementIfIsTrue( isR441Verified, 441, @"[In Provision Command Errors] [The cause of status value 1 is] The Policies element contains information about security policies."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R650"); // Verify MS-ASPROV requirement: MS-ASPROV_R650 // The acknowledgement Provision succeeds and PolicyKey element is not null, so this requirement can be captured. Site.CaptureRequirementIfIsNotNull( temporaryPolicyKey, 650, @"[In Responding to an Initial Request] The value of the PolicyKey element (section 2.2.2.41) is a temporary policy key that will be valid only for an acknowledgment request to acknowledge the policy settings contained in the Data element."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R657"); // Verify MS-ASPROV requirement: MS-ASPROV_R657 // The command executed successfully using the temporary PolicyKey, so this requirement can be captured. Site.CaptureRequirement( 657, @"[In Responding to a Security Policy Settings Acknowledgment] The server MUST ensure that the current policy key sent by the client in a security policy settings acknowledgment matches the temporary policy key issued by the server in the response to the initial request from this client."); // Get the policy element from the Provision response. policy = provisionResponse.ResponseData.Policies.Policy; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R605"); // Verify MS-ASPROV requirement: MS-ASPROV_R605 // The PolicyType, PolicyKey and Status elements are not null, so this requirement can be captured. Site.CaptureRequirementIfIsTrue( policy.PolicyKey != null && policy.PolicyType != null && policy.Status != 0, 605, @"[In Policy] In the acknowledgment Provision command response, the Policy element has the following child elements: PolicyType (section 2.2.2.42) (required) PolicyKey (section 2.2.2.41) (required) Status (section 2.2.2.53) (required)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R419"); // Verify MS-ASPROV requirement: MS-ASPROV_R419 // The PolicyType, PolicyKey and Status elements are not null, so this requirement can be captured. Site.CaptureRequirementIfIsTrue( policy.PolicyKey != null && policy.PolicyType != null && policy.Status != 0, 419, @"[In Abstract Data Model] In order 2, the server response contains the policy type, policy key, and status code to indicate that the server recorded the client's acknowledgement."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R688"); // Verify MS-ASPROV requirement: MS-ASPROV_R688 // The value of Status is 1, so this requirement can be captured. Site.CaptureRequirementIfAreEqual<byte>( 1, policy.Status, 688, @"[In Provision Command Errors] [The meaning of status value] 1 [is] Success."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R466"); // Verify MS-ASPROV requirement: MS-ASPROV_R466 // The value of Status is 1, so this requirement can be captured. Site.CaptureRequirementIfAreEqual<byte>( 1, policy.Status, 466, @"[In Provision Command Errors] [The cause of status value 1 is] The requested policy data is included in the response."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R703"); // Verify MS-ASPROV requirement: MS-ASPROV_R703 // The value of Status is 1, so this requirement can be captured. Site.CaptureRequirementIfAreEqual<byte>( 1, policy.Status, 703, @"[In Provision Command Errors] [When the scope is] Policy, [the meaning of status value] 1 [is] Success."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R495"); // Verify MS-ASPROV requirement: MS-ASPROV_R495 // The value of Status is 1, so this requirement can be captured. Site.CaptureRequirementIfAreEqual<byte>( 1, policy.Status, 495, @"[In Provision Command Errors] [When the scope is Policy], [the cause of status value 1 is] The requested policy data is included in the response."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R601"); // Verify MS-ASPROV requirement: MS-ASPROV_R601 // The Data element is null, so this requirement can be captured. Site.CaptureRequirementIfIsNull( policy.Data, 601, @"[In Data (container Data Type)] It [Data element] is not present in responses to acknowledgment requests, as specified in section 3.2.5.1.2."); #endregion #region Apply the final policy key got from acknowledgement Provision response. // Get the final policy key from the Provision command response. string finalPolicyKey = provisionResponse.ResponseData.Policies.Policy.PolicyKey; // Apply the final policy key for the subsequence commands. this.PROVAdapter.ApplyPolicyKey(finalPolicyKey); #endregion #region Call FolderSync command with the final policy key. FolderSyncRequest folderSyncRequest = Common.CreateFolderSyncRequest("0"); FolderSyncResponse folderSynReponse = this.PROVAdapter.FolderSync(folderSyncRequest); Site.Assert.AreEqual(folderSynReponse.StatusCode, HttpStatusCode.OK, "Server should return a HTTP expected status code [{0}] after apply Policy Key, actual is [{1}]", HttpStatusCode.OK, folderSynReponse.StatusCode); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R662"); // Verify MS-ASPROV requirement: MS-ASPROV_R662 // The FolderSync command executed successfully after the final policy key is applied, so this requirement can be captured. Site.CaptureRequirementIfIsNotNull( finalPolicyKey, 662, @"[In Responding to a Security Policy Settings Acknowledgment] The value of the PolicyKey element (section 2.2.2.41) is a permanent policy key that is valid for subsequent command requests from the client."); #endregion } /// <summary> /// This test case is intended to validate command could be executed successfully without acknowledging security policy settings if a security policy is set on the implementation to allow it. /// </summary> [TestCategory("MSASPROV"), TestMethod()] public void MSASPROV_S01_TC02_WithoutAcknowledgingSecurityPolicySettings() { #region Switch the current user to the user with setting AllowNonProvisionableDevices to true. this.SwitchUser(this.User3Information, false); #endregion #region Apply string.Empty to PolicyKey. this.PROVAdapter.ApplyPolicyKey(string.Empty); #endregion #region Call FolderSync command without Provision. FolderSyncRequest folderSyncRequest = Common.CreateFolderSyncRequest("0"); FolderSyncResponse folderSynReponse = this.PROVAdapter.FolderSync(folderSyncRequest); Site.Assert.AreEqual(folderSynReponse.StatusCode, HttpStatusCode.OK, "Server should return a HTTP expected status code [{0}], actual is [{1}]", HttpStatusCode.OK, folderSynReponse.StatusCode); if (Common.IsRequirementEnabled(509, this.Site)) { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASPROV_R509"); // Verify MS-ASPROV requirement: MS-ASPROV_R509 // The FolderSync command executed successfully without Provision, so this requirement can be captured. Site.CaptureRequirement( 509, @"[In Appendix A: Product Behavior] The implementation does require that the client device has requested and acknowledged the security policy settings before the client is allowed to synchronize with the server, unless a security policy is set on the implementation to allow it [client is allowed to synchronize with the implementation]. (Exchange 2007 and above follow this behavior.)"); } #endregion } /// <summary> /// This test case is intended to test when a policy setting that was previously set is unset on the server. /// </summary> [TestCategory("MSASPROV"), TestMethod()] public void MSASPROV_S01_TC03_InitialPreviouslySettingUnset() { #region Download the policy settings. // Download the policy settings. ProvisionResponse provisionResponse = this.CallProvisionCommand(string.Empty, "MS-EAS-Provisioning-WBXML", "1"); // Because the user is allowe to download attachment. // So if AttachmentsEnabled element is true then R207 will be verified. this.Site.CaptureRequirementIfAreEqual<bool>( true, provisionResponse.ResponseData.Policies.Policy.Data.EASProvisionDoc.AttachmentsEnabled, 207, @"[In AttachmentsEnabled] Value 1 means Attachments are allowed to be downloaded."); if (Common.IsRequirementEnabled(1044, this.Site)) { // Because the MinDevicePasswordLength is unset in previously set on the server. // So if the MinDevicePasswordLength element is emtry string then R1044 will be verified. this.Site.CaptureRequirementIfIsTrue( string.IsNullOrEmpty(provisionResponse.ResponseData.Policies.Policy.Data.EASProvisionDoc.MinDevicePasswordLength), 1044, @"[In Appendix B: Product Behavior] When a policy setting that was previously set is unset on the server, the implementation does specify the element that represents the setting as an empty tag [or a default value]. (Exchange 2007 and above follow this behavior.)"); } if (Common.IsRequirementEnabled(1045, this.Site)) { // Because the DevicePasswordHistory is unset in previously set on the server. // So if the DevicePasswordHistory element is default value(0) then R1045 will be verified. this.Site.CaptureRequirementIfIsTrue( provisionResponse.ResponseData.Policies.Policy.Data.EASProvisionDoc.DevicePasswordHistory == 0, 1045, @"[In Appendix B: Product Behavior] When a policy setting that was previously set is unset on the server, the implementation does specify the element that represents the setting as [an empty tag or] a default value. (Exchange 2007 and above follow this behavior.)"); } #endregion } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using MySql.Data.MySqlClient; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using System; using System.Collections.Generic; using System.Data; using System.Reflection; namespace OpenSim.Data.MySQL { public class MySQLEstateStore : IEstateDataStore { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const string m_waitTimeoutSelect = "select @@wait_timeout"; private string m_connectionString; private long m_waitTimeout; private long m_waitTimeoutLeeway = 60 * TimeSpan.TicksPerSecond; // private long m_lastConnectionUse; private FieldInfo[] m_Fields; private Dictionary<string, FieldInfo> m_FieldMap = new Dictionary<string, FieldInfo>(); protected virtual Assembly Assembly { get { return GetType().Assembly; } } public MySQLEstateStore() { } public MySQLEstateStore(string connectionString) { Initialise(connectionString); } public void Initialise(string connectionString) { m_connectionString = connectionString; try { m_log.Info("[REGION DB]: MySql - connecting: " + Util.GetDisplayConnectionString(m_connectionString)); } catch (Exception e) { m_log.Debug("Exception: password not found in connection string\n" + e.ToString()); } GetWaitTimeout(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); Migration m = new Migration(dbcon, Assembly, "EstateStore"); m.Update(); Type t = typeof(EstateSettings); m_Fields = t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); foreach (FieldInfo f in m_Fields) { if (f.Name.Substring(0, 2) == "m_") m_FieldMap[f.Name.Substring(2)] = f; } } } private string[] FieldList { get { return new List<string>(m_FieldMap.Keys).ToArray(); } } protected void GetWaitTimeout() { using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, dbcon)) { using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (dbReader.Read()) { m_waitTimeout = Convert.ToInt32(dbReader["@@wait_timeout"]) * TimeSpan.TicksPerSecond + m_waitTimeoutLeeway; } } } // m_lastConnectionUse = DateTime.Now.Ticks; m_log.DebugFormat( "[REGION DB]: Connection wait timeout {0} seconds", m_waitTimeout / TimeSpan.TicksPerSecond); } } public EstateSettings LoadEstateSettings(UUID regionID, bool create) { string sql = "select estate_settings." + String.Join(",estate_settings.", FieldList) + " from estate_map left join estate_settings on estate_map.EstateID = estate_settings.EstateID where estate_settings.EstateID is not null and RegionID = ?RegionID"; using (MySqlCommand cmd = new MySqlCommand()) { cmd.CommandText = sql; cmd.Parameters.AddWithValue("?RegionID", regionID.ToString()); return DoLoad(cmd, regionID, create); } } public EstateSettings CreateNewEstate() { EstateSettings es = new EstateSettings(); es.OnSave += StoreEstateSettings; DoCreate(es); LoadBanList(es); es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers"); es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users"); es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups"); return es; } private EstateSettings DoLoad(MySqlCommand cmd, UUID regionID, bool create) { EstateSettings es = new EstateSettings(); es.OnSave += StoreEstateSettings; using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); cmd.Connection = dbcon; bool found = false; using (IDataReader r = cmd.ExecuteReader()) { if (r.Read()) { found = true; foreach (string name in FieldList) { if (m_FieldMap[name].FieldType == typeof(bool)) { m_FieldMap[name].SetValue(es, Convert.ToInt32(r[name]) != 0); } else if (m_FieldMap[name].FieldType == typeof(UUID)) { m_FieldMap[name].SetValue(es, DBGuid.FromDB(r[name])); } else { m_FieldMap[name].SetValue(es, r[name]); } } } } if (!found && create) { DoCreate(es); LinkRegion(regionID, (int)es.EstateID); } } LoadBanList(es); es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers"); es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users"); es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups"); return es; } private void DoCreate(EstateSettings es) { // Migration case List<string> names = new List<string>(FieldList); names.Remove("EstateID"); string sql = "insert into estate_settings (" + String.Join(",", names.ToArray()) + ") values ( ?" + String.Join(", ?", names.ToArray()) + ")"; using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd2 = dbcon.CreateCommand()) { cmd2.CommandText = sql; cmd2.Parameters.Clear(); foreach (string name in FieldList) { if (m_FieldMap[name].GetValue(es) is bool) { if ((bool)m_FieldMap[name].GetValue(es)) cmd2.Parameters.AddWithValue("?" + name, "1"); else cmd2.Parameters.AddWithValue("?" + name, "0"); } else { cmd2.Parameters.AddWithValue("?" + name, m_FieldMap[name].GetValue(es).ToString()); } } cmd2.ExecuteNonQuery(); cmd2.CommandText = "select LAST_INSERT_ID() as id"; cmd2.Parameters.Clear(); using (IDataReader r = cmd2.ExecuteReader()) { r.Read(); es.EstateID = Convert.ToUInt32(r["id"]); } es.Save(); } } } public void StoreEstateSettings(EstateSettings es) { string sql = "replace into estate_settings (" + String.Join(",", FieldList) + ") values ( ?" + String.Join(", ?", FieldList) + ")"; using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = sql; foreach (string name in FieldList) { if (m_FieldMap[name].GetValue(es) is bool) { if ((bool)m_FieldMap[name].GetValue(es)) cmd.Parameters.AddWithValue("?" + name, "1"); else cmd.Parameters.AddWithValue("?" + name, "0"); } else { cmd.Parameters.AddWithValue("?" + name, m_FieldMap[name].GetValue(es).ToString()); } } cmd.ExecuteNonQuery(); } } SaveBanList(es); SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers); SaveUUIDList(es.EstateID, "estate_users", es.EstateAccess); SaveUUIDList(es.EstateID, "estate_groups", es.EstateGroups); } private void LoadBanList(EstateSettings es) { es.ClearBans(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "select bannedUUID from estateban where EstateID = ?EstateID"; cmd.Parameters.AddWithValue("?EstateID", es.EstateID); using (IDataReader r = cmd.ExecuteReader()) { while (r.Read()) { EstateBan eb = new EstateBan(); UUID uuid = new UUID(); UUID.TryParse(r["bannedUUID"].ToString(), out uuid); eb.BannedUserID = uuid; eb.BannedHostAddress = "0.0.0.0"; eb.BannedHostIPMask = "0.0.0.0"; es.AddBan(eb); } } } } } private void SaveBanList(EstateSettings es) { using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "delete from estateban where EstateID = ?EstateID"; cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString()); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); cmd.CommandText = "insert into estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask) values ( ?EstateID, ?bannedUUID, '', '', '' )"; foreach (EstateBan b in es.EstateBans) { cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString()); cmd.Parameters.AddWithValue("?bannedUUID", b.BannedUserID.ToString()); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } } } } void SaveUUIDList(uint EstateID, string table, UUID[] data) { using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "delete from " + table + " where EstateID = ?EstateID"; cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString()); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); cmd.CommandText = "insert into " + table + " (EstateID, uuid) values ( ?EstateID, ?uuid )"; foreach (UUID uuid in data) { cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString()); cmd.Parameters.AddWithValue("?uuid", uuid.ToString()); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } } } } UUID[] LoadUUIDList(uint EstateID, string table) { List<UUID> uuids = new List<UUID>(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "select uuid from " + table + " where EstateID = ?EstateID"; cmd.Parameters.AddWithValue("?EstateID", EstateID); using (IDataReader r = cmd.ExecuteReader()) { while (r.Read()) { // EstateBan eb = new EstateBan(); uuids.Add(DBGuid.FromDB(r["uuid"])); } } } } return uuids.ToArray(); } public EstateSettings LoadEstateSettings(int estateID) { using (MySqlCommand cmd = new MySqlCommand()) { string sql = "select estate_settings." + String.Join(",estate_settings.", FieldList) + " from estate_settings where EstateID = ?EstateID"; cmd.CommandText = sql; cmd.Parameters.AddWithValue("?EstateID", estateID); return DoLoad(cmd, UUID.Zero, false); } } public List<EstateSettings> LoadEstateSettingsAll() { List<EstateSettings> allEstateSettings = new List<EstateSettings>(); List<int> allEstateIds = GetEstatesAll(); foreach (int estateId in allEstateIds) allEstateSettings.Add(LoadEstateSettings(estateId)); return allEstateSettings; } public List<int> GetEstatesAll() { List<int> result = new List<int>(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "select estateID from estate_settings"; using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { result.Add(Convert.ToInt32(reader["EstateID"])); } reader.Close(); } } dbcon.Close(); } return result; } public List<int> GetEstates(string search) { List<int> result = new List<int>(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "select estateID from estate_settings where EstateName = ?EstateName"; cmd.Parameters.AddWithValue("?EstateName", search); using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { result.Add(Convert.ToInt32(reader["EstateID"])); } reader.Close(); } } dbcon.Close(); } return result; } public List<int> GetEstatesByOwner(UUID ownerID) { List<int> result = new List<int>(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "select estateID from estate_settings where EstateOwner = ?EstateOwner"; cmd.Parameters.AddWithValue("?EstateOwner", ownerID); using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { result.Add(Convert.ToInt32(reader["EstateID"])); } reader.Close(); } } dbcon.Close(); } return result; } public bool LinkRegion(UUID regionID, int estateID) { using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); MySqlTransaction transaction = dbcon.BeginTransaction(); try { // Delete any existing association of this region with an estate. using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.Transaction = transaction; cmd.CommandText = "delete from estate_map where RegionID = ?RegionID"; cmd.Parameters.AddWithValue("?RegionID", regionID); cmd.ExecuteNonQuery(); } using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.Transaction = transaction; cmd.CommandText = "insert into estate_map values (?RegionID, ?EstateID)"; cmd.Parameters.AddWithValue("?RegionID", regionID); cmd.Parameters.AddWithValue("?EstateID", estateID); int ret = cmd.ExecuteNonQuery(); if (ret != 0) transaction.Commit(); else transaction.Rollback(); dbcon.Close(); return (ret != 0); } } catch (MySqlException ex) { m_log.Error("[REGION DB]: LinkRegion failed: " + ex.Message); transaction.Rollback(); } dbcon.Close(); } return false; } public List<UUID> GetRegions(int estateID) { List<UUID> result = new List<UUID>(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); try { using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "select RegionID from estate_map where EstateID = ?EstateID"; cmd.Parameters.AddWithValue("?EstateID", estateID.ToString()); using (IDataReader reader = cmd.ExecuteReader()) { while(reader.Read()) result.Add(DBGuid.FromDB(reader["RegionID"])); reader.Close(); } } } catch (Exception e) { m_log.Error("[REGION DB]: Error reading estate map. " + e.ToString()); return result; } dbcon.Close(); } return result; } public bool DeleteEstate(int estateID) { return false; } } }
using Loon.Core.Timer; using Loon.Core.Graphics.Opengl; using System.Collections.Generic; using System.Runtime.CompilerServices; using Loon.Core.Input; namespace Loon.Core.Graphics.Component { public class LSelect : LContainer { private LFont messageFont = LFont.GetDefaultFont(); private LColor fontColor = LColor.white; private int left, top, type, nTop; private int sizeFont, doubleSizeFont, tmpOffset, messageLeft, nLeft, messageTop, selectSize, selectFlag; private float autoAlpha; private LTimer delay; private string[] selects; private string message, result; private LTexture cursor, buoyage; private bool isAutoAlpha, isSelect; public LSelect(int x, int y, int width, int height):this((LTexture) null, x, y, width, height) { } public LSelect(string fileName):this(fileName, 0, 0) { } public LSelect(string fileName, int x, int y):this(LTextures.LoadTexture(fileName), x, y) { } public LSelect(LTexture formImage):this(formImage, 0, 0) { } public LSelect(LTexture formImage, int x, int y):this(formImage, x, y, formImage.GetWidth(), formImage.GetHeight()) { } public LSelect(LTexture formImage, int x, int y, int width, int height):base(x, y, width, height) { if (formImage == null) { this.SetBackground(new LTexture(width, height, true, Loon.Core.Graphics.Opengl.LTexture.Format.SPEED)); this.SetAlpha(0.3F); } else { this.SetBackground(formImage); } this.customRendering = true; this.selectFlag = 1; this.tmpOffset = -(width / 10); this.delay = new LTimer(150); this.autoAlpha = 0.25F; this.isAutoAlpha = true; this.SetCursor(XNAConfig.LoadTex(LSystem.FRAMEWORK_IMG_NAME + "creese.png")); this.SetElastic(true); this.SetLocked(true); this.SetLayer(100); } public void SetLeftOffset(int left) { this.left = left; } public void SetTopOffset(int top) { this.top = top; } public int GetLeftOffset() { return left; } public int GetTopOffset() { return top; } public int GetResultIndex() { return selectFlag - 1; } public void SetDelay(long timer) { delay.SetDelay(timer); } public long GetDelay() { return delay.GetDelay(); } public string GetResult() { return result; } private static string[] GetListToStrings(IList<string> list) { if (list == null || list.Count == 0) return null; string[] rs = new string[list.Count]; for (int i = 0; i < rs.Length; i++) { rs[i] = list[i]; } return rs; } public void SetMessage(string mes, IList<string> list) { SetMessage(mes, GetListToStrings(list)); } public void SetMessage(string[] sel) { SetMessage(null, sel); } public void SetMessage(string mes, string[] sel) { this.message = mes; this.selects = sel; this.selectSize = sel.Length; if (doubleSizeFont == 0) { doubleSizeFont = 20; } } public override void Update(long elapsedTime) { if (!visible) { return; } base.Update(elapsedTime); if (isAutoAlpha && buoyage != null) { if (delay.Action(elapsedTime)) { if (autoAlpha < 0.95F) { autoAlpha += 0.05F; } else { autoAlpha = 0.25F; } } } } protected internal override void CreateCustomUI(GLEx g, int x, int y, int w, int h) { if (!visible) { return; } LColor oldColor = g.GetColor(); LFont oldFont = g.GetFont(); g.SetColor(fontColor); g.SetFont(messageFont); sizeFont = messageFont.GetSize(); doubleSizeFont = sizeFont * 2; if (doubleSizeFont == 0) { doubleSizeFont = 20; } messageLeft = (x + doubleSizeFont + sizeFont / 2) + tmpOffset + left + doubleSizeFont; // g.setAntiAlias(true); if (message != null) { messageTop = y + doubleSizeFont + top + 2; g.DrawString(message, messageLeft, messageTop); } else { messageTop = y + top + 2; } nTop = messageTop; if (selects != null) { nLeft = messageLeft - sizeFont / 4; for (int i = 0; i < selects.Length; i++) { nTop += 30; type = i + 1; isSelect = (type == ((selectFlag > 0) ? selectFlag : 1)); if ((buoyage != null) && isSelect) { g.SetAlpha(autoAlpha); g.DrawTexture(buoyage, nLeft, nTop - (int)(buoyage.GetHeight() / 1.5f)); g.SetAlpha(1.0F); } g.DrawString(selects[i], messageLeft, nTop); if ((cursor != null) && isSelect) { g.DrawTexture(cursor, nLeft, nTop - cursor.GetHeight() / 2, LColor.white); } } } // g.setAntiAlias(false); g.SetColor(oldColor); g.SetFont(oldFont); } private bool onClick; public void DoClick() { if (Click != null) { Click.DoClick(this); } } public bool IsClick() { return onClick; } protected internal override void ProcessTouchClicked() { if (!input.IsMoving()) { if ((selects != null) && (selectFlag > 0)) { this.result = selects[selectFlag - 1]; } this.DoClick(); this.onClick = true; } else { this.onClick = false; } } [MethodImpl(MethodImplOptions.Synchronized)] protected internal override void ProcessTouchMoved() { if (selects != null) { int touchY = input.GetTouchY(); selectFlag = selectSize - (((nTop + 30) - ((touchY == 0) ? 1 : touchY)) / doubleSizeFont); if (selectFlag < 1) { selectFlag = 0; } if (selectFlag > selectSize) { selectFlag = selectSize; } } } protected internal override void ProcessKeyPressed() { if (this.IsSelected() && this.input.GetKeyPressed() == Key.ENTER) { this.DoClick(); } } protected internal override void ProcessTouchDragged() { ProcessTouchMoved(); if (!locked) { if (GetContainer() != null) { GetContainer().SendToFront(this); } this.Move(this.input.GetTouchDX(), this.input.GetTouchDY()); } } public LColor GetFontColor() { return fontColor; } public void SetFontColor(LColor fontColor) { this.fontColor = fontColor; } public LFont GetMessageFont() { return messageFont; } public void SetMessageFont(LFont messageFont) { this.messageFont = messageFont; } public bool IsLocked() { return locked; } public void SetLocked(bool locked) { this.locked = locked; } public LTexture GetCursor() { return cursor; } public void SetNotCursor() { this.cursor = null; } public void SetCursor(LTexture cursor) { this.cursor = cursor; } public void SetCursor(string fileName) { SetCursor(new LTexture(fileName)); } public LTexture GetBuoyage() { return buoyage; } public void SetNotBuoyage() { this.cursor = null; } public void SetBuoyage(LTexture buoyage) { this.buoyage = buoyage; } public void SetBuoyage(string fileName) { SetBuoyage(new LTexture(fileName)); } public bool IsFlashBuoyage() { return isAutoAlpha; } public void SetFlashBuoyage(bool flashBuoyage) { this.isAutoAlpha = flashBuoyage; } public override void CreateUI(GLEx g, int x, int y, LComponent component, LTexture[] buttonImage) { } public override string GetUIName() { return "Select"; } } }
#region License // // Formatter.cs July 2006 // // Copyright (C) 2006, Niall Gallagher <niallg@users.sf.net> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // #endregion #region Using directives using System.IO; using System; #endregion namespace SimpleFramework.Xml.Stream { /// <summary> /// The <c>Formatter</c> object is used to format output as XML /// indented with a configurable indent level. This is used to write /// start and end tags, as well as attributes and values to the given /// writer. The output is written directly to the stream with and /// indentation for each element appropriate to its position in the /// document hierarchy. If the indent is set to zero then no indent /// is performed and all XML will appear on the same line. /// </summary> /// <seealso> /// SimpleFramework.Xml.Stream.Indenter /// </seealso> class Formatter { /// <summary> /// Represents the prefix used when declaring an XML namespace. /// </summary> private const char[] Namespace = { 'x', 'm', 'l', 'n', 's' }; /// <summary> /// Represents the XML escape sequence for the less than sign. /// </summary> private const char[] Less = { '&', 'l', 't', ';'}; /// <summary> /// Represents the XML escape sequence for the greater than sign. /// </summary> private const char[] Greater = { '&', 'g', 't', ';' }; /// <summary> /// Represents the XML escape sequence for the double quote. /// </summary> private const char[] Double = { '&', 'q', 'u', 'o', 't', ';' }; /// <summary> /// Represents the XML escape sequence for the single quote. /// </summary> private const char[] Single = { '&', 'a', 'p', 'o', 's', ';' }; /// <summary> /// Represents the XML escape sequence for the ampersand sign. /// </summary> private const char[] And = { '&', 'a', 'm', 'p', ';' }; /// <summary> /// This is used to open a comment section within the document. /// </summary> private const char[] Open = { '<', '!', '-', '-', ' ' }; /// <summary> /// This is used to close a comment section within the document. /// </summary> private const char[] Close = { ' ', '-', '-', '>' }; /// <summary> /// Output buffer used to write the generated XML result to. /// </summary> private OutputBuffer buffer; /// <summary> /// This is the writer that is used to write the XML document. /// </summary> private TextWriter result; /// <summary> /// Creates the indentations that are used buffer the XML file. /// </summary> private Indenter indenter; /// <summary> /// Represents the prolog to insert at the start of the document. /// </summary> private String prolog; /// <summary> /// Represents the last type of content that was written. /// </summary> private Tag last; /// <summary> /// Constructor for the <c>Formatter</c> object. This creates /// an object that can be used to write XML in an indented format /// to the specified writer. The XML written will be well formed. /// </summary> /// <param name="result"> /// this is where the XML should be written to /// </param> /// <param name="format"> /// this is the format object to use /// </param> public Formatter(TextWriter result, Format format){ this.indenter = new Indenter(format); this.buffer = new OutputBuffer(); this.prolog = format.Prolog; this.result = result; } /// <summary> /// This is used to write a prolog to the specified output. This is /// only written if the specified <c>Format</c> object has /// been given a non null prolog. If no prolog is specified then no /// prolog is written to the generated XML. /// </summary> public void WriteProlog() { if(prolog != null) { Write(prolog); Write("\n"); } } /// <summary> /// This is used to write any comments that have been set. The /// comment will typically be written at the start of an element /// to describe the purpose of the element or include debug data /// that can be used to determine any issues in serialization. /// </summary> /// <param name="comment"> /// this is the comment that is to be written /// </param> public void WriteComment(String comment) { String text = indenter.Top(); if(last == Tag.Start) { Append('>'); } if(text != null) { Append(text); Append(Open); Append(comment); Append(Close); } last = Tag.Comment; } /// <summary> /// This method is used to write a start tag for an element. If a /// start tag was written before this then it is closed. Before /// the start tag is written an indent is generated and placed in /// front of the tag, this is done for all but the first start tag. /// </summary> /// <param name="name"> /// this is the name of the start tag to be written /// </param> public void WriteStart(String name, String prefix) { String text = indenter.Push(); if(last == Tag.Start) { Append('>'); } Flush(); Append(text); Append('<'); if(!IsEmpty(prefix)) { Append(prefix); Append(':'); } Append(name); last = Tag.Start; } /// <summary> /// This is used to write a name value attribute pair. If the last /// tag written was not a start tag then this throws an exception. /// All attribute values written are enclosed in double quotes. /// </summary> /// <param name="name"> /// this is the name of the attribute to be written /// </param> /// <param name="value"> /// this is the value to assigne to the attribute /// </param> public void WriteAttribute(String name, String value, String prefix) { if(last != Tag.Start) { throw new NodeException("Start element required"); } Write(' '); Write(name, prefix); Write('='); Write('"'); Escape(value); Write('"'); } /// <summary> /// This is used to write the namespace to the element. This will /// write the special attribute using the prefix and reference /// specified. This will escape the reference if it is required. /// </summary> /// <param name="reference"> /// this is the namespace URI reference to use /// </param> /// <param name="prefix"> /// this is the prefix to used for the namespace /// </param> public void WriteNamespace(String reference, String prefix) { if(last != Tag.Start) { throw new NodeException("Start element required"); } Write(' '); Write(Namespace); if(!IsEmpty(prefix)) { Write(':'); Write(prefix); } Write('='); Write('"'); Escape(reference); Write('"'); } /// <summary> /// This is used to write the specified text value to the writer. /// If the last tag written was a start tag then it is closed. /// By default this will escape any illegal XML characters. /// </summary> /// <param name="text"> /// this is the text to write to the output /// </param> public void WriteText(String text) { WriteText(text, Mode.Escape); } /// <summary> /// This is used to write the specified text value to the writer. /// If the last tag written was a start tag then it is closed. /// This will use the output mode specified. /// </summary> /// <param name="text"> /// this is the text to write to the output /// </param> public void WriteText(String text, Mode mode) { if(last == Tag.Start) { Write('>'); } if(mode == Mode.Data) { Data(text); } else { Escape(text); } last = Tag.Text; } /// <summary> /// This is used to write an end element tag to the writer. This /// will close the element with a short <c>/&gt;</c> if the /// last tag written was a start tag. However if an end tag or /// some text was written then a full end tag is written. /// </summary> /// <param name="name"> /// this is the name of the element to be closed /// </param> public void WriteEnd(String name, String prefix) { String text = indenter.Pop(); if(last == Tag.Start) { Write('/'); Write('>'); } else { if(last != Tag.Text) { Write(text); } if(last != Tag.Start) { Write('<'); Write('/'); Write(name, prefix); Write('>'); } } last = Tag.End; } /// <summary> /// This is used to write a character to the output stream without /// any translation. This is used when writing the start tags and /// end tags, this is also used to write attribute names. /// </summary> /// <param name="ch"> /// this is the character to be written to the output /// </param> public void Write(char ch) { buffer.Write(result); buffer.Clear(); result.Write(ch); } /// <summary> /// This is used to write plain text to the output stream without /// any translation. This is used when writing the start tags and /// end tags, this is also used to write attribute names. /// </summary> /// <param name="plain"> /// this is the text to be written to the output /// </param> public void Write(char[] plain) { buffer.Write(result); buffer.Clear(); result.Write(plain); } /// <summary> /// This is used to write plain text to the output stream without /// any translation. This is used when writing the start tags and /// end tags, this is also used to write attribute names. /// </summary> /// <param name="plain"> /// this is the text to be written to the output /// </param> public void Write(String plain) { buffer.Write(result); buffer.Clear(); result.Write(plain); } /// <summary> /// This is used to write plain text to the output stream without /// any translation. This is used when writing the start tags and /// end tags, this is also used to write attribute names. /// </summary> /// <param name="plain"> /// this is the text to be written to the output /// </param> /// <param name="prefix"> /// this is the namespace prefix to be written /// </param> public void Write(String plain, String prefix) { buffer.Write(result); buffer.Clear(); if(!IsEmpty(prefix)) { result.Write(prefix); result.Write(':'); } result.Write(plain); } /// <summary> /// This is used to buffer a character to the output stream without /// any translation. This is used when buffering the start tags so /// that they can be reset without affecting the resulting document. /// </summary> /// <param name="ch"> /// this is the character to be written to the output /// </param> public void Append(char ch) { buffer.Append(ch); } /// <summary> /// This is used to buffer characters to the output stream without /// any translation. This is used when buffering the start tags so /// that they can be reset without affecting the resulting document. /// </summary> /// <param name="plain"> /// this is the string that is to be buffered /// </param> public void Append(char[] plain) { buffer.Append(plain); } /// <summary> /// This is used to buffer characters to the output stream without /// any translation. This is used when buffering the start tags so /// that they can be reset without affecting the resulting document. /// </summary> /// <param name="plain"> /// this is the string that is to be buffered /// </param> public void Append(String plain) { buffer.Append(plain); } /// <summary> /// This method is used to write the specified text as a CDATA block /// within the XML element. This is typically used when the value is /// large or if it must be preserved in a format that will not be /// affected by other XML parsers. For large text values this is /// also faster than performing a character by character escaping. /// </summary> /// <param name="value"> /// this is the text value to be written as CDATA /// </param> public void Data(String value) { Write("<![CDATA["); Write(value); Write("]]>"); } /// <summary> /// This is used to write the specified value to the output with /// translation to any symbol characters or non text characters. /// This will translate the symbol characters such as "&amp;", /// "&gt;", "&lt;", and "&quot;". This also writes any non text /// and non symbol characters as integer values like "&#123;". /// </summary> /// <param name="value"> /// the text value to be escaped and written /// </param> public void Escape(String value) { int size = value.Length; for(int i = 0; i < size; i++){ Escape(value[i]); } } /// <summary> /// This is used to write the specified value to the output with /// translation to any symbol characters or non text characters. /// This will translate the symbol characters such as "&amp;", /// "&gt;", "&lt;", and "&quot;". This also writes any non text /// and non symbol characters as integer values like "&#123;". /// </summary> /// <param name="ch"> /// the text character to be escaped and written /// </param> public void Escape(char ch) { char[] text = Symbol(ch); if(text != null) { Write(text); } else { Write(ch); } } /// <summary> /// This is used to flush the writer when the XML if it has been /// buffered. The flush method is used by the node writer after an /// end element has been written. Flushing ensures that buffering /// does not affect the result of the node writer. /// </summary> public void Flush() { buffer.Write(result); buffer.Clear(); result.Flush(); } /// <summary> /// This is used to convert the the specified character to unicode. /// This will simply get the decimal representation of the given /// character as a string so it can be written as an escape. /// </summary> /// <param name="ch"> /// this is the character that is to be converted /// </param> /// <returns> /// this is the decimal value of the given character /// </returns> public String Unicode(char ch) { return Convert.ToDecimal(ch).ToString(); } /// <summary> /// This method is used to determine if a root annotation value is /// an empty value. Rather than determining if a string is empty /// be comparing it to an empty string this method allows for the /// value an empty string represents to be changed in future. /// </summary> /// <param name="value"> /// this is the value to determine if it is empty /// </param> /// <returns> /// true if the string value specified is an empty value /// </returns> public bool IsEmpty(String value) { if(value != null) { return value.Length == 0; } return true; } /// <summary> /// This is used to determine if the specified character is a text /// character. If the character specified is not a text value then /// this returls true, otherwise this returns false. /// </summary> /// <param name="ch"> /// this is the character to be evaluated as text /// </param> /// <returns> /// this returns the true if the character is textual /// </returns> public bool IsText(char ch) { switch(ch) { case ' ': case '\n': case '\r': case '\t': return true; } if(ch > ' ' && ch <= 0x7E){ return ch != 0xF7; } return false; } /// <summary> /// This is used to convert the specified character to an XML text /// symbol if the specified character can be converted. If the /// character cannot be converted to a symbol null is returned. /// </summary> /// <param name="ch"> /// this is the character that is to be converted /// </param> /// <returns> /// this is the symbol character that has been resolved /// </returns> public char[] Symbol(char ch) { switch(ch) { case '<': return Less; case '>': return Greater; case '"': return Double; case '\'': return Single; case '&': return And; } return null; } /// <summary> /// This is used to enumerate the different types of tag that can /// be written. Each tag represents a state for the writer. After /// a specific tag type has been written the state of the writer /// is updated. This is needed to write well formed XML text. /// </summary> private enum Tag { Comment, Start, Text, End } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Security; namespace System.Configuration.Internal { internal sealed class InternalConfigHost : IInternalConfigHost { private const FileAttributes InvalidAttributesForWrite = FileAttributes.ReadOnly | FileAttributes.Hidden; void IInternalConfigHost.Init(IInternalConfigRoot configRoot, params object[] hostInitParams) { } void IInternalConfigHost.InitForConfiguration(ref string locationSubPath, out string configPath, out string locationConfigPath, IInternalConfigRoot configRoot, params object[] hostInitConfigurationParams) { configPath = null; locationConfigPath = null; } bool IInternalConfigHost.IsConfigRecordRequired(string configPath) { return true; } bool IInternalConfigHost.IsInitDelayed(IInternalConfigRecord configRecord) { return false; } void IInternalConfigHost.RequireCompleteInit(IInternalConfigRecord configRecord) { } public bool IsSecondaryRoot(string configPath) { // In the default there are no secondary root's return false; } string IInternalConfigHost.GetStreamName(string configPath) { throw ExceptionUtil.UnexpectedError("IInternalConfigHost.GetStreamName"); } string IInternalConfigHost.GetStreamNameForConfigSource(string streamName, string configSource) { return StaticGetStreamNameForConfigSource(streamName, configSource); } object IInternalConfigHost.GetStreamVersion(string streamName) { return StaticGetStreamVersion(streamName); } Stream IInternalConfigHost.OpenStreamForRead(string streamName) { return StaticOpenStreamForRead(streamName); } Stream IInternalConfigHost.OpenStreamForRead(string streamName, bool assertPermissions) { return StaticOpenStreamForRead(streamName); } Stream IInternalConfigHost.OpenStreamForWrite(string streamName, string templateStreamName, ref object writeContext) { return StaticOpenStreamForWrite(streamName, templateStreamName, ref writeContext); } Stream IInternalConfigHost.OpenStreamForWrite(string streamName, string templateStreamName, ref object writeContext, bool assertPermissions) { return StaticOpenStreamForWrite(streamName, templateStreamName, ref writeContext); } void IInternalConfigHost.WriteCompleted(string streamName, bool success, object writeContext) { StaticWriteCompleted(streamName, success, writeContext); } void IInternalConfigHost.WriteCompleted(string streamName, bool success, object writeContext, bool assertPermissions) { StaticWriteCompleted(streamName, success, writeContext); } void IInternalConfigHost.DeleteStream(string streamName) { StaticDeleteStream(streamName); } bool IInternalConfigHost.IsFile(string streamName) { return StaticIsFile(streamName); } bool IInternalConfigHost.SupportsChangeNotifications => false; object IInternalConfigHost.StartMonitoringStreamForChanges(string streamName, StreamChangeCallback callback) { throw ExceptionUtil.UnexpectedError("IInternalConfigHost.StartMonitoringStreamForChanges"); } void IInternalConfigHost.StopMonitoringStreamForChanges(string streamName, StreamChangeCallback callback) { throw ExceptionUtil.UnexpectedError("IInternalConfigHost.StopMonitoringStreamForChanges"); } bool IInternalConfigHost.SupportsRefresh => false; bool IInternalConfigHost.SupportsPath => false; bool IInternalConfigHost.IsDefinitionAllowed(string configPath, ConfigurationAllowDefinition allowDefinition, ConfigurationAllowExeDefinition allowExeDefinition) { return true; } void IInternalConfigHost.VerifyDefinitionAllowed(string configPath, ConfigurationAllowDefinition allowDefinition, ConfigurationAllowExeDefinition allowExeDefinition, IConfigErrorInfo errorInfo) { } bool IInternalConfigHost.SupportsLocation => false; bool IInternalConfigHost.IsAboveApplication(string configPath) { throw ExceptionUtil.UnexpectedError("IInternalConfigHost.IsAboveApplication"); } string IInternalConfigHost.GetConfigPathFromLocationSubPath(string configPath, string locationSubPath) { throw ExceptionUtil.UnexpectedError("IInternalConfigHost.GetConfigPathFromLocationSubPath"); } bool IInternalConfigHost.IsLocationApplicable(string configPath) { throw ExceptionUtil.UnexpectedError("IInternalConfigHost.IsLocationApplicable"); } bool IInternalConfigHost.PrefetchAll(string configPath, string streamName) { return false; } bool IInternalConfigHost.PrefetchSection(string sectionGroupName, string sectionName) { return false; } object IInternalConfigHost.CreateDeprecatedConfigContext(string configPath) { throw ExceptionUtil.UnexpectedError("IInternalConfigHost.CreateDeprecatedConfigContext"); } object IInternalConfigHost.CreateConfigurationContext(string configPath, string locationSubPath) { throw ExceptionUtil.UnexpectedError("IInternalConfigHost.CreateConfigurationContext"); } string IInternalConfigHost.DecryptSection(string encryptedXml, ProtectedConfigurationProvider protectionProvider, ProtectedConfigurationSection protectedConfigSection) { return ProtectedConfigurationSection.DecryptSection(encryptedXml, protectionProvider); } string IInternalConfigHost.EncryptSection(string clearTextXml, ProtectedConfigurationProvider protectionProvider, ProtectedConfigurationSection protectedConfigSection) { return ProtectedConfigurationSection.EncryptSection(clearTextXml, protectionProvider); } Type IInternalConfigHost.GetConfigType(string typeName, bool throwOnError) { return Type.GetType(typeName, throwOnError); } string IInternalConfigHost.GetConfigTypeName(Type t) { return t.AssemblyQualifiedName; } bool IInternalConfigHost.IsRemote => false; internal static string StaticGetStreamNameForConfigSource(string streamName, string configSource) { // RemoteWebConfigurationHost also redirects GetStreamNameForConfigSource to this // method, and that means streamName is referring to a path that's on the remote // machine. // don't allow relative paths for stream name if (!Path.IsPathRooted(streamName)) throw ExceptionUtil.ParameterInvalid(nameof(streamName)); // get the path part of the original stream streamName = Path.GetFullPath(streamName); string dirStream = UrlPath.GetDirectoryOrRootName(streamName); // combine with the new config source string result = Path.Combine(dirStream, configSource); result = Path.GetFullPath(result); // ensure the result is in or under the directory of the original source string dirResult = UrlPath.GetDirectoryOrRootName(result); if (!UrlPath.IsEqualOrSubdirectory(dirStream, dirResult)) throw new ArgumentException(SR.Format(SR.Config_source_not_under_config_dir, configSource)); return result; } internal static FileVersion StaticGetStreamVersion(string streamName) { FileInfo info = new FileInfo(streamName); return info.Exists ? new FileVersion(true, info.Length, info.CreationTimeUtc, info.LastWriteTimeUtc) : new FileVersion(false, 0, DateTime.MinValue, DateTime.MinValue); } // default impl treats name as a file name // null means stream doesn't exist for this name internal static Stream StaticOpenStreamForRead(string streamName) { if (string.IsNullOrEmpty(streamName)) throw ExceptionUtil.UnexpectedError("InternalConfigHost::StaticOpenStreamForRead"); return !File.Exists(streamName) ? null : new FileStream(streamName, FileMode.Open, FileAccess.Read, FileShare.Read); } // This method doesn't really open the streamName for write. Instead, using WriteFileContext // it opens a stream on a temporary file created in the same directory as streamName. internal static Stream StaticOpenStreamForWrite(string streamName, string templateStreamName, ref object writeContext) { if (string.IsNullOrEmpty(streamName)) throw new ConfigurationErrorsException(SR.Config_no_stream_to_write); // Create directory if it does not exist. // Ignore errors, allow any failure to come when trying to open the file. string dir = Path.GetDirectoryName(streamName); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); Stream stream; WriteFileContext writeFileContext = null; try { writeFileContext = new WriteFileContext(streamName, templateStreamName); if (File.Exists(streamName)) { FileInfo fi = new FileInfo(streamName); FileAttributes attrs = fi.Attributes; if ((attrs & InvalidAttributesForWrite) != 0) { throw new IOException(SR.Format(SR.Config_invalid_attributes_for_write, streamName)); } } try { stream = new FileStream(writeFileContext.TempNewFilename, FileMode.Create, FileAccess.Write, FileShare.Read); } catch (Exception e) { // Wrap all exceptions so that we provide a meaningful filename - otherwise the end user // will just see the temporary file name, which is meaningless. throw new ConfigurationErrorsException(SR.Format(SR.Config_write_failed, streamName), e); } } catch { writeFileContext?.Complete(streamName, false); throw; } writeContext = writeFileContext; return stream; } internal static void StaticWriteCompleted(string streamName, bool success, object writeContext) { ((WriteFileContext)writeContext).Complete(streamName, success); } internal static void StaticDeleteStream(string streamName) { File.Delete(streamName); } internal static bool StaticIsFile(string streamName) { return Path.IsPathRooted(streamName); } public bool IsTrustedConfigPath(string configPath) => true; public bool IsFullTrustSectionWithoutAptcaAllowed(IInternalConfigRecord configRecord) => true; public IDisposable Impersonate() => new DummyDisposable(); public void GetRestrictedPermissions(IInternalConfigRecord configRecord, out PermissionSet permissionSet, out bool isHostReady) { permissionSet = new PermissionSet(null); isHostReady = true; } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// ApplicationResource /// </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; namespace Twilio.Rest.Api.V2010.Account { public class ApplicationResource : Resource { private static Request BuildCreateRequest(CreateApplicationOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Applications.json", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Create a new application within your account /// </summary> /// <param name="options"> Create Application parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Application </returns> public static ApplicationResource Create(CreateApplicationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Create a new application within your account /// </summary> /// <param name="options"> Create Application parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Application </returns> public static async System.Threading.Tasks.Task<ApplicationResource> CreateAsync(CreateApplicationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Create a new application within your account /// </summary> /// <param name="pathAccountSid"> The SID of the Account that will create the resource </param> /// <param name="apiVersion"> The API version to use to start a new TwiML session </param> /// <param name="voiceUrl"> The URL to call when the phone number receives a call </param> /// <param name="voiceMethod"> The HTTP method to use with the voice_url </param> /// <param name="voiceFallbackUrl"> The URL to call when a TwiML error occurs </param> /// <param name="voiceFallbackMethod"> The HTTP method to use with voice_fallback_url </param> /// <param name="statusCallback"> The URL to send status information to your application </param> /// <param name="statusCallbackMethod"> The HTTP method to use to call status_callback </param> /// <param name="voiceCallerIdLookup"> Whether to lookup the caller's name </param> /// <param name="smsUrl"> The URL to call when the phone number receives an incoming SMS message </param> /// <param name="smsMethod"> The HTTP method to use with sms_url </param> /// <param name="smsFallbackUrl"> The URL to call when an error occurs while retrieving or executing the TwiML </param> /// <param name="smsFallbackMethod"> The HTTP method to use with sms_fallback_url </param> /// <param name="smsStatusCallback"> The URL to send status information to your application </param> /// <param name="messageStatusCallback"> The URL to send message status information to your application </param> /// <param name="friendlyName"> A string to describe the new resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Application </returns> public static ApplicationResource Create(string pathAccountSid = null, string apiVersion = null, Uri voiceUrl = null, Twilio.Http.HttpMethod voiceMethod = null, Uri voiceFallbackUrl = null, Twilio.Http.HttpMethod voiceFallbackMethod = null, Uri statusCallback = null, Twilio.Http.HttpMethod statusCallbackMethod = null, bool? voiceCallerIdLookup = null, Uri smsUrl = null, Twilio.Http.HttpMethod smsMethod = null, Uri smsFallbackUrl = null, Twilio.Http.HttpMethod smsFallbackMethod = null, Uri smsStatusCallback = null, Uri messageStatusCallback = null, string friendlyName = null, ITwilioRestClient client = null) { var options = new CreateApplicationOptions(){PathAccountSid = pathAccountSid, ApiVersion = apiVersion, VoiceUrl = voiceUrl, VoiceMethod = voiceMethod, VoiceFallbackUrl = voiceFallbackUrl, VoiceFallbackMethod = voiceFallbackMethod, StatusCallback = statusCallback, StatusCallbackMethod = statusCallbackMethod, VoiceCallerIdLookup = voiceCallerIdLookup, SmsUrl = smsUrl, SmsMethod = smsMethod, SmsFallbackUrl = smsFallbackUrl, SmsFallbackMethod = smsFallbackMethod, SmsStatusCallback = smsStatusCallback, MessageStatusCallback = messageStatusCallback, FriendlyName = friendlyName}; return Create(options, client); } #if !NET35 /// <summary> /// Create a new application within your account /// </summary> /// <param name="pathAccountSid"> The SID of the Account that will create the resource </param> /// <param name="apiVersion"> The API version to use to start a new TwiML session </param> /// <param name="voiceUrl"> The URL to call when the phone number receives a call </param> /// <param name="voiceMethod"> The HTTP method to use with the voice_url </param> /// <param name="voiceFallbackUrl"> The URL to call when a TwiML error occurs </param> /// <param name="voiceFallbackMethod"> The HTTP method to use with voice_fallback_url </param> /// <param name="statusCallback"> The URL to send status information to your application </param> /// <param name="statusCallbackMethod"> The HTTP method to use to call status_callback </param> /// <param name="voiceCallerIdLookup"> Whether to lookup the caller's name </param> /// <param name="smsUrl"> The URL to call when the phone number receives an incoming SMS message </param> /// <param name="smsMethod"> The HTTP method to use with sms_url </param> /// <param name="smsFallbackUrl"> The URL to call when an error occurs while retrieving or executing the TwiML </param> /// <param name="smsFallbackMethod"> The HTTP method to use with sms_fallback_url </param> /// <param name="smsStatusCallback"> The URL to send status information to your application </param> /// <param name="messageStatusCallback"> The URL to send message status information to your application </param> /// <param name="friendlyName"> A string to describe the new resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Application </returns> public static async System.Threading.Tasks.Task<ApplicationResource> CreateAsync(string pathAccountSid = null, string apiVersion = null, Uri voiceUrl = null, Twilio.Http.HttpMethod voiceMethod = null, Uri voiceFallbackUrl = null, Twilio.Http.HttpMethod voiceFallbackMethod = null, Uri statusCallback = null, Twilio.Http.HttpMethod statusCallbackMethod = null, bool? voiceCallerIdLookup = null, Uri smsUrl = null, Twilio.Http.HttpMethod smsMethod = null, Uri smsFallbackUrl = null, Twilio.Http.HttpMethod smsFallbackMethod = null, Uri smsStatusCallback = null, Uri messageStatusCallback = null, string friendlyName = null, ITwilioRestClient client = null) { var options = new CreateApplicationOptions(){PathAccountSid = pathAccountSid, ApiVersion = apiVersion, VoiceUrl = voiceUrl, VoiceMethod = voiceMethod, VoiceFallbackUrl = voiceFallbackUrl, VoiceFallbackMethod = voiceFallbackMethod, StatusCallback = statusCallback, StatusCallbackMethod = statusCallbackMethod, VoiceCallerIdLookup = voiceCallerIdLookup, SmsUrl = smsUrl, SmsMethod = smsMethod, SmsFallbackUrl = smsFallbackUrl, SmsFallbackMethod = smsFallbackMethod, SmsStatusCallback = smsStatusCallback, MessageStatusCallback = messageStatusCallback, FriendlyName = friendlyName}; return await CreateAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteApplicationOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Applications/" + options.PathSid + ".json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Delete the application by the specified application sid /// </summary> /// <param name="options"> Delete Application parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Application </returns> public static bool Delete(DeleteApplicationOptions 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 the application by the specified application sid /// </summary> /// <param name="options"> Delete Application parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Application </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteApplicationOptions 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 the application by the specified application sid /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resources to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Application </returns> public static bool Delete(string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new DeleteApplicationOptions(pathSid){PathAccountSid = pathAccountSid}; return Delete(options, client); } #if !NET35 /// <summary> /// Delete the application by the specified application sid /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resources to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Application </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new DeleteApplicationOptions(pathSid){PathAccountSid = pathAccountSid}; return await DeleteAsync(options, client); } #endif private static Request BuildFetchRequest(FetchApplicationOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Applications/" + options.PathSid + ".json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Fetch the application specified by the provided sid /// </summary> /// <param name="options"> Fetch Application parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Application </returns> public static ApplicationResource Fetch(FetchApplicationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Fetch the application specified by the provided sid /// </summary> /// <param name="options"> Fetch Application parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Application </returns> public static async System.Threading.Tasks.Task<ApplicationResource> FetchAsync(FetchApplicationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Fetch the application specified by the provided sid /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Application </returns> public static ApplicationResource Fetch(string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new FetchApplicationOptions(pathSid){PathAccountSid = pathAccountSid}; return Fetch(options, client); } #if !NET35 /// <summary> /// Fetch the application specified by the provided sid /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Application </returns> public static async System.Threading.Tasks.Task<ApplicationResource> FetchAsync(string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new FetchApplicationOptions(pathSid){PathAccountSid = pathAccountSid}; return await FetchAsync(options, client); } #endif private static Request BuildReadRequest(ReadApplicationOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Applications.json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of applications representing an application within the requesting account /// </summary> /// <param name="options"> Read Application parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Application </returns> public static ResourceSet<ApplicationResource> Read(ReadApplicationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<ApplicationResource>.FromJson("applications", response.Content); return new ResourceSet<ApplicationResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of applications representing an application within the requesting account /// </summary> /// <param name="options"> Read Application parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Application </returns> public static async System.Threading.Tasks.Task<ResourceSet<ApplicationResource>> ReadAsync(ReadApplicationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<ApplicationResource>.FromJson("applications", response.Content); return new ResourceSet<ApplicationResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of applications representing an application within the requesting account /// </summary> /// <param name="pathAccountSid"> The SID of the Account that created the resources to read </param> /// <param name="friendlyName"> The string that identifies the Application resources to read </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 Application </returns> public static ResourceSet<ApplicationResource> Read(string pathAccountSid = null, string friendlyName = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadApplicationOptions(){PathAccountSid = pathAccountSid, FriendlyName = friendlyName, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of applications representing an application within the requesting account /// </summary> /// <param name="pathAccountSid"> The SID of the Account that created the resources to read </param> /// <param name="friendlyName"> The string that identifies the Application resources to read </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 Application </returns> public static async System.Threading.Tasks.Task<ResourceSet<ApplicationResource>> ReadAsync(string pathAccountSid = null, string friendlyName = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadApplicationOptions(){PathAccountSid = pathAccountSid, FriendlyName = friendlyName, 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<ApplicationResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<ApplicationResource>.FromJson("applications", 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<ApplicationResource> NextPage(Page<ApplicationResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Api) ); var response = client.Request(request); return Page<ApplicationResource>.FromJson("applications", 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<ApplicationResource> PreviousPage(Page<ApplicationResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Api) ); var response = client.Request(request); return Page<ApplicationResource>.FromJson("applications", response.Content); } private static Request BuildUpdateRequest(UpdateApplicationOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Applications/" + options.PathSid + ".json", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Updates the application's properties /// </summary> /// <param name="options"> Update Application parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Application </returns> public static ApplicationResource Update(UpdateApplicationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Updates the application's properties /// </summary> /// <param name="options"> Update Application parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Application </returns> public static async System.Threading.Tasks.Task<ApplicationResource> UpdateAsync(UpdateApplicationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Updates the application's properties /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that will create the resource </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="apiVersion"> The API version to use to start a new TwiML session </param> /// <param name="voiceUrl"> The URL to call when the phone number receives a call </param> /// <param name="voiceMethod"> The HTTP method to use with the voice_url </param> /// <param name="voiceFallbackUrl"> The URL to call when a TwiML error occurs </param> /// <param name="voiceFallbackMethod"> The HTTP method to use with voice_fallback_url </param> /// <param name="statusCallback"> The URL to send status information to your application </param> /// <param name="statusCallbackMethod"> The HTTP method to use to call status_callback </param> /// <param name="voiceCallerIdLookup"> Whether to lookup the caller's name </param> /// <param name="smsUrl"> The URL to call when the phone number receives an incoming SMS message </param> /// <param name="smsMethod"> The HTTP method to use with sms_url </param> /// <param name="smsFallbackUrl"> The URL to call when an error occurs while retrieving or executing the TwiML </param> /// <param name="smsFallbackMethod"> The HTTP method to use with sms_fallback_url </param> /// <param name="smsStatusCallback"> Same as message_status_callback. Deprecated, included for backwards compatibility. /// </param> /// <param name="messageStatusCallback"> The URL to send message status information to your application </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Application </returns> public static ApplicationResource Update(string pathSid, string pathAccountSid = null, string friendlyName = null, string apiVersion = null, Uri voiceUrl = null, Twilio.Http.HttpMethod voiceMethod = null, Uri voiceFallbackUrl = null, Twilio.Http.HttpMethod voiceFallbackMethod = null, Uri statusCallback = null, Twilio.Http.HttpMethod statusCallbackMethod = null, bool? voiceCallerIdLookup = null, Uri smsUrl = null, Twilio.Http.HttpMethod smsMethod = null, Uri smsFallbackUrl = null, Twilio.Http.HttpMethod smsFallbackMethod = null, Uri smsStatusCallback = null, Uri messageStatusCallback = null, ITwilioRestClient client = null) { var options = new UpdateApplicationOptions(pathSid){PathAccountSid = pathAccountSid, FriendlyName = friendlyName, ApiVersion = apiVersion, VoiceUrl = voiceUrl, VoiceMethod = voiceMethod, VoiceFallbackUrl = voiceFallbackUrl, VoiceFallbackMethod = voiceFallbackMethod, StatusCallback = statusCallback, StatusCallbackMethod = statusCallbackMethod, VoiceCallerIdLookup = voiceCallerIdLookup, SmsUrl = smsUrl, SmsMethod = smsMethod, SmsFallbackUrl = smsFallbackUrl, SmsFallbackMethod = smsFallbackMethod, SmsStatusCallback = smsStatusCallback, MessageStatusCallback = messageStatusCallback}; return Update(options, client); } #if !NET35 /// <summary> /// Updates the application's properties /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that will create the resource </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="apiVersion"> The API version to use to start a new TwiML session </param> /// <param name="voiceUrl"> The URL to call when the phone number receives a call </param> /// <param name="voiceMethod"> The HTTP method to use with the voice_url </param> /// <param name="voiceFallbackUrl"> The URL to call when a TwiML error occurs </param> /// <param name="voiceFallbackMethod"> The HTTP method to use with voice_fallback_url </param> /// <param name="statusCallback"> The URL to send status information to your application </param> /// <param name="statusCallbackMethod"> The HTTP method to use to call status_callback </param> /// <param name="voiceCallerIdLookup"> Whether to lookup the caller's name </param> /// <param name="smsUrl"> The URL to call when the phone number receives an incoming SMS message </param> /// <param name="smsMethod"> The HTTP method to use with sms_url </param> /// <param name="smsFallbackUrl"> The URL to call when an error occurs while retrieving or executing the TwiML </param> /// <param name="smsFallbackMethod"> The HTTP method to use with sms_fallback_url </param> /// <param name="smsStatusCallback"> Same as message_status_callback. Deprecated, included for backwards compatibility. /// </param> /// <param name="messageStatusCallback"> The URL to send message status information to your application </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Application </returns> public static async System.Threading.Tasks.Task<ApplicationResource> UpdateAsync(string pathSid, string pathAccountSid = null, string friendlyName = null, string apiVersion = null, Uri voiceUrl = null, Twilio.Http.HttpMethod voiceMethod = null, Uri voiceFallbackUrl = null, Twilio.Http.HttpMethod voiceFallbackMethod = null, Uri statusCallback = null, Twilio.Http.HttpMethod statusCallbackMethod = null, bool? voiceCallerIdLookup = null, Uri smsUrl = null, Twilio.Http.HttpMethod smsMethod = null, Uri smsFallbackUrl = null, Twilio.Http.HttpMethod smsFallbackMethod = null, Uri smsStatusCallback = null, Uri messageStatusCallback = null, ITwilioRestClient client = null) { var options = new UpdateApplicationOptions(pathSid){PathAccountSid = pathAccountSid, FriendlyName = friendlyName, ApiVersion = apiVersion, VoiceUrl = voiceUrl, VoiceMethod = voiceMethod, VoiceFallbackUrl = voiceFallbackUrl, VoiceFallbackMethod = voiceFallbackMethod, StatusCallback = statusCallback, StatusCallbackMethod = statusCallbackMethod, VoiceCallerIdLookup = voiceCallerIdLookup, SmsUrl = smsUrl, SmsMethod = smsMethod, SmsFallbackUrl = smsFallbackUrl, SmsFallbackMethod = smsFallbackMethod, SmsStatusCallback = smsStatusCallback, MessageStatusCallback = messageStatusCallback}; return await UpdateAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a ApplicationResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> ApplicationResource object represented by the provided JSON </returns> public static ApplicationResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<ApplicationResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The API version used to start a new TwiML session /// </summary> [JsonProperty("api_version")] public string ApiVersion { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT that the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT that the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { 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 URL to send message status information to your application /// </summary> [JsonProperty("message_status_callback")] public Uri MessageStatusCallback { get; private set; } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The HTTP method used with sms_fallback_url /// </summary> [JsonProperty("sms_fallback_method")] [JsonConverter(typeof(HttpMethodConverter))] public Twilio.Http.HttpMethod SmsFallbackMethod { get; private set; } /// <summary> /// The URL that we call when an error occurs while retrieving or executing the TwiML /// </summary> [JsonProperty("sms_fallback_url")] public Uri SmsFallbackUrl { get; private set; } /// <summary> /// The HTTP method to use with sms_url /// </summary> [JsonProperty("sms_method")] [JsonConverter(typeof(HttpMethodConverter))] public Twilio.Http.HttpMethod SmsMethod { get; private set; } /// <summary> /// The URL to send status information to your application /// </summary> [JsonProperty("sms_status_callback")] public Uri SmsStatusCallback { get; private set; } /// <summary> /// The URL we call when the phone number receives an incoming SMS message /// </summary> [JsonProperty("sms_url")] public Uri SmsUrl { get; private set; } /// <summary> /// The URL to send status information to your application /// </summary> [JsonProperty("status_callback")] public Uri StatusCallback { get; private set; } /// <summary> /// The HTTP method we use to call status_callback /// </summary> [JsonProperty("status_callback_method")] [JsonConverter(typeof(HttpMethodConverter))] public Twilio.Http.HttpMethod StatusCallbackMethod { get; private set; } /// <summary> /// The URI of the resource, relative to `https://api.twilio.com` /// </summary> [JsonProperty("uri")] public string Uri { get; private set; } /// <summary> /// Whether to lookup the caller's name /// </summary> [JsonProperty("voice_caller_id_lookup")] public bool? VoiceCallerIdLookup { get; private set; } /// <summary> /// The HTTP method used with voice_fallback_url /// </summary> [JsonProperty("voice_fallback_method")] [JsonConverter(typeof(HttpMethodConverter))] public Twilio.Http.HttpMethod VoiceFallbackMethod { get; private set; } /// <summary> /// The URL we call when a TwiML error occurs /// </summary> [JsonProperty("voice_fallback_url")] public Uri VoiceFallbackUrl { get; private set; } /// <summary> /// The HTTP method used with the voice_url /// </summary> [JsonProperty("voice_method")] [JsonConverter(typeof(HttpMethodConverter))] public Twilio.Http.HttpMethod VoiceMethod { get; private set; } /// <summary> /// The URL we call when the phone number receives a call /// </summary> [JsonProperty("voice_url")] public Uri VoiceUrl { get; private set; } private ApplicationResource() { } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using L10NSharp; namespace Bloom.Wizard.WinForms { class WizardControl : Control { public event EventHandler Cancelled; public event EventHandler Finished; public event EventHandler SelectedPageChanged; #region protected member vars Panel _contentPanel; Panel _buttonPanel; Button _nextAndFinishedButton; Button _backButton; Button _cancelButton; int _currentPageIndex; WizardPage _currentShownPage; private readonly Stack<int> _history = new Stack<int>(); #endregion public WizardControl() { Dock = DockStyle.Fill; Pages = new List<WizardPage>(); } public WizardPage SelectedPage { get { if (Pages.Count <= 0) return null; return _currentShownPage; } } public List<WizardPage> Pages { get; protected set; } public string Title { get; set; } public string NextButtonText { get; set; } public string FinishButtonText { get; set; } public string CancelButtonText { get { return _cancelButton.Text; } set { _cancelButton.Text = value; } } public Icon TitleIcon { get; set; } public void BeginInit() { _backButton = new Button { Text = "Back", Size = new Size(75, 25), Left = 0 }; _backButton.Text = LocalizationManager.GetString("Common.BackButton", "Back", "In a wizard, this button takes you to the previous step."); _nextAndFinishedButton = new Button { Text = "Next", Size = new Size(75, 25), Left = 80}; _nextAndFinishedButton.Text = LocalizationManager.GetString("Common.NextButton", "Next", "In a wizard, this button takes you to the next step."); _cancelButton = new Button { Text = "Cancel", Size = new Size(75, 25), Left = 160 }; _cancelButton.Text = LocalizationManager.GetString("Common.CancelButton", "Cancel"); _contentPanel = new Panel { Dock = DockStyle.Fill }; _buttonPanel = new Panel { Dock = DockStyle.Bottom, Height = 35, Padding = new Padding(5) }; var panel = new Panel { Dock = DockStyle.Right, AutoSize = true }; panel.Controls.Add(_backButton); panel.Controls.Add(_nextAndFinishedButton); panel.Controls.Add(_cancelButton); _buttonPanel.Controls.Add(panel); } public void EndInit() { _nextAndFinishedButton.Click += nextAndFinishedButton_Click; _backButton.Click += _backButton_Click; _cancelButton.Click += _cancelButton_Click; Controls.Add(_contentPanel); Controls.Add(_buttonPanel); } public void ShowFirstPage() { ShowPage(0); } void _cancelButton_Click(object sender, EventArgs e) { if (Cancelled != null) Cancelled(this, EventArgs.Empty); } void _backButton_Click(object sender, EventArgs e) { if (_history.Count < 2) return; _history.Pop(); ShowPage(_history.Pop()); InvokePagedChangedEvent(); } void nextAndFinishedButton_Click(object sender, EventArgs e) { if (_currentShownPage.IsFinishPage) { if (Finished != null) Finished(this, EventArgs.Empty); return; } ShowPage(GetNextPage()); InvokePagedChangedEvent(); } protected void InvokePagedChangedEvent() { UpdateNextAndFinishedButtonText(); if (SelectedPageChanged != null) SelectedPageChanged(this, EventArgs.Empty); } public void UpdateNextAndFinishedButtonText() { if (_nextAndFinishedButton != null && _currentShownPage != null) _nextAndFinishedButton.Text = _currentShownPage.IsFinishPage ? FinishButtonText : NextButtonText; } protected virtual void ShowPage(int pageNumber) { ShowPage(Pages[pageNumber], pageNumber); } protected virtual void ShowPage(WizardPage page) { ShowPage(page, Pages.IndexOf(page)); } private void ShowPage(WizardPage page, int pageNumber) { if (page.Suppress) { ShowPage(GetNextPage()); return; } if (_currentShownPage != null) _contentPanel.Controls.Remove(_currentShownPage); _currentPageIndex = pageNumber; _currentShownPage = page; _currentShownPage.InvokeInitializeEvent(); _currentShownPage.Dock = DockStyle.Fill; _currentShownPage.BeforeShow(); _contentPanel.Controls.Add(_currentShownPage); _backButton.Enabled = _history.Count > 0; _nextAndFinishedButton.Enabled = _currentShownPage.AllowNext; _currentShownPage.AllowNextChanged -= _currentShownPage_AllowNextChanged; _currentShownPage.AllowNextChanged += _currentShownPage_AllowNextChanged; _history.Push(pageNumber); } private WizardPage GetNextPage() { if (_currentShownPage != null && _currentShownPage.NextPage != null) return _currentShownPage.NextPage; return Pages[++_currentPageIndex]; } void _currentShownPage_AllowNextChanged(object sender, EventArgs e) { _nextAndFinishedButton.Enabled = _currentShownPage.AllowNext; } protected override void OnParentChanged(EventArgs e) { base.OnParentChanged(e); var form = FindForm(); if (form == null) return; form.Text = Title; form.Icon = TitleIcon; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Hatfield.AnalyteManagement.Web.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.Net.Sockets { // Provides the underlying stream of data for network access. public class NetworkStream : Stream { // Used by the class to hold the underlying socket the stream uses. private Socket _streamSocket; // Used by the class to indicate that the stream is m_Readable. private bool _readable; // Used by the class to indicate that the stream is writable. private bool _writeable; private bool _ownsSocket; // Creates a new instance of the System.Net.Sockets.NetworkStream without initalization. internal NetworkStream() { _ownsSocket = true; } // Creates a new instance of the System.Net.Sockets.NetworkStream class for the specified System.Net.Sockets.Socket. public NetworkStream(Socket socket) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User)) { #endif if (socket == null) { throw new ArgumentNullException("socket"); } InitNetworkStream(socket); #if DEBUG } #endif } public NetworkStream(Socket socket, bool ownsSocket) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User)) { #endif if (socket == null) { throw new ArgumentNullException("socket"); } InitNetworkStream(socket); _ownsSocket = ownsSocket; #if DEBUG } #endif } internal NetworkStream(NetworkStream networkStream, bool ownsSocket) { Socket socket = networkStream.Socket; if (socket == null) { throw new ArgumentNullException("networkStream"); } InitNetworkStream(socket); _ownsSocket = ownsSocket; } // Socket - provides access to socket for stream closing protected Socket Socket { get { return _streamSocket; } } internal Socket InternalSocket { get { Socket chkSocket = _streamSocket; if (_cleanedUp || chkSocket == null) { throw new ObjectDisposedException(this.GetType().FullName); } return chkSocket; } } internal void InternalAbortSocket() { if (!_ownsSocket) { throw new InvalidOperationException(); } Socket chkSocket = _streamSocket; if (_cleanedUp || chkSocket == null) { return; } try { chkSocket.Dispose(); } catch (ObjectDisposedException) { } } internal void ConvertToNotSocketOwner() { _ownsSocket = false; // Suppress for finialization still allow proceed the requests GC.SuppressFinalize(this); } // Used by the class to indicate that the stream is m_Readable. protected bool Readable { get { return _readable; } set { _readable = value; } } // Used by the class to indicate that the stream is writable. protected bool Writeable { get { return _writeable; } set { _writeable = value; } } // Indicates that data can be read from the stream. // We return the readability of this stream. This is a read only property. public override bool CanRead { get { return _readable; } } // Indicates that the stream can seek a specific location // in the stream. This property always returns false. public override bool CanSeek { get { return false; } } // Indicates that data can be written to the stream. public override bool CanWrite { get { return _writeable; } } // Indicates whether we can timeout public override bool CanTimeout { get { return true; // should we check for Connected state? } } // Set/Get ReadTimeout, note of a strange behavior, 0 timeout == infinite for sockets, // so we map this to -1, and if you set 0, we cannot support it public override int ReadTimeout { get { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout); if (timeout == 0) { return -1; } return timeout; #if DEBUG } #endif } set { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif if (value <= 0 && value != System.Threading.Timeout.Infinite) { throw new ArgumentOutOfRangeException("value", SR.net_io_timeout_use_gt_zero); } SetSocketTimeoutOption(SocketShutdown.Receive, value, false); #if DEBUG } #endif } } // Set/Get WriteTimeout, note of a strange behavior, 0 timeout == infinite for sockets, // so we map this to -1, and if you set 0, we cannot support it public override int WriteTimeout { get { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout); if (timeout == 0) { return -1; } return timeout; #if DEBUG } #endif } set { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif if (value <= 0 && value != System.Threading.Timeout.Infinite) { throw new ArgumentOutOfRangeException("value", SR.net_io_timeout_use_gt_zero); } SetSocketTimeoutOption(SocketShutdown.Send, value, false); #if DEBUG } #endif } } // Indicates data is available on the stream to be read. // This property checks to see if at least one byte of data is currently available public virtual bool DataAvailable { get { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } // Ask the socket how many bytes are available. If it's // not zero, return true. return chkStreamSocket.Available != 0; #if DEBUG } #endif } } // The length of data available on the stream. Always throws NotSupportedException. public override long Length { get { throw new NotSupportedException(SR.net_noseek); } } // Gets or sets the position in the stream. Always throws NotSupportedException. public override long Position { get { throw new NotSupportedException(SR.net_noseek); } set { throw new NotSupportedException(SR.net_noseek); } } // Seeks a specific position in the stream. This method is not supported by the // NetworkStream class. public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(SR.net_noseek); } internal void InitNetworkStream(Socket socket) { if (!socket.Blocking) { throw new IOException(SR.net_sockets_blocking); } if (!socket.Connected) { throw new IOException(SR.net_notconnected); } if (socket.SocketType != SocketType.Stream) { throw new IOException(SR.net_notstream); } _streamSocket = socket; _readable = true; _writeable = true; } internal bool PollRead() { if (_cleanedUp) { return false; } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { return false; } return chkStreamSocket.Poll(0, SelectMode.SelectRead); } internal bool Poll(int microSeconds, SelectMode mode) { if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } return chkStreamSocket.Poll(microSeconds, mode); } // Read - provide core Read functionality. // // Provide core read functionality. All we do is call through to the // socket Receive functionality. // // Input: // // Buffer - Buffer to read into. // Offset - Offset into the buffer where we're to read. // Count - Number of bytes to read. // // Returns: // // Number of bytes we read, or 0 if the socket is closed. public override int Read([In, Out] byte[] buffer, int offset, int size) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) { #endif bool canRead = CanRead; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canRead) { throw new InvalidOperationException(SR.net_writeonlystream); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException("size"); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } try { int bytesTransferred = chkStreamSocket.Receive(buffer, offset, size, 0); return bytesTransferred; } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception); } #if DEBUG } #endif } // Write - provide core Write functionality. // // Provide core write functionality. All we do is call through to the // socket Send method.. // // Input: // // Buffer - Buffer to write from. // Offset - Offset into the buffer from where we'll start writing. // Count - Number of bytes to write. // // Returns: // // Number of bytes written. We'll throw an exception if we // can't write everything. It's brutal, but there's no other // way to indicate an error. public override void Write(byte[] buffer, int offset, int size) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) { #endif bool canWrite = CanWrite; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canWrite) { throw new InvalidOperationException(SR.net_readonlystream); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException("size"); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_writefailure, SR.net_io_connectionclosed)); } try { // Since the socket is in blocking mode this will always complete // after ALL the requested number of bytes was transferred. chkStreamSocket.Send(buffer, offset, size, SocketFlags.None); } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception); } #if DEBUG } #endif } private volatile bool _cleanedUp = false; protected override void Dispose(bool disposing) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User)) { #endif // Mark this as disposed before changing anything else. bool cleanedUp = _cleanedUp; _cleanedUp = true; if (!cleanedUp && disposing) { // The only resource we need to free is the network stream, since this // is based on the client socket, closing the stream will cause us // to flush the data to the network, close the stream and (in the // NetoworkStream code) close the socket as well. if (_streamSocket != null) { _readable = false; _writeable = false; if (_ownsSocket) { // If we own the Socket (false by default), close it // ignoring possible exceptions (eg: the user told us // that we own the Socket but it closed at some point of time, // here we would get an ObjectDisposedException) Socket chkStreamSocket = _streamSocket; if (chkStreamSocket != null) { chkStreamSocket.InternalShutdown(SocketShutdown.Both); chkStreamSocket.Dispose(); } } } } #if DEBUG } #endif base.Dispose(disposing); } ~NetworkStream() { #if DEBUG GlobalLog.SetThreadSource(ThreadKinds.Finalization); #endif Dispose(false); } // Indicates whether the stream is still connected internal bool Connected { get { Socket socket = _streamSocket; if (!_cleanedUp && socket != null && socket.Connected) { return true; } else { return false; } } } // BeginRead - provide async read functionality. // // This method provides async read functionality. All we do is // call through to the underlying socket async read. // // Input: // // buffer - Buffer to read into. // offset - Offset into the buffer where we're to read. // size - Number of bytes to read. // // Returns: // // An IASyncResult, representing the read. public IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif bool canRead = CanRead; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canRead) { throw new InvalidOperationException(SR.net_writeonlystream); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException("size"); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } try { IAsyncResult asyncResult = chkStreamSocket.BeginReceive( buffer, offset, size, SocketFlags.None, callback, state); return asyncResult; } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception); } #if DEBUG } #endif } internal virtual IAsyncResult UnsafeBeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { bool canRead = CanRead; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(GetType().FullName); } if (!canRead) { throw new InvalidOperationException(SR.net_writeonlystream); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } try { IAsyncResult asyncResult = chkStreamSocket.UnsafeBeginReceive( buffer, offset, size, SocketFlags.None, callback, state); return asyncResult; } catch (Exception exception) { if (ExceptionCheck.IsFatal(exception)) throw; // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception); } } // EndRead - handle the end of an async read. // // This method is called when an async read is completed. All we // do is call through to the core socket EndReceive functionality. // // Returns: // // The number of bytes read. May throw an exception. public int EndRead(IAsyncResult asyncResult) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User)) { #endif if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } // Validate input parameters. if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed)); } try { int bytesTransferred = chkStreamSocket.EndReceive(asyncResult); return bytesTransferred; } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception); } #if DEBUG } #endif } // BeginWrite - provide async write functionality. // // This method provides async write functionality. All we do is // call through to the underlying socket async send. // // Input: // // buffer - Buffer to write into. // offset - Offset into the buffer where we're to write. // size - Number of bytes to written. // // Returns: // // An IASyncResult, representing the write. public IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif bool canWrite = CanWrite; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canWrite) { throw new InvalidOperationException(SR.net_readonlystream); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException("size"); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_writefailure, SR.net_io_connectionclosed)); } try { // Call BeginSend on the Socket. IAsyncResult asyncResult = chkStreamSocket.BeginSend( buffer, offset, size, SocketFlags.None, callback, state); return asyncResult; } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception); } #if DEBUG } #endif } internal virtual IAsyncResult UnsafeBeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif bool canWrite = CanWrite; // Prevent race with Dispose. if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (!canWrite) { throw new InvalidOperationException(SR.net_readonlystream); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_writefailure, SR.net_io_connectionclosed)); } try { // Call BeginSend on the Socket. IAsyncResult asyncResult = chkStreamSocket.UnsafeBeginSend( buffer, offset, size, SocketFlags.None, callback, state); return asyncResult; } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception); } #if DEBUG } #endif } // Handle the end of an asynchronous write. // This method is called when an async write is completed. All we // do is call through to the core socket EndSend functionality. // Returns: The number of bytes read. May throw an exception. public void EndWrite(IAsyncResult asyncResult) { #if DEBUG using (GlobalLog.SetThreadKind(ThreadKinds.User)) { #endif if (_cleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } // Validate input parameters. if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { throw new IOException(SR.Format(SR.net_io_writefailure, SR.net_io_connectionclosed)); } try { chkStreamSocket.EndSend(asyncResult); } catch (Exception exception) { if (exception is OutOfMemoryException) { throw; } // Some sort of error occurred on the socket call, // set the SocketException as InnerException and throw. throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception); } #if DEBUG } #endif } // ReadAsync - provide async read functionality. // // This method provides async read functionality. All we do is // call through to the Begin/EndRead methods. // // Input: // // buffer - Buffer to read into. // offset - Offset into the buffer where we're to read. // size - Number of bytes to read. // cancellationtoken - Token used to request cancellation of the operation // // Returns: // // A Task<int> representing the read. public override Task<int> ReadAsync(byte[] buffer, int offset, int size, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<int>(cancellationToken); } return Task.Factory.FromAsync( (bufferArg, offsetArg, sizeArg, callback, state) => ((NetworkStream)state).BeginRead(bufferArg, offsetArg, sizeArg, callback, state), iar => ((NetworkStream)iar.AsyncState).EndRead(iar), buffer, offset, size, this); } // WriteAsync - provide async write functionality. // // This method provides async write functionality. All we do is // call through to the Begin/EndWrite methods. // // Input: // // buffer - Buffer to write into. // offset - Offset into the buffer where we're to write. // size - Number of bytes to write. // cancellationtoken - Token used to request cancellation of the operation // // Returns: // // A Task representing the write. public override Task WriteAsync(byte[] buffer, int offset, int size, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<int>(cancellationToken); } return Task.Factory.FromAsync( (bufferArg, offsetArg, sizeArg, callback, state) => ((NetworkStream)state).BeginWrite(bufferArg, offsetArg, sizeArg, callback, state), iar => ((NetworkStream)iar.AsyncState).EndWrite(iar), buffer, offset, size, this); } // Flushes data from the stream. This is meaningless for us, so it does nothing. public override void Flush() { } public override Task FlushAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } // Sets the length of the stream. Always throws NotSupportedException public override void SetLength(long value) { throw new NotSupportedException(SR.net_noseek); } private int _currentReadTimeout = -1; private int _currentWriteTimeout = -1; internal void SetSocketTimeoutOption(SocketShutdown mode, int timeout, bool silent) { GlobalLog.Print("NetworkStream#" + Logging.HashString(this) + "::SetSocketTimeoutOption() mode:" + mode + " silent:" + silent + " timeout:" + timeout + " m_CurrentReadTimeout:" + _currentReadTimeout + " m_CurrentWriteTimeout:" + _currentWriteTimeout); GlobalLog.ThreadContract(ThreadKinds.Unknown, "NetworkStream#" + Logging.HashString(this) + "::SetSocketTimeoutOption"); if (timeout < 0) { timeout = 0; // -1 becomes 0 for the winsock stack } Socket chkStreamSocket = _streamSocket; if (chkStreamSocket == null) { return; } if (mode == SocketShutdown.Send || mode == SocketShutdown.Both) { if (timeout != _currentWriteTimeout) { chkStreamSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout, silent); _currentWriteTimeout = timeout; } } if (mode == SocketShutdown.Receive || mode == SocketShutdown.Both) { if (timeout != _currentReadTimeout) { chkStreamSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout, silent); _currentReadTimeout = timeout; } } } [System.Diagnostics.Conditional("TRACE_VERBOSE")] internal void DebugMembers() { if (_streamSocket != null) { GlobalLog.Print("_streamSocket:"); _streamSocket.DebugMembers(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEditor; using UnityEngine; #if UNITY_5_3_OR_NEWER using UnityEditor.SceneManagement; #endif namespace UnityTest { [CustomEditor(typeof(AssertionComponent))] public class AssertionComponentEditor : Editor { private readonly DropDownControl<Type> m_ComparerDropDown = new DropDownControl<Type>(); private readonly PropertyPathSelector m_ThisPathSelector = new PropertyPathSelector("Compare"); private readonly PropertyPathSelector m_OtherPathSelector = new PropertyPathSelector("Compare to"); #region GUI Contents private readonly GUIContent m_GUICheckAfterTimeGuiContent = new GUIContent("Check after (seconds)", "After how many seconds the assertion should be checked"); private readonly GUIContent m_GUIRepeatCheckTimeGuiContent = new GUIContent("Repeat check", "Should the check be repeated."); private readonly GUIContent m_GUIRepeatEveryTimeGuiContent = new GUIContent("Frequency of repetitions", "How often should the check be done"); private readonly GUIContent m_GUICheckAfterFramesGuiContent = new GUIContent("Check after (frames)", "After how many frames the assertion should be checked"); private readonly GUIContent m_GUIRepeatCheckFrameGuiContent = new GUIContent("Repeat check", "Should the check be repeated."); #endregion private static List<Type> allComparersList = null; public AssertionComponentEditor() { m_ComparerDropDown.convertForButtonLabel = type => type.Name; m_ComparerDropDown.convertForGUIContent = type => type.Name; m_ComparerDropDown.ignoreConvertForGUIContent = types => false; m_ComparerDropDown.tooltip = "Comparer that will be used to compare values and determine the result of assertion."; } public override void OnInspectorGUI() { var script = (AssertionComponent)target; EditorGUILayout.BeginHorizontal(); var obj = DrawComparerSelection(script); script.checkMethods = (CheckMethod)EditorGUILayout.EnumMaskField(script.checkMethods, EditorStyles.popup, GUILayout.ExpandWidth(false)); EditorGUILayout.EndHorizontal(); if (script.IsCheckMethodSelected(CheckMethod.AfterPeriodOfTime)) { DrawOptionsForAfterPeriodOfTime(script); } if (script.IsCheckMethodSelected(CheckMethod.Update)) { DrawOptionsForOnUpdate(script); } if (obj) { EditorGUILayout.Space(); m_ThisPathSelector.Draw(script.Action.go, script.Action, script.Action.thisPropertyPath, script.Action.GetAccepatbleTypesForA(), go => { script.Action.go = go; AssertionExplorerWindow.Reload(); }, s => { script.Action.thisPropertyPath = s; AssertionExplorerWindow.Reload(); }); EditorGUILayout.Space(); DrawCustomFields(script); EditorGUILayout.Space(); if (script.Action is ComparerBase) { DrawCompareToType(script.Action as ComparerBase); } } if(GUI.changed) { #if UNITY_5_3_OR_NEWER EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); #else EditorApplication.MarkSceneDirty(); #endif } } private void DrawOptionsForAfterPeriodOfTime(AssertionComponent script) { EditorGUILayout.Space(); script.checkAfterTime = EditorGUILayout.FloatField(m_GUICheckAfterTimeGuiContent, script.checkAfterTime); if (script.checkAfterTime < 0) script.checkAfterTime = 0; script.repeatCheckTime = EditorGUILayout.Toggle(m_GUIRepeatCheckTimeGuiContent, script.repeatCheckTime); if (script.repeatCheckTime) { script.repeatEveryTime = EditorGUILayout.FloatField(m_GUIRepeatEveryTimeGuiContent, script.repeatEveryTime); if (script.repeatEveryTime < 0) script.repeatEveryTime = 0; } } private void DrawOptionsForOnUpdate(AssertionComponent script) { EditorGUILayout.Space(); script.checkAfterFrames = EditorGUILayout.IntField(m_GUICheckAfterFramesGuiContent, script.checkAfterFrames); if (script.checkAfterFrames < 1) script.checkAfterFrames = 1; script.repeatCheckFrame = EditorGUILayout.Toggle(m_GUIRepeatCheckFrameGuiContent, script.repeatCheckFrame); if (script.repeatCheckFrame) { script.repeatEveryFrame = EditorGUILayout.IntField(m_GUIRepeatEveryTimeGuiContent, script.repeatEveryFrame); if (script.repeatEveryFrame < 1) script.repeatEveryFrame = 1; } } private void DrawCompareToType(ComparerBase comparer) { comparer.compareToType = (ComparerBase.CompareToType)EditorGUILayout.EnumPopup("Compare to type", comparer.compareToType, EditorStyles.popup); if (comparer.compareToType == ComparerBase.CompareToType.CompareToConstantValue) { try { DrawConstCompareField(comparer); } catch (NotImplementedException) { Debug.LogWarning("This comparer can't compare to static value"); comparer.compareToType = ComparerBase.CompareToType.CompareToObject; } } else if (comparer.compareToType == ComparerBase.CompareToType.CompareToObject) { DrawObjectCompareField(comparer); } } private void DrawObjectCompareField(ComparerBase comparer) { m_OtherPathSelector.Draw(comparer.other, comparer, comparer.otherPropertyPath, comparer.GetAccepatbleTypesForB(), go => { comparer.other = go; AssertionExplorerWindow.Reload(); }, s => { comparer.otherPropertyPath = s; AssertionExplorerWindow.Reload(); } ); } private void DrawConstCompareField(ComparerBase comparer) { if (comparer.ConstValue == null) { comparer.ConstValue = comparer.GetDefaultConstValue(); } var so = new SerializedObject(comparer); var sp = so.FindProperty("constantValueGeneric"); if (sp != null) { EditorGUILayout.PropertyField(sp, new GUIContent("Constant"), true); so.ApplyModifiedProperties(); } } private bool DrawComparerSelection(AssertionComponent script) { if(allComparersList == null) { allComparersList = new List<Type>(); var allAssemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (var assembly in allAssemblies) { var types = assembly.GetTypes(); allComparersList.AddRange(types.Where(type => type.IsSubclassOf(typeof(ActionBase)) && !type.IsAbstract)); } } var allComparers = allComparersList.ToArray(); if (script.Action == null) script.Action = (ActionBase)CreateInstance(allComparers.First()); m_ComparerDropDown.Draw(script.Action.GetType(), allComparers, type => { if (script.Action == null || script.Action.GetType().Name != type.Name) { script.Action = (ActionBase)CreateInstance(type); AssertionExplorerWindow.Reload(); } }); return script.Action != null; } private void DrawCustomFields(AssertionComponent script) { foreach (var prop in script.Action.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { var so = new SerializedObject(script.Action); var sp = so.FindProperty(prop.Name); if (sp != null) { EditorGUILayout.PropertyField(sp, true); so.ApplyModifiedProperties(); } } } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // SpoolingTask.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Threading; using System.Threading.Tasks; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Linq.Parallel { /// <summary> /// A factory class to execute spooling logic. /// </summary> internal static class SpoolingTask { //----------------------------------------------------------------------------------- // Creates and begins execution of a new spooling task. Executes synchronously, // and by the time this API has returned all of the results have been produced. // // Arguments: // groupState - values for inter-task communication // partitions - the producer enumerators // channels - the producer-consumer channels // taskScheduler - the task manager on which to execute // internal static void SpoolStopAndGo<TInputOutput, TIgnoreKey>( QueryTaskGroupState groupState, PartitionedStream<TInputOutput, TIgnoreKey> partitions, SynchronousChannel<TInputOutput>[] channels, TaskScheduler taskScheduler) { Contract.Requires(partitions.PartitionCount == channels.Length); Contract.Requires(groupState != null); // Ensure all tasks in this query are parented under a common root. Task rootTask = new Task( () => { int maxToRunInParallel = partitions.PartitionCount - 1; // A stop-and-go merge uses the current thread for one task and then blocks before // returning to the caller, until all results have been accumulated. We do this by // running the last partition on the calling thread. for (int i = 0; i < maxToRunInParallel; i++) { TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] asynchronously", i); QueryTask asyncTask = new StopAndGoSpoolingTask<TInputOutput, TIgnoreKey>(i, groupState, partitions[i], channels[i]); asyncTask.RunAsynchronously(taskScheduler); } TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] synchronously", maxToRunInParallel); // Run one task synchronously on the current thread. QueryTask syncTask = new StopAndGoSpoolingTask<TInputOutput, TIgnoreKey>( maxToRunInParallel, groupState, partitions[maxToRunInParallel], channels[maxToRunInParallel]); syncTask.RunSynchronously(taskScheduler); }); // Begin the query on the calling thread. groupState.QueryBegin(rootTask); // We don't want to return until the task is finished. Run it on the calling thread. rootTask.RunSynchronously(taskScheduler); // Wait for the query to complete, propagate exceptions, and so on. // For pipelined queries, this step happens in the async enumerator. groupState.QueryEnd(false); } //----------------------------------------------------------------------------------- // Creates and begins execution of a new spooling task. Runs asynchronously. // // Arguments: // groupState - values for inter-task communication // partitions - the producer enumerators // channels - the producer-consumer channels // taskScheduler - the task manager on which to execute // internal static void SpoolPipeline<TInputOutput, TIgnoreKey>( QueryTaskGroupState groupState, PartitionedStream<TInputOutput, TIgnoreKey> partitions, AsynchronousChannel<TInputOutput>[] channels, TaskScheduler taskScheduler) { Contract.Requires(partitions.PartitionCount == channels.Length); Contract.Requires(groupState != null); // Ensure all tasks in this query are parented under a common root. Because this // is a pipelined query, we detach it from the parent (to avoid blocking the calling // thread), and run the query on a separate thread. Task rootTask = new Task( () => { // Create tasks that will enumerate the partitions in parallel. Because we're pipelining, // we will begin running these tasks in parallel and then return. for (int i = 0; i < partitions.PartitionCount; i++) { TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] asynchronously", i); QueryTask asyncTask = new PipelineSpoolingTask<TInputOutput, TIgnoreKey>(i, groupState, partitions[i], channels[i]); asyncTask.RunAsynchronously(taskScheduler); } }); // Begin the query on the calling thread. groupState.QueryBegin(rootTask); // And schedule it for execution. This is done after beginning to ensure no thread tries to // end the query before its root task has been recorded properly. rootTask.Start(taskScheduler); // We don't call QueryEnd here; when we return, the query is still executing, and the // last enumerator to be disposed of will call QueryEnd for us. } //----------------------------------------------------------------------------------- // Creates and begins execution of a new spooling task. This is a for-all style // execution, meaning that the query will be run fully (for effect) before returning // and that there are no channels into which data will be queued. // // Arguments: // groupState - values for inter-task communication // partitions - the producer enumerators // taskScheduler - the task manager on which to execute // internal static void SpoolForAll<TInputOutput, TIgnoreKey>( QueryTaskGroupState groupState, PartitionedStream<TInputOutput, TIgnoreKey> partitions, TaskScheduler taskScheduler) { Contract.Requires(groupState != null); // Ensure all tasks in this query are parented under a common root. Task rootTask = new Task( () => { int maxToRunInParallel = partitions.PartitionCount - 1; // Create tasks that will enumerate the partitions in parallel "for effect"; in other words, // no data will be placed into any kind of producer-consumer channel. for (int i = 0; i < maxToRunInParallel; i++) { TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] asynchronously", i); QueryTask asyncTask = new ForAllSpoolingTask<TInputOutput, TIgnoreKey>(i, groupState, partitions[i]); asyncTask.RunAsynchronously(taskScheduler); } TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] synchronously", maxToRunInParallel); // Run one task synchronously on the current thread. QueryTask syncTask = new ForAllSpoolingTask<TInputOutput, TIgnoreKey>(maxToRunInParallel, groupState, partitions[maxToRunInParallel]); syncTask.RunSynchronously(taskScheduler); }); // Begin the query on the calling thread. groupState.QueryBegin(rootTask); // We don't want to return until the task is finished. Run it on the calling thread. rootTask.RunSynchronously(taskScheduler); // Wait for the query to complete, propagate exceptions, and so on. // For pipelined queries, this step happens in the async enumerator. groupState.QueryEnd(false); } } /// <summary> /// A spooling task handles marshaling data from a producer to a consumer. It's given /// a single enumerator object that contains all of the production algorithms, a single /// destination channel from which consumers draw results, and (optionally) a /// synchronization primitive using which to notify asynchronous consumers. /// </summary> /// <typeparam name="TInputOutput"></typeparam> /// <typeparam name="TIgnoreKey"></typeparam> internal class StopAndGoSpoolingTask<TInputOutput, TIgnoreKey> : SpoolingTaskBase { // The data source from which to pull data. private QueryOperatorEnumerator<TInputOutput, TIgnoreKey> _source; // The destination channel into which data is placed. This can be null if we are // enumerating "for effect", e.g. forall loop. private SynchronousChannel<TInputOutput> _destination; //----------------------------------------------------------------------------------- // Creates, but does not execute, a new spooling task. // // Arguments: // taskIndex - the unique index of this task // source - the producer enumerator // destination - the destination channel into which to spool elements // // Assumptions: // Source cannot be null, although the other arguments may be. // internal StopAndGoSpoolingTask( int taskIndex, QueryTaskGroupState groupState, QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source, SynchronousChannel<TInputOutput> destination) : base(taskIndex, groupState) { Contract.Requires(source != null); _source = source; _destination = destination; } //----------------------------------------------------------------------------------- // This method is responsible for enumerating results and enqueueing them to // the output channel(s) as appropriate. Each base class implements its own. // protected override void SpoolingWork() { // We just enumerate over the entire source data stream, placing each element // into the destination channel. TInputOutput current = default(TInputOutput); TIgnoreKey keyUnused = default(TIgnoreKey); QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source = _source; SynchronousChannel<TInputOutput> destination = _destination; CancellationToken cancelToken = _groupState.CancellationState.MergedCancellationToken; destination.Init(); while (source.MoveNext(ref current, ref keyUnused)) { // If an abort has been requested, stop this worker immediately. if (cancelToken.IsCancellationRequested) { break; } destination.Enqueue(current); } } //----------------------------------------------------------------------------------- // Ensure we signal that the channel is complete. // protected override void SpoolingFinally() { // Call the base implementation. base.SpoolingFinally(); // Signal that we are done, in the case of asynchronous consumption. if (_destination != null) { _destination.SetDone(); } // Dispose of the source enumerator *after* signaling that the task is done. // We call Dispose() last to ensure that if it throws an exception, we will not cause a deadlock. _source.Dispose(); } } /// <summary> /// A spooling task handles marshaling data from a producer to a consumer. It's given /// a single enumerator object that contains all of the production algorithms, a single /// destination channel from which consumers draw results, and (optionally) a /// synchronization primitive using which to notify asynchronous consumers. /// </summary> /// <typeparam name="TInputOutput"></typeparam> /// <typeparam name="TIgnoreKey"></typeparam> internal class PipelineSpoolingTask<TInputOutput, TIgnoreKey> : SpoolingTaskBase { // The data source from which to pull data. private QueryOperatorEnumerator<TInputOutput, TIgnoreKey> _source; // The destination channel into which data is placed. This can be null if we are // enumerating "for effect", e.g. forall loop. private AsynchronousChannel<TInputOutput> _destination; //----------------------------------------------------------------------------------- // Creates, but does not execute, a new spooling task. // // Arguments: // taskIndex - the unique index of this task // source - the producer enumerator // destination - the destination channel into which to spool elements // // Assumptions: // Source cannot be null, although the other arguments may be. // internal PipelineSpoolingTask( int taskIndex, QueryTaskGroupState groupState, QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source, AsynchronousChannel<TInputOutput> destination) : base(taskIndex, groupState) { Debug.Assert(source != null); _source = source; _destination = destination; } //----------------------------------------------------------------------------------- // This method is responsible for enumerating results and enqueueing them to // the output channel(s) as appropriate. Each base class implements its own. // protected override void SpoolingWork() { // We just enumerate over the entire source data stream, placing each element // into the destination channel. TInputOutput current = default(TInputOutput); TIgnoreKey keyUnused = default(TIgnoreKey); QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source = _source; AsynchronousChannel<TInputOutput> destination = _destination; CancellationToken cancelToken = _groupState.CancellationState.MergedCancellationToken; while (source.MoveNext(ref current, ref keyUnused)) { // If an abort has been requested, stop this worker immediately. if (cancelToken.IsCancellationRequested) { break; } destination.Enqueue(current); } // Flush remaining data to the query consumer in preparation for channel shutdown. destination.FlushBuffers(); } //----------------------------------------------------------------------------------- // Ensure we signal that the channel is complete. // protected override void SpoolingFinally() { // Call the base implementation. base.SpoolingFinally(); // Signal that we are done, in the case of asynchronous consumption. if (_destination != null) { _destination.SetDone(); } // Dispose of the source enumerator *after* signaling that the task is done. // We call Dispose() last to ensure that if it throws an exception, we will not cause a deadlock. _source.Dispose(); } } /// <summary> /// A spooling task handles marshaling data from a producer to a consumer. It's given /// a single enumerator object that contains all of the production algorithms, a single /// destination channel from which consumers draw results, and (optionally) a /// synchronization primitive using which to notify asynchronous consumers. /// </summary> /// <typeparam name="TInputOutput"></typeparam> /// <typeparam name="TIgnoreKey"></typeparam> internal class ForAllSpoolingTask<TInputOutput, TIgnoreKey> : SpoolingTaskBase { // The data source from which to pull data. private QueryOperatorEnumerator<TInputOutput, TIgnoreKey> _source; //----------------------------------------------------------------------------------- // Creates, but does not execute, a new spooling task. // // Arguments: // taskIndex - the unique index of this task // source - the producer enumerator // destination - the destination channel into which to spool elements // // Assumptions: // Source cannot be null, although the other arguments may be. // internal ForAllSpoolingTask( int taskIndex, QueryTaskGroupState groupState, QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source) : base(taskIndex, groupState) { Debug.Assert(source != null); _source = source; } //----------------------------------------------------------------------------------- // This method is responsible for enumerating results and enqueueing them to // the output channel(s) as appropriate. Each base class implements its own. // protected override void SpoolingWork() { // We just enumerate over the entire source data stream for effect. TInputOutput currentUnused = default(TInputOutput); TIgnoreKey keyUnused = default(TIgnoreKey); //Note: this only ever runs with a ForAll operator, and ForAllEnumerator performs cancellation checks while (_source.MoveNext(ref currentUnused, ref keyUnused)) ; } //----------------------------------------------------------------------------------- // Ensure we signal that the channel is complete. // protected override void SpoolingFinally() { // Call the base implementation. base.SpoolingFinally(); // Dispose of the source enumerator _source.Dispose(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using TeamsServices.Areas.HelpPage.ModelDescriptions; using TeamsServices.Areas.HelpPage.Models; namespace TeamsServices.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
#region BSD License /* Copyright (c) 2011, Clarius Consulting 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 Clarius Consulting nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion namespace TracerHub.Diagnostics { using Microsoft.AspNet.SignalR.Client; using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Globalization; /// <summary> /// Provides a <see cref="TraceListener"/> implementation that connects to a /// remote SignalR hub to dispatch calls to its <c>TraceEvent</c> overloads. /// </summary> public partial class RealtimeTraceListener : TraceListener { /// <summary> /// The SignalR hosted hub. Change to your own host URL if self-hosting. /// </summary> const string HostedHubUrl = "http://tracer.azurewebsites.net/"; static readonly string DefaultHubUrl; const string HubName = "Tracer"; string hubUrl; string groupName; /// <summary> /// Initializes the Hub URL from the <c>HubUrl</c> appSettings configuration /// value, or sets it to the default tracer hub. /// </summary> static RealtimeTraceListener() { DefaultHubUrl = ConfigurationManager.AppSettings["HubUrl"]; if (string.IsNullOrEmpty(DefaultHubUrl)) DefaultHubUrl = HostedHubUrl; } /// <summary> /// Initializes a new instance of the <see cref="RealtimeTraceListener"/> class. /// </summary> /// <param name="groupName">Name of the group within the hub to broadcast traces to.</param> public RealtimeTraceListener(string groupName) { if (string.IsNullOrEmpty(groupName)) throw new ArgumentException("String value for groupName cannot be empty or null.", "groupName"); this.groupName = groupName; this.hubUrl = DefaultHubUrl; } ~RealtimeTraceListener() { Dispose(false); GC.SuppressFinalize(this); } /// <summary> /// Gets the SignalR hub, if connected. Null otherwise. /// </summary> public HubConnection Hub { get; private set; } /// <summary> /// Gets the SignalR hub proxy, if connected. Null otherwise. /// </summary> public IHubProxy Proxy { get; private set; } public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { if ((this.Filter == null) || this.Filter.ShouldTrace(eventCache, source, eventType, id, message, null, null, null)) { DoTraceEvent(eventCache, source, eventType, id, message); } } public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args) { if ((this.Filter == null) || this.Filter.ShouldTrace(eventCache, source, eventType, id, format, args, null, null)) { if (args == null || args.Length == 0) DoTraceEvent(eventCache, source, eventType, id, format); else DoTraceEvent(eventCache, source, eventType, id, string.Format(CultureInfo.InvariantCulture, format, args)); } } /// <summary> /// No-op, since this listener only pushes <c>TraceEvent</c> calls. /// </summary> public override void Write(string message) { } /// <summary> /// No-op, since this listener only pushes <c>TraceEvent</c> calls. /// </summary> public override void WriteLine(string message) { } /// <summary> /// Disposes the underlying SignalR hub, if connected. /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing && Hub != null) { Hub.Dispose(); Hub = null; } } /// <summary> /// Invoked when the <see cref="Hub"/> and <see cref="Proxy"/> are created /// but before connecting to the remote hub via the <c>Start</c> method /// on the <see cref="Hub"/>. /// </summary> partial void OnConnecting(); /// <summary> /// Invoked when the <see cref="Hub"/> and <see cref="Proxy"/> are created /// and connected to the remote hub. /// </summary> partial void OnConnected(); // NOTE: Tracer.SystemDiagnostics for .NET 4.0+ (required to use this listener) // always traces asynchronously, so it's fine to just Wait() here for the connection, // since this would NOT be slowing down the app in any way. Also, Tracer will trace // in a single background thread, so this is automatically "thread-safe" without needing // an explicit lock. private void DoTraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { if (Hub == null) { var data = new Dictionary<string, string> { { "groupName", groupName } }; Hub = new HubConnection(hubUrl, data); Proxy = Hub.CreateHubProxy(HubName); OnConnecting(); Hub.Start().Wait(); OnConnected(); } Proxy.Invoke("TraceEvent", new TraceEventInfo { EventType = eventType, Source = source, Message = message, }); } /// <summary> /// Payload data to send to the hub about the traced event. /// </summary> partial class TraceEventInfo { /// <summary> /// Gets or sets the type of the event trace. /// </summary> public TraceEventType EventType { get; set; } /// <summary> /// Gets or sets the trace message. /// </summary> public string Message { get; set; } /// <summary> /// Gets or sets the source of the trace event. /// </summary> public string Source { get; set; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.ExternalPackageGenerators.Msdn { using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Reactive.Concurrency; using System.Reactive.Linq; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Xml; using Microsoft.DocAsCode.Build.Engine; using Microsoft.DocAsCode.Glob; using Microsoft.DocAsCode.Plugins; internal sealed class Program { #region Fields private static readonly Regex GenericMethodPostFix = new Regex(@"``\d+$", RegexOptions.Compiled); private static string MsdnUrlTemplate = "https://msdn.microsoft.com/en-us/library/{0}(v={1}).aspx"; private static string MtpsApiUrlTemplate = "http://services.mtps.microsoft.com/ServiceAPI/content/{0}/en-us;{1}/common/mtps.links"; private static int HttpMaxConcurrency = 64; private static int[] RetryDelay = new[] { 1000, 3000, 10000 }; private static int StatisticsFreshPerSecond = 5; private static readonly Stopwatch Stopwatch = Stopwatch.StartNew(); private readonly Regex NormalUid = new Regex(@"^[a-zA-Z0-9_\.]+$", RegexOptions.Compiled); private readonly HttpClient _client = new HttpClient(); private readonly Cache<string> _shortIdCache; private readonly Cache<Dictionary<string, string>> _commentIdToShortIdMapCache; private readonly Cache<StrongBox<bool?>> _checkUrlCache; private readonly string _packageFile; private readonly string _baseDirectory; private readonly string _globPattern; private readonly string _msdnVersion; private readonly int _maxHttp; private readonly int _maxEntry; private readonly SemaphoreSlim _semaphoreForHttp; private readonly SemaphoreSlim _semaphoreForEntry; private int _entryCount; private int _apiCount; private string[] _currentPackages = new string[2]; #endregion #region Entry Point private static int Main(string[] args) { if (args.Length != 4) { PrintUsage(); return 2; } try { ReadConfig(); ServicePointManager.DefaultConnectionLimit = HttpMaxConcurrency; ThreadPool.SetMinThreads(HttpMaxConcurrency, HttpMaxConcurrency); var p = new Program(args[0], args[1], args[2], args[3]); p.PackReference(); return 0; } catch (Exception ex) { Console.Error.WriteLine(ex); return 1; } } private static void ReadConfig() { MsdnUrlTemplate = ConfigurationManager.AppSettings["MsdnUrlTemplate"] ?? MsdnUrlTemplate; MtpsApiUrlTemplate = ConfigurationManager.AppSettings["MtpsApiUrlTemplate"] ?? MtpsApiUrlTemplate; if (ConfigurationManager.AppSettings["HttpMaxConcurrency"] != null) { if (int.TryParse(ConfigurationManager.AppSettings["HttpMaxConcurrency"], out int value) && value > 0) { HttpMaxConcurrency = value; } else { Console.WriteLine("Bad config: HttpMaxConcurrency, using default value:{0}", HttpMaxConcurrency); } } if (ConfigurationManager.AppSettings["RetryDelayInMillisecond"] != null) { string[] texts; texts = ConfigurationManager.AppSettings["RetryDelayInMillisecond"].Split(','); var values = new int[texts.Length]; for (int i = 0; i < texts.Length; i++) { if (!int.TryParse(texts[i].Trim(), out values[i])) { break; } } if (values.All(v => v > 0)) { RetryDelay = values; } else { Console.WriteLine("Bad config: RetryDelayInMillisecond, using default value:{0}", string.Join(", ", RetryDelay)); } } if (ConfigurationManager.AppSettings["StatisticsFreshPerSecond"] != null) { if (int.TryParse(ConfigurationManager.AppSettings["StatisticsFreshPerSecond"], out int value) && value > 0) { StatisticsFreshPerSecond = value; } else { Console.WriteLine("Bad config: StatisticsFreshPerSecond, using default value:{0}", HttpMaxConcurrency); } } } #endregion #region Constructor public Program(string packageDirectory, string baseDirectory, string globPattern, string msdnVersion) { _packageFile = packageDirectory; _baseDirectory = baseDirectory; _globPattern = globPattern; _msdnVersion = msdnVersion; _shortIdCache = new Cache<string>(nameof(_shortIdCache), LoadShortIdAsync); _commentIdToShortIdMapCache = new Cache<Dictionary<string, string>>(nameof(_commentIdToShortIdMapCache), LoadCommentIdToShortIdMapAsync); _checkUrlCache = new Cache<StrongBox<bool?>>(nameof(_checkUrlCache), IsUrlOkAsync); _maxHttp = HttpMaxConcurrency; _maxEntry = (int)(HttpMaxConcurrency * 1.1) + 1; _semaphoreForHttp = new SemaphoreSlim(_maxHttp); _semaphoreForEntry = new SemaphoreSlim(_maxEntry); } #endregion #region Methods private static void PrintUsage() { Console.WriteLine("Usage:"); Console.WriteLine("{0} <outputFile> <baseDirectory> <globPattern> <msdnVersion>", AppDomain.CurrentDomain.FriendlyName); Console.WriteLine(" outputFile The output xref archive file."); Console.WriteLine(" e.g. \"msdn\""); Console.WriteLine(" baseDirectory The base directory contains develop comment xml file."); Console.WriteLine(" e.g. \"c:\\\""); Console.WriteLine(" globPattern The glob pattern for develop comment xml file."); Console.WriteLine(" '\' is considered as ESCAPE character, make sure to transform '\' in file path to '/'"); Console.WriteLine(" e.g. \"**/*.xml\""); Console.WriteLine(" msdnVersion The version in msdn."); Console.WriteLine(" e.g. \"vs.110\""); } private void PackReference() { var task = PackReferenceAsync(); PrintStatistics(task).Wait(); } private async Task PackReferenceAsync() { var files = GetAllFiles(); if (files.Count == 0) { return; } var dir = Path.GetDirectoryName(_packageFile); if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) { Directory.CreateDirectory(dir); } bool updateMode = File.Exists(_packageFile); using (var writer = XRefArchive.Open(_packageFile, updateMode ? XRefArchiveMode.Update : XRefArchiveMode.Create)) { if (!updateMode) { writer.CreateMajor(new XRefMap { HrefUpdated = true, Redirections = new List<XRefMapRedirection>() }); } if (files.Count == 1) { await PackOneReferenceAsync(files[0], writer); return; } // left is smaller files, right is bigger files. var left = 0; var right = files.Count - 1; var leftTask = PackOneReferenceAsync(files[left], writer); var rightTask = PackOneReferenceAsync(files[right], writer); while (left <= right) { var completed = await Task.WhenAny(new[] { leftTask, rightTask }.Where(t => t != null)); await completed; // throw if any error. if (completed == leftTask) { left++; if (left < right) { leftTask = PackOneReferenceAsync(files[left], writer); } else { leftTask = null; } } else { right--; if (left < right) { rightTask = PackOneReferenceAsync(files[right], writer); } else { rightTask = null; } } } } } private async Task PackOneReferenceAsync(string file, XRefArchive writer) { var currentPackage = Path.GetFileName(file); lock (_currentPackages) { _currentPackages[Array.IndexOf(_currentPackages, null)] = currentPackage; } var entries = new List<XRefMapRedirection>(); await GetItems(file).ForEachAsync(pair => { lock (writer) { entries.Add( new XRefMapRedirection { UidPrefix = pair.EntryName, Href = writer.CreateMinor( new XRefMap { Sorted = true, HrefUpdated = true, References = pair.ViewModel, }, new[] { pair.EntryName }) }); _entryCount++; _apiCount += pair.ViewModel.Count; } }); lock (writer) { var map = writer.GetMajor(); map.Redirections = (from r in map.Redirections.Concat(entries) orderby r.UidPrefix.Length descending select r).ToList(); writer.UpdateMajor(map); } lock (_currentPackages) { _currentPackages[Array.IndexOf(_currentPackages, currentPackage)] = null; } } private async Task PrintStatistics(Task mainTask) { bool isFirst = true; var queue = new Queue<Tuple<int, int>>(10 * StatisticsFreshPerSecond); while (!mainTask.IsCompleted) { await Task.Delay(1000 / StatisticsFreshPerSecond); if (queue.Count >= 10 * StatisticsFreshPerSecond) { queue.Dequeue(); } var last = Tuple.Create(_entryCount, _apiCount); queue.Enqueue(last); if (isFirst) { isFirst = false; } else { Console.SetCursorPosition(0, Console.CursorTop - 3 - _currentPackages.Length); } lock (_currentPackages) { for (int i = 0; i < _currentPackages.Length; i++) { Console.WriteLine("Packing: " + (_currentPackages[i] ?? string.Empty).PadRight(Console.WindowWidth - "Packing: ".Length - 1)); } } Console.WriteLine( "Elapsed time: {0}, generated type: {1}, generated api: {2}", Stopwatch.Elapsed.ToString(@"hh\:mm\:ss"), _entryCount.ToString(), _apiCount.ToString()); Console.WriteLine( "Status: http:{0,4}, type entry:{1,4}", (_maxHttp - _semaphoreForHttp.CurrentCount).ToString(), (_maxEntry - _semaphoreForEntry.CurrentCount).ToString()); Console.WriteLine( "Generating per second: type:{0,7}, api:{1,7}", ((double)(last.Item1 - queue.Peek().Item1) * StatisticsFreshPerSecond / queue.Count).ToString("F1"), ((double)(last.Item2 - queue.Peek().Item2) * StatisticsFreshPerSecond / queue.Count).ToString("F1")); } try { await mainTask; } catch (Exception ex) { Console.WriteLine(ex); } } private IObservable<EntryNameAndViewModel> GetItems(string file) { return from entry in (from entry in GetAllCommentId(file) select entry).AcquireSemaphore(_semaphoreForEntry).ToObservable(Scheduler.Default) from vm in Observable.FromAsync(() => GetXRefSpecAsync(entry)).Do(_ => _semaphoreForEntry.Release()) where vm.Count > 0 select new EntryNameAndViewModel(entry.EntryName, vm); } private async Task<List<XRefSpec>> GetXRefSpecAsync(ClassEntry entry) { var result = new List<XRefSpec>(entry.Items.Count); var type = entry.Items.Find(item => item.Uid == entry.EntryName); XRefSpec typeSpec = null; if (type != null) { typeSpec = await GetXRefSpecAsync(type); if (typeSpec != null) { result.Add(typeSpec); } } int size = 0; foreach (var specsTask in from block in (from item in entry.Items where item != type select item).BlockBuffer(() => size = size * 2 + 1) select Task.WhenAll(from item in block select GetXRefSpecAsync(item))) { result.AddRange(from s in await specsTask where s != null select s); } result.AddRange(await GetOverloadXRefSpecAsync(result)); if (typeSpec != null && typeSpec.Href != null) { // handle enum field, or other one-page-member foreach (var item in result) { if (item.Href == null) { item.Href = typeSpec.Href; } } } else { result.RemoveAll(item => item.Href == null); } result.Sort(XRefSpecUidComparer.Instance); return result; } private async Task<XRefSpec> GetXRefSpecAsync(CommentIdAndUid pair) { var alias = GetAliasWithMember(pair.CommentId); if (alias != null) { var url = string.Format(MsdnUrlTemplate, alias, _msdnVersion); // verify alias exists var vr = (await _checkUrlCache.GetAsync(pair.CommentId + "||||" + url)).Value; if (vr == true) { return new XRefSpec { Uid = pair.Uid, CommentId = pair.CommentId, Href = url, }; } } var shortId = await _shortIdCache.GetAsync(pair.CommentId); if (string.IsNullOrEmpty(shortId)) { if (pair.CommentId.StartsWith("F:")) { // work around for enum field. shortId = await _shortIdCache.GetAsync( "T:" + pair.CommentId.Remove(pair.CommentId.LastIndexOf('.')).Substring(2)); if (string.IsNullOrEmpty(shortId)) { return null; } } else { return null; } } return new XRefSpec { Uid = pair.Uid, CommentId = pair.CommentId, Href = string.Format(MsdnUrlTemplate, shortId, _msdnVersion), }; } private async Task<XRefSpec[]> GetOverloadXRefSpecAsync(List<XRefSpec> specs) { var pairs = (from spec in specs let overload = GetOverloadIdBody(spec) where overload != null group Tuple.Create(spec, overload) by overload.Uid into g select g.First()); return await Task.WhenAll(from pair in pairs select GetOverloadXRefSpecCoreAsync(pair)); } private async Task<XRefSpec> GetOverloadXRefSpecCoreAsync(Tuple<XRefSpec, CommentIdAndUid> pair) { var dict = await _commentIdToShortIdMapCache.GetAsync(pair.Item1.CommentId); if (dict.TryGetValue(pair.Item2.CommentId, out string shortId)) { return new XRefSpec { Uid = pair.Item2.Uid, CommentId = pair.Item2.CommentId, Href = string.Format(MsdnUrlTemplate, shortId, _msdnVersion), }; } else { return new XRefSpec(pair.Item1) { Uid = pair.Item2.Uid }; } } private static CommentIdAndUid GetOverloadIdBody(XRefSpec pair) { switch (pair.CommentId[0]) { case 'M': case 'P': var body = pair.Uid; var index = body.IndexOf('('); if (index != -1) { body = body.Remove(index); } body = GenericMethodPostFix.Replace(body, string.Empty); return new CommentIdAndUid("Overload:" + body, body + "*"); default: return null; } } private string GetContainingCommentId(string commentId) { var result = commentId; var index = result.IndexOf('('); if (index != -1) { result = result.Remove(index); } index = result.LastIndexOf('.'); if (index != -1) { result = result.Remove(index); switch (result[0]) { case 'E': case 'F': case 'M': case 'P': return "T" + result.Substring(1); case 'O': return "T" + result.Substring("Overload".Length); default: return "N" + result.Substring(1); } } return null; } private string GetAlias(string commentId) { if (!commentId.StartsWith("T:") && !commentId.StartsWith("N:")) { return null; } var uid = commentId.Substring(2); if (NormalUid.IsMatch(uid)) { return uid.ToLower(); } return null; } private string GetAliasWithMember(string commentId) { var uid = commentId.Substring(2); var parameterIndex = uid.IndexOf('('); if (parameterIndex != -1) { uid = uid.Remove(parameterIndex); } uid = GenericMethodPostFix.Replace(uid, string.Empty); if (NormalUid.IsMatch(uid)) { return uid.ToLower(); } return null; } private async Task<string> LoadShortIdAsync(string commentId) { string alias = GetAlias(commentId); string currentCommentId = commentId; if (alias != null) { using (var response = await _client.GetWithRetryAsync(string.Format(MsdnUrlTemplate, alias, _msdnVersion), _semaphoreForHttp, RetryDelay)) { if (response.StatusCode == HttpStatusCode.OK) { using (var stream = await response.Content.ReadAsStreamAsync()) using (var xr = XmlReader.Create(stream, new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore })) { while (xr.ReadToFollowing("meta")) { if (xr.GetAttribute("name") == "Search.ShortId" || xr.GetAttribute("name") == "ms.shortidmsdn") { return xr.GetAttribute("content"); } } } } } } do { var containingCommentId = GetContainingCommentId(currentCommentId); if (containingCommentId == null) { return string.Empty; } var dict = await _commentIdToShortIdMapCache.GetAsync(containingCommentId); if (dict.TryGetValue(commentId, out string shortId)) { return shortId; } else { // maybe case not match. shortId = dict.FirstOrDefault(p => string.Equals(p.Key, commentId, StringComparison.OrdinalIgnoreCase)).Value; if (shortId != null) { return shortId; } } currentCommentId = containingCommentId; } while (commentId[0] == 'T'); // handle nested type return string.Empty; } private async Task<Dictionary<string, string>> LoadCommentIdToShortIdMapAsync(string containingCommentId) { var result = new Dictionary<string, string>(); var shortId = await _shortIdCache.GetAsync(containingCommentId); if (!string.IsNullOrEmpty(shortId)) { using (var response = await _client.GetWithRetryAsync(string.Format(MtpsApiUrlTemplate, shortId, _msdnVersion), _semaphoreForHttp, RetryDelay)) { if (response.StatusCode == HttpStatusCode.OK) { using (var stream = await response.Content.ReadAsStreamAsync()) using (var xr = XmlReader.Create(stream, new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore })) { foreach (var item in ReadApiContent(xr)) { result[item.Item1] = item.Item2; } } } } } return result; } private IEnumerable<Tuple<string, string>> ReadApiContent(XmlReader xr) { while (xr.ReadToFollowing("div")) { if (xr.GetAttribute("class") == "link-data") { using (var subtree = xr.ReadSubtree()) { string assetId = null; string shortId = null; while (subtree.ReadToFollowing("span")) { var className = subtree.GetAttribute("class"); if (className == "link-short-id") { shortId = subtree.ReadElementContentAsString(); } if (className == "link-asset-id") { assetId = subtree.ReadElementContentAsString(); } } if (shortId != null && assetId != null && assetId.StartsWith("AssetId:")) { yield return Tuple.Create(assetId.Substring("AssetId:".Length), shortId); } } } } } private IEnumerable<ClassEntry> GetAllCommentId(string file) { return from commentId in GetAllCommentIdCore(file) where commentId.StartsWith("N:") || commentId.StartsWith("T:") || commentId.StartsWith("E:") || commentId.StartsWith("F:") || commentId.StartsWith("M:") || commentId.StartsWith("P:") let uid = commentId.Substring(2) let lastDot = uid.Split('(')[0].LastIndexOf('.') group new CommentIdAndUid(commentId, uid) by commentId.StartsWith("N:") || commentId.StartsWith("T:") || lastDot == -1 ? uid : uid.Remove(lastDot) into g select new ClassEntry(g.Key, g.ToList()); } private List<string> GetAllFiles() { // just guess: the bigger files contains more apis/types. var files = (from file in FileGlob.GetFiles(_baseDirectory, new string[] { _globPattern }, null) let fi = new FileInfo(file) orderby fi.Length select file).ToList(); if (files.Count > 0) { Console.WriteLine("Loading comment id from:"); foreach (var file in files) { Console.WriteLine(file); } } else { Console.WriteLine("File not found."); } return files; } private IEnumerable<string> GetAllCommentIdCore(string file) { if (".xml".Equals(Path.GetExtension(file), StringComparison.OrdinalIgnoreCase)) { return GetAllCommentIdFromXml(file); } if (".txt".Equals(Path.GetExtension(file), StringComparison.OrdinalIgnoreCase)) { return GetAllCommentIdFromText(file); } throw new NotSupportedException($"Unable to read comment id from file: {file}."); } private IEnumerable<string> GetAllCommentIdFromXml(string file) { return from reader in new Func<XmlReader>(() => XmlReader.Create(file)) .EmptyIfThrow() .ProtectResource() where reader.ReadToFollowing("members") from apiReader in reader.Elements("member") let commentId = apiReader.GetAttribute("name") where commentId != null select commentId; } private IEnumerable<string> GetAllCommentIdFromText(string file) { return File.ReadLines(file); } private async Task<StrongBox<bool?>> IsUrlOkAsync(string pair) { var index = pair.IndexOf("||||"); var commentId = pair.Remove(index); var url = pair.Substring(index + "||||".Length); using (var response = await _client.GetWithRetryAsync(url, _semaphoreForHttp, RetryDelay)) { if (response.StatusCode != HttpStatusCode.OK) { return new StrongBox<bool?>(null); } using (var stream = await response.Content.ReadAsStreamAsync()) using (var xr = XmlReader.Create(stream, new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore })) { while (xr.ReadToFollowing("meta")) { if (xr.GetAttribute("name") == "ms.assetid") { return new StrongBox<bool?>(commentId.Equals(xr.GetAttribute("content"), StringComparison.OrdinalIgnoreCase)); } } } return new StrongBox<bool?>(false); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System.Threading; using System.Globalization; using System.Threading.Tasks; using System.Runtime.CompilerServices; using System.Buffers; namespace System.IO { // This abstract base class represents a writer that can write a sequential // stream of characters. A subclass must minimally implement the // Write(char) method. // // This class is intended for character output, not bytes. // There are methods on the Stream class for writing bytes. public abstract partial class TextWriter : MarshalByRefObject, IDisposable { public static readonly TextWriter Null = new NullTextWriter(); // We don't want to allocate on every TextWriter creation, so cache the char array. private static readonly char[] s_coreNewLine = Environment.NewLine.ToCharArray(); /// <summary> /// This is the 'NewLine' property expressed as a char[]. /// It is exposed to subclasses as a protected field for read-only /// purposes. You should only modify it by using the 'NewLine' property. /// In particular you should never modify the elements of the array /// as they are shared among many instances of TextWriter. /// </summary> protected char[] CoreNewLine = s_coreNewLine; private string CoreNewLineStr = Environment.NewLine; // Can be null - if so, ask for the Thread's CurrentCulture every time. private IFormatProvider _internalFormatProvider; protected TextWriter() { _internalFormatProvider = null; // Ask for CurrentCulture all the time. } protected TextWriter(IFormatProvider formatProvider) { _internalFormatProvider = formatProvider; } public virtual IFormatProvider FormatProvider { get { if (_internalFormatProvider == null) { return CultureInfo.CurrentCulture; } else { return _internalFormatProvider; } } } public virtual void Close() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // Clears all buffers for this TextWriter and causes any buffered data to be // written to the underlying device. This default method is empty, but // descendant classes can override the method to provide the appropriate // functionality. public virtual void Flush() { } public abstract Encoding Encoding { get; } // Returns the line terminator string used by this TextWriter. The default line // terminator string is a carriage return followed by a line feed ("\r\n"). // // Sets the line terminator string for this TextWriter. The line terminator // string is written to the text stream whenever one of the // WriteLine methods are called. In order for text written by // the TextWriter to be readable by a TextReader, only one of the following line // terminator strings should be used: "\r", "\n", or "\r\n". // public virtual string NewLine { get { return CoreNewLineStr; } set { if (value == null) { value = Environment.NewLine; } CoreNewLineStr = value; CoreNewLine = value.ToCharArray(); } } // Writes a character to the text stream. This default method is empty, // but descendant classes can override the method to provide the // appropriate functionality. // public virtual void Write(char value) { } // Writes a character array to the text stream. This default method calls // Write(char) for each of the characters in the character array. // If the character array is null, nothing is written. // public virtual void Write(char[] buffer) { if (buffer != null) { Write(buffer, 0, buffer.Length); } } // Writes a range of a character array to the text stream. This method will // write count characters of data into this TextWriter from the // buffer character array starting at position index. // public virtual void Write(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } for (int i = 0; i < count; i++) Write(buffer[index + i]); } // Writes a span of characters to the text stream. // public virtual void Write(ReadOnlySpan<char> buffer) { char[] array = ArrayPool<char>.Shared.Rent(buffer.Length); try { buffer.CopyTo(new Span<char>(array)); Write(array, 0, buffer.Length); } finally { ArrayPool<char>.Shared.Return(array); } } // Writes the text representation of a boolean to the text stream. This // method outputs either Boolean.TrueString or Boolean.FalseString. // public virtual void Write(bool value) { Write(value ? "True" : "False"); } // Writes the text representation of an integer to the text stream. The // text representation of the given value is produced by calling the // Int32.ToString() method. // public virtual void Write(int value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of an integer to the text stream. The // text representation of the given value is produced by calling the // UInt32.ToString() method. // [CLSCompliant(false)] public virtual void Write(uint value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of a long to the text stream. The // text representation of the given value is produced by calling the // Int64.ToString() method. // public virtual void Write(long value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of an unsigned long to the text // stream. The text representation of the given value is produced // by calling the UInt64.ToString() method. // [CLSCompliant(false)] public virtual void Write(ulong value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of a float to the text stream. The // text representation of the given value is produced by calling the // Float.toString(float) method. // public virtual void Write(float value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of a double to the text stream. The // text representation of the given value is produced by calling the // Double.toString(double) method. // public virtual void Write(double value) { Write(value.ToString(FormatProvider)); } public virtual void Write(decimal value) { Write(value.ToString(FormatProvider)); } // Writes a string to the text stream. If the given string is null, nothing // is written to the text stream. // public virtual void Write(string value) { if (value != null) { Write(value.ToCharArray()); } } // Writes the text representation of an object to the text stream. If the // given object is null, nothing is written to the text stream. // Otherwise, the object's ToString method is called to produce the // string representation, and the resulting string is then written to the // output stream. // public virtual void Write(object value) { if (value != null) { IFormattable f = value as IFormattable; if (f != null) { Write(f.ToString(null, FormatProvider)); } else Write(value.ToString()); } } // Writes out a formatted string. Uses the same semantics as // String.Format. // public virtual void Write(string format, object arg0) { Write(string.Format(FormatProvider, format, arg0)); } // Writes out a formatted string. Uses the same semantics as // String.Format. // public virtual void Write(string format, object arg0, object arg1) { Write(string.Format(FormatProvider, format, arg0, arg1)); } // Writes out a formatted string. Uses the same semantics as // String.Format. // public virtual void Write(string format, object arg0, object arg1, object arg2) { Write(string.Format(FormatProvider, format, arg0, arg1, arg2)); } // Writes out a formatted string. Uses the same semantics as // String.Format. // public virtual void Write(string format, params object[] arg) { Write(string.Format(FormatProvider, format, arg)); } // Writes a line terminator to the text stream. The default line terminator // is Environment.NewLine, but this value can be changed by setting the NewLine property. // public virtual void WriteLine() { Write(CoreNewLine); } // Writes a character followed by a line terminator to the text stream. // public virtual void WriteLine(char value) { Write(value); WriteLine(); } // Writes an array of characters followed by a line terminator to the text // stream. // public virtual void WriteLine(char[] buffer) { Write(buffer); WriteLine(); } // Writes a range of a character array followed by a line terminator to the // text stream. // public virtual void WriteLine(char[] buffer, int index, int count) { Write(buffer, index, count); WriteLine(); } public virtual void WriteLine(ReadOnlySpan<char> buffer) { char[] array = ArrayPool<char>.Shared.Rent(buffer.Length); try { buffer.CopyTo(new Span<char>(array)); WriteLine(array, 0, buffer.Length); } finally { ArrayPool<char>.Shared.Return(array); } } // Writes the text representation of a boolean followed by a line // terminator to the text stream. // public virtual void WriteLine(bool value) { Write(value); WriteLine(); } // Writes the text representation of an integer followed by a line // terminator to the text stream. // public virtual void WriteLine(int value) { Write(value); WriteLine(); } // Writes the text representation of an unsigned integer followed by // a line terminator to the text stream. // [CLSCompliant(false)] public virtual void WriteLine(uint value) { Write(value); WriteLine(); } // Writes the text representation of a long followed by a line terminator // to the text stream. // public virtual void WriteLine(long value) { Write(value); WriteLine(); } // Writes the text representation of an unsigned long followed by // a line terminator to the text stream. // [CLSCompliant(false)] public virtual void WriteLine(ulong value) { Write(value); WriteLine(); } // Writes the text representation of a float followed by a line terminator // to the text stream. // public virtual void WriteLine(float value) { Write(value); WriteLine(); } // Writes the text representation of a double followed by a line terminator // to the text stream. // public virtual void WriteLine(double value) { Write(value); WriteLine(); } public virtual void WriteLine(decimal value) { Write(value); WriteLine(); } // Writes a string followed by a line terminator to the text stream. // public virtual void WriteLine(string value) { if (value != null) { Write(value); } Write(CoreNewLineStr); } // Writes the text representation of an object followed by a line // terminator to the text stream. // public virtual void WriteLine(object value) { if (value == null) { WriteLine(); } else { // Call WriteLine(value.ToString), not Write(Object), WriteLine(). // This makes calls to WriteLine(Object) atomic. IFormattable f = value as IFormattable; if (f != null) { WriteLine(f.ToString(null, FormatProvider)); } else { WriteLine(value.ToString()); } } } // Writes out a formatted string and a new line. Uses the same // semantics as String.Format. // public virtual void WriteLine(string format, object arg0) { WriteLine(string.Format(FormatProvider, format, arg0)); } // Writes out a formatted string and a new line. Uses the same // semantics as String.Format. // public virtual void WriteLine(string format, object arg0, object arg1) { WriteLine(string.Format(FormatProvider, format, arg0, arg1)); } // Writes out a formatted string and a new line. Uses the same // semantics as String.Format. // public virtual void WriteLine(string format, object arg0, object arg1, object arg2) { WriteLine(string.Format(FormatProvider, format, arg0, arg1, arg2)); } // Writes out a formatted string and a new line. Uses the same // semantics as String.Format. // public virtual void WriteLine(string format, params object[] arg) { WriteLine(string.Format(FormatProvider, format, arg)); } #region Task based Async APIs public virtual Task WriteAsync(char value) { var tuple = new Tuple<TextWriter, char>(this, value); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, char>)state; t.Item1.Write(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } public virtual Task WriteAsync(string value) { var tuple = new Tuple<TextWriter, string>(this, value); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, string>)state; t.Item1.Write(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } public Task WriteAsync(char[] buffer) { if (buffer == null) { return Task.CompletedTask; } return WriteAsync(buffer, 0, buffer.Length); } public virtual Task WriteAsync(char[] buffer, int index, int count) { var tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, char[], int, int>)state; t.Item1.Write(t.Item2, t.Item3, t.Item4); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } public virtual Task WriteAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default(CancellationToken)) => buffer.DangerousTryGetArray(out ArraySegment<char> array) ? WriteAsync(array.Array, array.Offset, array.Count) : Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, ReadOnlyMemory<char>>)state; t.Item1.Write(t.Item2.Span); }, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); public virtual Task WriteLineAsync(char value) { var tuple = new Tuple<TextWriter, char>(this, value); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, char>)state; t.Item1.WriteLine(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } public virtual Task WriteLineAsync(string value) { var tuple = new Tuple<TextWriter, string>(this, value); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, string>)state; t.Item1.WriteLine(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } public Task WriteLineAsync(char[] buffer) { if (buffer == null) { return WriteLineAsync(); } return WriteLineAsync(buffer, 0, buffer.Length); } public virtual Task WriteLineAsync(char[] buffer, int index, int count) { var tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, char[], int, int>)state; t.Item1.WriteLine(t.Item2, t.Item3, t.Item4); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } public virtual Task WriteLineAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default(CancellationToken)) => buffer.DangerousTryGetArray(out ArraySegment<char> array) ? WriteLineAsync(array.Array, array.Offset, array.Count) : Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, ReadOnlyMemory<char>>)state; t.Item1.WriteLine(t.Item2.Span); }, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); public virtual Task WriteLineAsync() { return WriteAsync(CoreNewLine); } public virtual Task FlushAsync() { return Task.Factory.StartNew(state => { ((TextWriter)state).Flush(); }, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } #endregion private sealed class NullTextWriter : TextWriter { internal NullTextWriter() : base(CultureInfo.InvariantCulture) { } public override Encoding Encoding { get { return Encoding.Unicode; } } public override void Write(char[] buffer, int index, int count) { } public override void Write(string value) { } // Not strictly necessary, but for perf reasons public override void WriteLine() { } // Not strictly necessary, but for perf reasons public override void WriteLine(string value) { } public override void WriteLine(object value) { } public override void Write(char value) { } } public static TextWriter Synchronized(TextWriter writer) { if (writer == null) throw new ArgumentNullException(nameof(writer)); return writer is SyncTextWriter ? writer : new SyncTextWriter(writer); } internal sealed class SyncTextWriter : TextWriter, IDisposable { private readonly TextWriter _out; internal SyncTextWriter(TextWriter t) : base(t.FormatProvider) { _out = t; } public override Encoding Encoding => _out.Encoding; public override IFormatProvider FormatProvider => _out.FormatProvider; public override string NewLine { [MethodImpl(MethodImplOptions.Synchronized)] get { return _out.NewLine; } [MethodImpl(MethodImplOptions.Synchronized)] set { _out.NewLine = value; } } [MethodImpl(MethodImplOptions.Synchronized)] public override void Close() => _out.Close(); [MethodImpl(MethodImplOptions.Synchronized)] protected override void Dispose(bool disposing) { // Explicitly pick up a potentially methodimpl'ed Dispose if (disposing) ((IDisposable)_out).Dispose(); } [MethodImpl(MethodImplOptions.Synchronized)] public override void Flush() => _out.Flush(); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(char value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(char[] buffer) => _out.Write(buffer); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(char[] buffer, int index, int count) => _out.Write(buffer, index, count); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(bool value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(int value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(uint value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(long value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(ulong value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(float value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(double value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(Decimal value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(string value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(object value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(string format, object arg0) => _out.Write(format, arg0); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(string format, object arg0, object arg1) => _out.Write(format, arg0, arg1); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(string format, object arg0, object arg1, object arg2) => _out.Write(format, arg0, arg1, arg2); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(string format, object[] arg) => _out.Write(format, arg); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine() => _out.WriteLine(); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(char value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(decimal value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(char[] buffer) => _out.WriteLine(buffer); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(char[] buffer, int index, int count) => _out.WriteLine(buffer, index, count); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(bool value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(int value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(uint value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(long value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(ulong value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(float value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(double value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(string value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(object value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(string format, object arg0) => _out.WriteLine(format, arg0); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(string format, object arg0, object arg1) => _out.WriteLine(format, arg0, arg1); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(string format, object arg0, object arg1, object arg2) => _out.WriteLine(format, arg0, arg1, arg2); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(string format, object[] arg) => _out.WriteLine(format, arg); // // On SyncTextWriter all APIs should run synchronously, even the async ones. // [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteAsync(char value) { Write(value); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteAsync(string value) { Write(value); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteAsync(char[] buffer, int index, int count) { Write(buffer, index, count); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteLineAsync(char value) { WriteLine(value); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteLineAsync(string value) { WriteLine(value); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteLineAsync(char[] buffer, int index, int count) { WriteLine(buffer, index, count); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task FlushAsync() { Flush(); return Task.CompletedTask; } } } }
// 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; using System.Security.Principal; using System.Threading; using System.ComponentModel; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; namespace System.Net.Security { // // The class maintains the state of the authentication process and the security context. // It encapsulates security context and does the real work in authentication and // user data encryption // internal class NegoState { private static readonly byte[] s_emptyMessage = new byte[0]; // used in reference comparisons private static readonly AsyncCallback s_readCallback = new AsyncCallback(ReadCallback); private static readonly AsyncCallback s_writeCallback = new AsyncCallback(WriteCallback); private Stream _innerStream; private bool _leaveStreamOpen; private Exception _exception; private StreamFramer _framer; private NTAuthentication _context; private int _nestedAuth; internal const int ERROR_TRUST_FAILURE = 1790; // Used to serialize protectionLevel or impersonationLevel mismatch error to the remote side. internal const int MaxReadFrameSize = 64 * 1024; internal const int MaxWriteDataSize = 63 * 1024; // 1k for the framing and trailer that is always less as per SSPI. private bool _canRetryAuthentication; private ProtectionLevel _expectedProtectionLevel; private TokenImpersonationLevel _expectedImpersonationLevel; private uint _writeSequenceNumber; private uint _readSequenceNumber; private ExtendedProtectionPolicy _extendedProtectionPolicy; // SSPI does not send a server ack on successful auth. // This is a state variable used to gracefully handle auth confirmation. private bool _remoteOk = false; internal NegoState(Stream innerStream, bool leaveStreamOpen) { if (innerStream == null) { throw new ArgumentNullException("stream"); } _innerStream = innerStream; _leaveStreamOpen = leaveStreamOpen; } internal static string DefaultPackage { get { return NegotiationInfoClass.Negotiate; } } internal IIdentity GetIdentity() { CheckThrow(true); return NegotiateStreamPal.GetIdentity(_context); } internal void ValidateCreateContext( string package, NetworkCredential credential, string servicePrincipalName, ExtendedProtectionPolicy policy, ProtectionLevel protectionLevel, TokenImpersonationLevel impersonationLevel) { if (policy != null) { // One of these must be set if EP is turned on if (policy.CustomChannelBinding == null && policy.CustomServiceNames == null) { throw new ArgumentException(SR.net_auth_must_specify_extended_protection_scheme, nameof(policy)); } _extendedProtectionPolicy = policy; } else { _extendedProtectionPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Never); } ValidateCreateContext(package, true, credential, servicePrincipalName, _extendedProtectionPolicy.CustomChannelBinding, protectionLevel, impersonationLevel); } internal void ValidateCreateContext( string package, bool isServer, NetworkCredential credential, string servicePrincipalName, ChannelBinding channelBinding, ProtectionLevel protectionLevel, TokenImpersonationLevel impersonationLevel) { if (_exception != null && !_canRetryAuthentication) { throw _exception; } if (_context != null && _context.IsValidContext) { throw new InvalidOperationException(SR.net_auth_reauth); } if (credential == null) { throw new ArgumentNullException(nameof(credential)); } if (servicePrincipalName == null) { throw new ArgumentNullException(nameof(servicePrincipalName)); } NegotiateStreamPal.ValidateImpersonationLevel(impersonationLevel); if (_context != null && IsServer != isServer) { throw new InvalidOperationException(SR.net_auth_client_server); } _exception = null; _remoteOk = false; _framer = new StreamFramer(_innerStream); _framer.WriteHeader.MessageId = FrameHeader.HandshakeId; _expectedProtectionLevel = protectionLevel; _expectedImpersonationLevel = isServer ? impersonationLevel : TokenImpersonationLevel.None; _writeSequenceNumber = 0; _readSequenceNumber = 0; ContextFlagsPal flags = ContextFlagsPal.Connection; // A workaround for the client when talking to Win9x on the server side. if (protectionLevel == ProtectionLevel.None && !isServer) { package = NegotiationInfoClass.NTLM; } else if (protectionLevel == ProtectionLevel.EncryptAndSign) { flags |= ContextFlagsPal.Confidentiality; } else if (protectionLevel == ProtectionLevel.Sign) { // Assuming user expects NT4 SP4 and above. flags |= (ContextFlagsPal.ReplayDetect | ContextFlagsPal.SequenceDetect | ContextFlagsPal.InitIntegrity); } if (isServer) { if (_extendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.WhenSupported) { flags |= ContextFlagsPal.AllowMissingBindings; } if (_extendedProtectionPolicy.PolicyEnforcement != PolicyEnforcement.Never && _extendedProtectionPolicy.ProtectionScenario == ProtectionScenario.TrustedProxy) { flags |= ContextFlagsPal.ProxyBindings; } } else { // Server side should not request any of these flags. if (protectionLevel != ProtectionLevel.None) { flags |= ContextFlagsPal.MutualAuth; } if (impersonationLevel == TokenImpersonationLevel.Identification) { flags |= ContextFlagsPal.InitIdentify; } if (impersonationLevel == TokenImpersonationLevel.Delegation) { flags |= ContextFlagsPal.Delegate; } } _canRetryAuthentication = false; try { _context = new NTAuthentication(isServer, package, credential, servicePrincipalName, flags, channelBinding); } catch (Win32Exception e) { throw new AuthenticationException(SR.net_auth_SSPI, e); } } private Exception SetException(Exception e) { if (_exception == null || !(_exception is ObjectDisposedException)) { _exception = e; } if (_exception != null && _context != null) { _context.CloseContext(); } return _exception; } internal bool IsAuthenticated { get { return _context != null && HandshakeComplete && _exception == null && _remoteOk; } } internal bool IsMutuallyAuthenticated { get { if (!IsAuthenticated) { return false; } // Suppressing for NTLM since SSPI does not return correct value in the context flags. if (_context.IsNTLM) { return false; } return _context.IsMutualAuthFlag; } } internal bool IsEncrypted { get { return IsAuthenticated && _context.IsConfidentialityFlag; } } internal bool IsSigned { get { return IsAuthenticated && (_context.IsIntegrityFlag || _context.IsConfidentialityFlag); } } internal bool IsServer { get { return _context != null && _context.IsServer; } } internal bool CanGetSecureStream { get { return (_context.IsConfidentialityFlag || _context.IsIntegrityFlag); } } internal TokenImpersonationLevel AllowedImpersonation { get { CheckThrow(true); return PrivateImpersonationLevel; } } private TokenImpersonationLevel PrivateImpersonationLevel { get { // We should suppress the delegate flag in NTLM case. return (_context.IsDelegationFlag && _context.ProtocolName != NegotiationInfoClass.NTLM) ? TokenImpersonationLevel.Delegation : _context.IsIdentifyFlag ? TokenImpersonationLevel.Identification : TokenImpersonationLevel.Impersonation; } } private bool HandshakeComplete { get { return _context.IsCompleted && _context.IsValidContext; } } internal void CheckThrow(bool authSucessCheck) { if (_exception != null) { throw _exception; } if (authSucessCheck && !IsAuthenticated) { throw new InvalidOperationException(SR.net_auth_noauth); } } // // This is to not depend on GC&SafeHandle class if the context is not needed anymore. // internal void Close() { // Mark this instance as disposed. _exception = new ObjectDisposedException("NegotiateStream"); if (_context != null) { _context.CloseContext(); } } internal void ProcessAuthentication(LazyAsyncResult lazyResult) { CheckThrow(false); if (Interlocked.Exchange(ref _nestedAuth, 1) == 1) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidnestedcall, lazyResult == null ? "BeginAuthenticate" : "Authenticate", "authenticate")); } try { if (_context.IsServer) { // Listen for a client blob. StartReceiveBlob(lazyResult); } else { // Start with the first blob. StartSendBlob(null, lazyResult); } } catch (Exception e) { // Round-trip it through SetException(). e = SetException(e); throw; } finally { if (lazyResult == null || _exception != null) { _nestedAuth = 0; } } } internal void EndProcessAuthentication(IAsyncResult result) { if (result == null) { throw new ArgumentNullException("asyncResult"); } LazyAsyncResult lazyResult = result as LazyAsyncResult; if (lazyResult == null) { throw new ArgumentException(SR.Format(SR.net_io_async_result, result.GetType().FullName), "asyncResult"); } if (Interlocked.Exchange(ref _nestedAuth, 0) == 0) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndAuthenticate")); } // No "artificial" timeouts implemented so far, InnerStream controls that. lazyResult.InternalWaitForCompletion(); Exception e = lazyResult.Result as Exception; if (e != null) { // Round-trip it through the SetException(). e = SetException(e); throw e; } } private bool CheckSpn() { if (_context.IsKerberos) { return true; } if (_extendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.Never || _extendedProtectionPolicy.CustomServiceNames == null) { return true; } string clientSpn = _context.ClientSpecifiedSpn; if (String.IsNullOrEmpty(clientSpn)) { if (_extendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.WhenSupported) { return true; } } else { return _extendedProtectionPolicy.CustomServiceNames.Contains(clientSpn); } return false; } // // Client side starts here, but server also loops through this method. // private void StartSendBlob(byte[] message, LazyAsyncResult lazyResult) { Exception exception = null; if (message != s_emptyMessage) { message = GetOutgoingBlob(message, ref exception); } if (exception != null) { // Signal remote side on a failed attempt. StartSendAuthResetSignal(lazyResult, message, exception); return; } if (HandshakeComplete) { if (_context.IsServer && !CheckSpn()) { exception = new AuthenticationException(SR.net_auth_bad_client_creds_or_target_mismatch); int statusCode = ERROR_TRUST_FAILURE; message = new byte[8]; //sizeof(long) for (int i = message.Length - 1; i >= 0; --i) { message[i] = (byte)(statusCode & 0xFF); statusCode = (int)((uint)statusCode >> 8); } StartSendAuthResetSignal(lazyResult, message, exception); return; } if (PrivateImpersonationLevel < _expectedImpersonationLevel) { exception = new AuthenticationException(SR.Format(SR.net_auth_context_expectation, _expectedImpersonationLevel.ToString(), PrivateImpersonationLevel.ToString())); int statusCode = ERROR_TRUST_FAILURE; message = new byte[8]; //sizeof(long) for (int i = message.Length - 1; i >= 0; --i) { message[i] = (byte)(statusCode & 0xFF); statusCode = (int)((uint)statusCode >> 8); } StartSendAuthResetSignal(lazyResult, message, exception); return; } ProtectionLevel result = _context.IsConfidentialityFlag ? ProtectionLevel.EncryptAndSign : _context.IsIntegrityFlag ? ProtectionLevel.Sign : ProtectionLevel.None; if (result < _expectedProtectionLevel) { exception = new AuthenticationException(SR.Format(SR.net_auth_context_expectation, result.ToString(), _expectedProtectionLevel.ToString())); int statusCode = ERROR_TRUST_FAILURE; message = new byte[8]; //sizeof(long) for (int i = message.Length - 1; i >= 0; --i) { message[i] = (byte)(statusCode & 0xFF); statusCode = (int)((uint)statusCode >> 8); } StartSendAuthResetSignal(lazyResult, message, exception); return; } // Signal remote party that we are done _framer.WriteHeader.MessageId = FrameHeader.HandshakeDoneId; if (_context.IsServer) { // Server may complete now because client SSPI would not complain at this point. _remoteOk = true; // However the client will wait for server to send this ACK //Force signaling server OK to the client if (message == null) { message = s_emptyMessage; } } } else if (message == null || message == s_emptyMessage) { throw new InternalException(); } if (message != null) { //even if we are completed, there could be a blob for sending. if (lazyResult == null) { _framer.WriteMessage(message); } else { IAsyncResult ar = _framer.BeginWriteMessage(message, s_writeCallback, lazyResult); if (!ar.CompletedSynchronously) { return; } _framer.EndWriteMessage(ar); } } CheckCompletionBeforeNextReceive(lazyResult); } // // This will check and logically complete the auth handshake. // private void CheckCompletionBeforeNextReceive(LazyAsyncResult lazyResult) { if (HandshakeComplete && _remoteOk) { // We are done with success. if (lazyResult != null) { lazyResult.InvokeCallback(); } return; } StartReceiveBlob(lazyResult); } // // Server side starts here, but client also loops through this method. // private void StartReceiveBlob(LazyAsyncResult lazyResult) { byte[] message; if (lazyResult == null) { message = _framer.ReadMessage(); } else { IAsyncResult ar = _framer.BeginReadMessage(s_readCallback, lazyResult); if (!ar.CompletedSynchronously) { return; } message = _framer.EndReadMessage(ar); } ProcessReceivedBlob(message, lazyResult); } private void ProcessReceivedBlob(byte[] message, LazyAsyncResult lazyResult) { // This is an EOF otherwise we would get at least *empty* message but not a null one. if (message == null) { throw new AuthenticationException(SR.net_auth_eof, null); } // Process Header information. if (_framer.ReadHeader.MessageId == FrameHeader.HandshakeErrId) { if (message.Length >= 8) // sizeof(long) { // Try to recover remote win32 Exception. long error = 0; for (int i = 0; i < 8; ++i) { error = (error << 8) + message[i]; } ThrowCredentialException(error); } throw new AuthenticationException(SR.net_auth_alert, null); } if (_framer.ReadHeader.MessageId == FrameHeader.HandshakeDoneId) { _remoteOk = true; } else if (_framer.ReadHeader.MessageId != FrameHeader.HandshakeId) { throw new AuthenticationException(SR.Format(SR.net_io_header_id, "MessageId", _framer.ReadHeader.MessageId, FrameHeader.HandshakeId), null); } CheckCompletionBeforeNextSend(message, lazyResult); } // // This will check and logically complete the auth handshake. // private void CheckCompletionBeforeNextSend(byte[] message, LazyAsyncResult lazyResult) { //If we are done don't go into send. if (HandshakeComplete) { if (!_remoteOk) { throw new AuthenticationException(SR.Format(SR.net_io_header_id, "MessageId", _framer.ReadHeader.MessageId, FrameHeader.HandshakeDoneId), null); } if (lazyResult != null) { lazyResult.InvokeCallback(); } return; } // Not yet done, get a new blob and send it if any. StartSendBlob(message, lazyResult); } // // This is to reset auth state on the remote side. // If this write succeeds we will allow auth retrying. // private void StartSendAuthResetSignal(LazyAsyncResult lazyResult, byte[] message, Exception exception) { _framer.WriteHeader.MessageId = FrameHeader.HandshakeErrId; if (IsLogonDeniedException(exception)) { if (IsServer) { exception = new InvalidCredentialException(SR.net_auth_bad_client_creds, exception); } else { exception = new InvalidCredentialException(SR.net_auth_bad_client_creds_or_target_mismatch, exception); } } if (!(exception is AuthenticationException)) { exception = new AuthenticationException(SR.net_auth_SSPI, exception); } if (lazyResult == null) { _framer.WriteMessage(message); } else { lazyResult.Result = exception; IAsyncResult ar = _framer.BeginWriteMessage(message, s_writeCallback, lazyResult); if (!ar.CompletedSynchronously) { return; } _framer.EndWriteMessage(ar); } _canRetryAuthentication = true; throw exception; } private static void WriteCallback(IAsyncResult transportResult) { if (!(transportResult.AsyncState is LazyAsyncResult)) { if (GlobalLog.IsEnabled) { GlobalLog.Assert("WriteCallback|State type is wrong, expected LazyAsyncResult."); } Debug.Fail("WriteCallback|State type is wrong, expected LazyAsyncResult."); } if (transportResult.CompletedSynchronously) { return; } LazyAsyncResult lazyResult = (LazyAsyncResult)transportResult.AsyncState; // Async completion. try { NegoState authState = (NegoState)lazyResult.AsyncObject; authState._framer.EndWriteMessage(transportResult); // Special case for an error notification. if (lazyResult.Result is Exception) { authState._canRetryAuthentication = true; throw (Exception)lazyResult.Result; } authState.CheckCompletionBeforeNextReceive(lazyResult); } catch (Exception e) { if (lazyResult.InternalPeekCompleted) { // This will throw on a worker thread. throw; } lazyResult.InvokeCallback(e); } } private static void ReadCallback(IAsyncResult transportResult) { if (!(transportResult.AsyncState is LazyAsyncResult)) { if (GlobalLog.IsEnabled) { GlobalLog.Assert("ReadCallback|State type is wrong, expected LazyAsyncResult."); } Debug.Fail("ReadCallback|State type is wrong, expected LazyAsyncResult."); } if (transportResult.CompletedSynchronously) { return; } LazyAsyncResult lazyResult = (LazyAsyncResult)transportResult.AsyncState; // Async completion. try { NegoState authState = (NegoState)lazyResult.AsyncObject; byte[] message = authState._framer.EndReadMessage(transportResult); authState.ProcessReceivedBlob(message, lazyResult); } catch (Exception e) { if (lazyResult.InternalPeekCompleted) { // This will throw on a worker thread. throw; } lazyResult.InvokeCallback(e); } } internal static bool IsError(SecurityStatusPal status) { return ((int)status.ErrorCode >= (int)SecurityStatusPalErrorCode.OutOfMemory); } private unsafe byte[] GetOutgoingBlob(byte[] incomingBlob, ref Exception e) { SecurityStatusPal statusCode; byte[] message = _context.GetOutgoingBlob(incomingBlob, false, out statusCode); if (IsError(statusCode)) { e = NegotiateStreamPal.CreateExceptionFromError(statusCode); uint error = (uint)e.HResult; message = new byte[sizeof(long)]; for (int i = message.Length - 1; i >= 0; --i) { message[i] = (byte)(error & 0xFF); error = (error >> 8); } } if (message != null && message.Length == 0) { message = s_emptyMessage; } return message; } internal int EncryptData(byte[] buffer, int offset, int count, ref byte[] outBuffer) { CheckThrow(true); // SSPI seems to ignore this sequence number. ++_writeSequenceNumber; return _context.Encrypt(buffer, offset, count, ref outBuffer, _writeSequenceNumber); } internal int DecryptData(byte[] buffer, int offset, int count, out int newOffset) { CheckThrow(true); // SSPI seems to ignore this sequence number. ++_readSequenceNumber; return _context.Decrypt(buffer, offset, count, out newOffset, _readSequenceNumber); } internal static void ThrowCredentialException(long error) { Win32Exception e = new Win32Exception((int)error); if (e.NativeErrorCode == (int)SecurityStatusPalErrorCode.LogonDenied) { throw new InvalidCredentialException(SR.net_auth_bad_client_creds, e); } if (e.NativeErrorCode == NegoState.ERROR_TRUST_FAILURE) { throw new AuthenticationException(SR.net_auth_context_expectation_remote, e); } throw new AuthenticationException(SR.net_auth_alert, e); } internal static bool IsLogonDeniedException(Exception exception) { Win32Exception win32exception = exception as Win32Exception; return (win32exception != null) && (win32exception.NativeErrorCode == (int)SecurityStatusPalErrorCode.LogonDenied); } } }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.LayoutRenderers.Wrappers { using NLog; using NLog.Layouts; using Xunit; public class WhenTests : NLogTestBase { [Fact] public void PositiveWhenTest() { SimpleLayout l = @"${message:when=logger=='logger'}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("message", l.Render(le)); } [Fact] public void NegativeWhenTest() { SimpleLayout l = @"${message:when=logger=='logger'}"; var le = LogEventInfo.Create(LogLevel.Info, "logger2", "message"); Assert.Equal("", l.Render(le)); } [Fact] public void ComplexWhenTest() { // condition is pretty complex here and includes nested layout renderers // we are testing here that layout parsers property invokes Condition parser to consume the right number of characters SimpleLayout l = @"${message:when='${pad:${logger}:padding=10:padCharacter=X}'=='XXXXlogger':padding=-10:padCharacter=Y}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("messageYYY", l.Render(le)); } [Fact] public void ComplexWhenTest2() { // condition is pretty complex here and includes nested layout renderers // we are testing here that layout parsers property invokes Condition parser to consume the right number of characters SimpleLayout l = @"${message:padding=-10:padCharacter=Y:when='${pad:${logger}:padding=10:padCharacter=X}'=='XXXXlogger'}"; var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("messageYYY", l.Render(le)); } [Fact] public void WhenElseCase() { //else cannot be invoked ambiently. First param is inner SimpleLayout l = @"${when:good:when=logger=='logger':else=better}"; { var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("good", l.Render(le)); } { var le = LogEventInfo.Create(LogLevel.Info, "logger1", "message"); Assert.Equal("better", l.Render(le)); } } [Fact] public void WhenElseCase_empty_when() { //else cannot be invoked ambiently. First param is inner SimpleLayout l = @"${when:good:else=better}"; { var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("good", l.Render(le)); } { var le = LogEventInfo.Create(LogLevel.Info, "logger1", "message"); Assert.Equal("good", l.Render(le)); } } [Fact] public void WhenElseCase_noIf() { //else cannot be invoked ambiently. First param is inner SimpleLayout l = @"${when:when=logger=='logger':else=better}"; { var le = LogEventInfo.Create(LogLevel.Info, "logger", "message"); Assert.Equal("", l.Render(le)); } { var le = LogEventInfo.Create(LogLevel.Info, "logger1", "message"); Assert.Equal("better", l.Render(le)); } } [Fact] public void WhenLogLevelConditionTestLayoutRenderer() { //else cannot be invoked ambiently. First param is inner SimpleLayout l = @"${when:when=level<=LogLevel.Info:inner=Good:else=Bad}"; { var le = LogEventInfo.Create(LogLevel.Debug, "logger", "message"); Assert.Equal("Good", l.Render(le)); } { var le = LogEventInfo.Create(LogLevel.Error, "logger1", "message"); Assert.Equal("Bad", l.Render(le)); } } [Fact] public void WhenLogLevelConditionTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug'> <filters> <when condition=""level>=LogLevel.Info"" action=""Log""></when> <when condition='true' action='Ignore' /> </filters> </logger> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Trace("Test"); AssertDebugCounter("debug", 0); logger.Debug("Test"); AssertDebugCounter("debug", 0); logger.Info("Test"); AssertDebugCounter("debug", 1); logger.Warn("Test"); AssertDebugCounter("debug", 2); logger.Error("Test"); AssertDebugCounter("debug", 3); logger.Fatal("Test"); AssertDebugCounter("debug", 4); } [Fact] public void WhenNumericAndPropertyConditionTest() { //else cannot be invoked ambiently. First param is inner SimpleLayout l = @"${when:when=100 < '${event-properties:item=Elapsed}':inner=Slow:else=Fast}"; // WhenNumericAndPropertyConditionTest_inner(l, "a", false); WhenNumericAndPropertyConditionTest_inner(l, 101, false); WhenNumericAndPropertyConditionTest_inner(l, 11, true); WhenNumericAndPropertyConditionTest_inner(l, 100, true); WhenNumericAndPropertyConditionTest_inner(l, 1, true); WhenNumericAndPropertyConditionTest_inner(l, 2, true); WhenNumericAndPropertyConditionTest_inner(l, 20, true); WhenNumericAndPropertyConditionTest_inner(l, 100000, false); } private static void WhenNumericAndPropertyConditionTest_inner(SimpleLayout l, object time, bool fast) { var le = LogEventInfo.Create(LogLevel.Debug, "logger", "message"); le.Properties["Elapsed"] = time; Assert.Equal(fast ? "Fast" : "Slow", l.Render(le)); } } }
using System; using System.Drawing; using System.Windows.Forms; using System.Security.Permissions; using System.Diagnostics.CodeAnalysis; namespace WeifenLuo.WinFormsUI.Docking { public class FloatWindow : Form, INestedPanesContainer, IDockDragSource { private NestedPaneCollection m_nestedPanes; internal const int WM_CHECKDISPOSE = (int)(Win32.Msgs.WM_USER + 1); internal protected FloatWindow(DockPanel dockPanel, DockPane pane) { InternalConstruct(dockPanel, pane, false, Rectangle.Empty); } internal protected FloatWindow(DockPanel dockPanel, DockPane pane, Rectangle bounds) { InternalConstruct(dockPanel, pane, true, bounds); } private void InternalConstruct(DockPanel dockPanel, DockPane pane, bool boundsSpecified, Rectangle bounds) { if (dockPanel == null) throw(new ArgumentNullException(Strings.FloatWindow_Constructor_NullDockPanel)); m_nestedPanes = new NestedPaneCollection(this); FormBorderStyle = FormBorderStyle.SizableToolWindow; ShowInTaskbar = false; if (dockPanel.RightToLeft != RightToLeft) RightToLeft = dockPanel.RightToLeft; if (RightToLeftLayout != dockPanel.RightToLeftLayout) RightToLeftLayout = dockPanel.RightToLeftLayout; SuspendLayout(); if (boundsSpecified) { Bounds = bounds; StartPosition = FormStartPosition.Manual; } else { StartPosition = FormStartPosition.WindowsDefaultLocation; Size = dockPanel.DefaultFloatWindowSize; } m_dockPanel = dockPanel; Owner = DockPanel.FindForm(); DockPanel.AddFloatWindow(this); if (pane != null) pane.FloatWindow = this; if (PatchController.EnableFontInheritanceFix == true) { Font = dockPanel.Font; } ResumeLayout(); } protected override void Dispose(bool disposing) { if (disposing) { if (DockPanel != null) DockPanel.RemoveFloatWindow(this); m_dockPanel = null; } base.Dispose(disposing); } private bool m_allowEndUserDocking = true; public bool AllowEndUserDocking { get { return m_allowEndUserDocking; } set { m_allowEndUserDocking = value; } } private bool m_doubleClickTitleBarToDock = true; public bool DoubleClickTitleBarToDock { get { return m_doubleClickTitleBarToDock; } set { m_doubleClickTitleBarToDock = value; } } public NestedPaneCollection NestedPanes { get { return m_nestedPanes; } } public VisibleNestedPaneCollection VisibleNestedPanes { get { return NestedPanes.VisibleNestedPanes; } } private DockPanel m_dockPanel; public DockPanel DockPanel { get { return m_dockPanel; } } public DockState DockState { get { return DockState.Float; } } public bool IsFloat { get { return DockState == DockState.Float; } } internal bool IsDockStateValid(DockState dockState) { foreach (DockPane pane in NestedPanes) foreach (IDockContent content in pane.Contents) if (!DockHelper.IsDockStateValid(dockState, content.DockHandler.DockAreas)) return false; return true; } protected override void OnActivated(EventArgs e) { DockPanel.FloatWindows.BringWindowToFront(this); base.OnActivated (e); // Propagate the Activated event to the visible panes content objects foreach (DockPane pane in VisibleNestedPanes) foreach (IDockContent content in pane.Contents) content.OnActivated(e); } protected override void OnDeactivate(EventArgs e) { base.OnDeactivate(e); // Propagate the Deactivate event to the visible panes content objects foreach (DockPane pane in VisibleNestedPanes) foreach (IDockContent content in pane.Contents) content.OnDeactivate(e); } protected override void OnLayout(LayoutEventArgs levent) { VisibleNestedPanes.Refresh(); RefreshChanges(); Visible = (VisibleNestedPanes.Count > 0); SetText(); base.OnLayout(levent); } [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "System.Windows.Forms.Control.set_Text(System.String)")] internal void SetText() { DockPane theOnlyPane = (VisibleNestedPanes.Count == 1) ? VisibleNestedPanes[0] : null; if (theOnlyPane == null || theOnlyPane.ActiveContent == null) { Text = " "; // use " " instead of string.Empty because the whole title bar will disappear when ControlBox is set to false. Icon = null; } else { Text = theOnlyPane.ActiveContent.DockHandler.TabText; Icon = theOnlyPane.ActiveContent.DockHandler.Icon; } } protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { Rectangle rectWorkArea = SystemInformation.VirtualScreen; if (y + height > rectWorkArea.Bottom) y -= (y + height) - rectWorkArea.Bottom; if (y < rectWorkArea.Top) y += rectWorkArea.Top - y; base.SetBoundsCore (x, y, width, height, specified); } [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] protected override void WndProc(ref Message m) { switch (m.Msg) { case (int)Win32.Msgs.WM_NCLBUTTONDOWN: { if (IsDisposed) return; uint result = Win32Helper.IsRunningOnMono ? 0 : NativeMethods.SendMessage(this.Handle, (int)Win32.Msgs.WM_NCHITTEST, 0, (uint)m.LParam); if (result == 2 && DockPanel.AllowEndUserDocking && this.AllowEndUserDocking) // HITTEST_CAPTION { Activate(); m_dockPanel.BeginDrag(this); } else base.WndProc(ref m); return; } case (int)Win32.Msgs.WM_NCRBUTTONDOWN: { uint result = Win32Helper.IsRunningOnMono ? Win32Helper.HitTestCaption(this) : NativeMethods.SendMessage(this.Handle, (int)Win32.Msgs.WM_NCHITTEST, 0, (uint)m.LParam); if (result == 2) // HITTEST_CAPTION { DockPane theOnlyPane = (VisibleNestedPanes.Count == 1) ? VisibleNestedPanes[0] : null; if (theOnlyPane != null && theOnlyPane.ActiveContent != null) { theOnlyPane.ShowTabPageContextMenu(this, PointToClient(Control.MousePosition)); return; } } base.WndProc(ref m); return; } case (int)Win32.Msgs.WM_CLOSE: if (NestedPanes.Count == 0) { base.WndProc(ref m); return; } for (int i = NestedPanes.Count - 1; i >= 0; i--) { DockContentCollection contents = NestedPanes[i].Contents; for (int j = contents.Count - 1; j >= 0; j--) { IDockContent content = contents[j]; if (content.DockHandler.DockState != DockState.Float) continue; if (!content.DockHandler.CloseButton) continue; if (content.DockHandler.HideOnClose) content.DockHandler.Hide(); else content.DockHandler.Close(); } } return; case (int)Win32.Msgs.WM_NCLBUTTONDBLCLK: { uint result = !DoubleClickTitleBarToDock || Win32Helper.IsRunningOnMono ? Win32Helper.HitTestCaption(this) : NativeMethods.SendMessage(this.Handle, (int)Win32.Msgs.WM_NCHITTEST, 0, (uint)m.LParam); if (result != 2) // HITTEST_CAPTION { base.WndProc(ref m); return; } DockPanel.SuspendLayout(true); // Restore to panel foreach (DockPane pane in NestedPanes) { if (pane.DockState != DockState.Float) continue; pane.RestoreToPanel(); } DockPanel.ResumeLayout(true, true); return; } case WM_CHECKDISPOSE: if (NestedPanes.Count == 0) Dispose(); return; } base.WndProc(ref m); } internal void RefreshChanges() { if (IsDisposed) return; if (VisibleNestedPanes.Count == 0) { ControlBox = true; return; } for (int i=VisibleNestedPanes.Count - 1; i>=0; i--) { DockContentCollection contents = VisibleNestedPanes[i].Contents; for (int j=contents.Count - 1; j>=0; j--) { IDockContent content = contents[j]; if (content.DockHandler.DockState != DockState.Float) continue; if (content.DockHandler.CloseButton && content.DockHandler.CloseButtonVisible) { ControlBox = true; return; } } } //Only if there is a ControlBox do we turn it off //old code caused a flash of the window. if (ControlBox) ControlBox = false; } public virtual Rectangle DisplayingRectangle { get { return ClientRectangle; } } internal void TestDrop(IDockDragSource dragSource, DockOutlineBase dockOutline) { if (VisibleNestedPanes.Count == 1) { DockPane pane = VisibleNestedPanes[0]; if (!dragSource.CanDockTo(pane)) return; Point ptMouse = Control.MousePosition; uint lParam = Win32Helper.MakeLong(ptMouse.X, ptMouse.Y); if (!Win32Helper.IsRunningOnMono) { if (NativeMethods.SendMessage(Handle, (int)Win32.Msgs.WM_NCHITTEST, 0, lParam) == (uint)Win32.HitTest.HTCAPTION) { dockOutline.Show(VisibleNestedPanes[0], -1); } } } } #region IDockDragSource Members #region IDragSource Members Control IDragSource.DragControl { get { return this; } } #endregion bool IDockDragSource.IsDockStateValid(DockState dockState) { return IsDockStateValid(dockState); } bool IDockDragSource.CanDockTo(DockPane pane) { if (!IsDockStateValid(pane.DockState)) return false; if (pane.FloatWindow == this) return false; return true; } private int m_preDragExStyle; Rectangle IDockDragSource.BeginDrag(Point ptMouse) { m_preDragExStyle = NativeMethods.GetWindowLong(this.Handle, (int)Win32.GetWindowLongIndex.GWL_EXSTYLE); NativeMethods.SetWindowLong(this.Handle, (int)Win32.GetWindowLongIndex.GWL_EXSTYLE, m_preDragExStyle | (int)(Win32.WindowExStyles.WS_EX_TRANSPARENT | Win32.WindowExStyles.WS_EX_LAYERED) ); return Bounds; } void IDockDragSource.EndDrag() { NativeMethods.SetWindowLong(this.Handle, (int)Win32.GetWindowLongIndex.GWL_EXSTYLE, m_preDragExStyle); Invalidate(true); NativeMethods.SendMessage(this.Handle, (int)Win32.Msgs.WM_NCPAINT, 1, 0); } public void FloatAt(Rectangle floatWindowBounds) { Bounds = floatWindowBounds; } public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex) { if (dockStyle == DockStyle.Fill) { for (int i = NestedPanes.Count - 1; i >= 0; i--) { DockPane paneFrom = NestedPanes[i]; for (int j = paneFrom.Contents.Count - 1; j >= 0; j--) { IDockContent c = paneFrom.Contents[j]; c.DockHandler.Pane = pane; if (contentIndex != -1) pane.SetContentIndex(c, contentIndex); c.DockHandler.Activate(); } } } else { DockAlignment alignment = DockAlignment.Left; if (dockStyle == DockStyle.Left) alignment = DockAlignment.Left; else if (dockStyle == DockStyle.Right) alignment = DockAlignment.Right; else if (dockStyle == DockStyle.Top) alignment = DockAlignment.Top; else if (dockStyle == DockStyle.Bottom) alignment = DockAlignment.Bottom; MergeNestedPanes(VisibleNestedPanes, pane.NestedPanesContainer.NestedPanes, pane, alignment, 0.5); } } public void DockTo(DockPanel panel, DockStyle dockStyle) { if (panel != DockPanel) throw new ArgumentException(Strings.IDockDragSource_DockTo_InvalidPanel, "panel"); NestedPaneCollection nestedPanesTo = null; if (dockStyle == DockStyle.Top) nestedPanesTo = DockPanel.DockWindows[DockState.DockTop].NestedPanes; else if (dockStyle == DockStyle.Bottom) nestedPanesTo = DockPanel.DockWindows[DockState.DockBottom].NestedPanes; else if (dockStyle == DockStyle.Left) nestedPanesTo = DockPanel.DockWindows[DockState.DockLeft].NestedPanes; else if (dockStyle == DockStyle.Right) nestedPanesTo = DockPanel.DockWindows[DockState.DockRight].NestedPanes; else if (dockStyle == DockStyle.Fill) nestedPanesTo = DockPanel.DockWindows[DockState.Document].NestedPanes; DockPane prevPane = null; for (int i = nestedPanesTo.Count - 1; i >= 0; i--) if (nestedPanesTo[i] != VisibleNestedPanes[0]) prevPane = nestedPanesTo[i]; MergeNestedPanes(VisibleNestedPanes, nestedPanesTo, prevPane, DockAlignment.Left, 0.5); } private static void MergeNestedPanes(VisibleNestedPaneCollection nestedPanesFrom, NestedPaneCollection nestedPanesTo, DockPane prevPane, DockAlignment alignment, double proportion) { if (nestedPanesFrom.Count == 0) return; int count = nestedPanesFrom.Count; DockPane[] panes = new DockPane[count]; DockPane[] prevPanes = new DockPane[count]; DockAlignment[] alignments = new DockAlignment[count]; double[] proportions = new double[count]; for (int i = 0; i < count; i++) { panes[i] = nestedPanesFrom[i]; prevPanes[i] = nestedPanesFrom[i].NestedDockingStatus.PreviousPane; alignments[i] = nestedPanesFrom[i].NestedDockingStatus.Alignment; proportions[i] = nestedPanesFrom[i].NestedDockingStatus.Proportion; } DockPane pane = panes[0].DockTo(nestedPanesTo.Container, prevPane, alignment, proportion); panes[0].DockState = nestedPanesTo.DockState; for (int i = 1; i < count; i++) { for (int j = i; j < count; j++) { if (prevPanes[j] == panes[i - 1]) prevPanes[j] = pane; } pane = panes[i].DockTo(nestedPanesTo.Container, prevPanes[i], alignments[i], proportions[i]); panes[i].DockState = nestedPanesTo.DockState; } } #endregion } }
using System; using System.Collections.Generic; using Tibia.Objects; namespace Tibia.Constants { public static class CreatureLists { #region All Creatures public static Dictionary<string, CreatureData> AllCreatures = new Dictionary<string, CreatureData> { { Creatures.Achad.Name, Creatures.Achad }, { Creatures.AcidBlob.Name, Creatures.AcidBlob }, { Creatures.AcolyteofDarkness.Name, Creatures.AcolyteofDarkness }, { Creatures.AcolyteoftheCult.Name, Creatures.AcolyteoftheCult }, { Creatures.AdeptoftheCult.Name, Creatures.AdeptoftheCult }, { Creatures.Amazon.Name, Creatures.Amazon }, { Creatures.AncientScarab.Name, Creatures.AncientScarab }, { Creatures.Annihilon.Name, Creatures.Annihilon }, { Creatures.Apocalypse.Name, Creatures.Apocalypse }, { Creatures.ApprenticeSheng.Name, Creatures.ApprenticeSheng }, { Creatures.ArachirtheAncientOne.Name, Creatures.ArachirtheAncientOne }, { Creatures.Arkhothep.Name, Creatures.Arkhothep }, { Creatures.Armenius.Name, Creatures.Armenius }, { Creatures.Arthei.Name, Creatures.Arthei }, { Creatures.Ashmunrah.Name, Creatures.Ashmunrah }, { Creatures.Assassin.Name, Creatures.Assassin }, { Creatures.Avalanche.Name, Creatures.Avalanche }, { Creatures.AxeitusHeadbanger.Name, Creatures.AxeitusHeadbanger }, { Creatures.Azerus.Name, Creatures.Azerus }, { Creatures.AzureFrog.Name, Creatures.AzureFrog }, { Creatures.Badger.Name, Creatures.Badger }, { Creatures.Bandit.Name, Creatures.Bandit }, { Creatures.BaneofLight.Name, Creatures.BaneofLight }, { Creatures.Banshee.Name, Creatures.Banshee }, { Creatures.Barbaria.Name, Creatures.Barbaria }, { Creatures.BarbarianBloodwalker.Name, Creatures.BarbarianBloodwalker }, { Creatures.BarbarianBrutetamer.Name, Creatures.BarbarianBrutetamer }, { Creatures.BarbarianHeadsplitter.Name, Creatures.BarbarianHeadsplitter }, { Creatures.BarbarianSkullhunter.Name, Creatures.BarbarianSkullhunter }, { Creatures.BaronBrute.Name, Creatures.BaronBrute }, { Creatures.Bat.Name, Creatures.Bat }, { Creatures.BattlemasterZunzu.Name, Creatures.BattlemasterZunzu }, { Creatures.Bazir.Name, Creatures.Bazir }, { Creatures.Bear.Name, Creatures.Bear }, { Creatures.Behemoth.Name, Creatures.Behemoth }, { Creatures.Beholder.Name, Creatures.Beholder }, { Creatures.BerserkerChicken.Name, Creatures.BerserkerChicken }, { Creatures.BetrayedWraith.Name, Creatures.BetrayedWraith }, { Creatures.BigBossTrolliver.Name, Creatures.BigBossTrolliver }, { Creatures.BlackKnight.Name, Creatures.BlackKnight }, { Creatures.BlackSheep.Name, Creatures.BlackSheep }, { Creatures.BlazingFireElemental.Name, Creatures.BlazingFireElemental }, { Creatures.Blightwalker.Name, Creatures.Blightwalker }, { Creatures.BlisteringFireElemental.Name, Creatures.BlisteringFireElemental }, { Creatures.BloodCrab.Name, Creatures.BloodCrab }, { Creatures.BloodCrabUnderwater.Name, Creatures.BloodCrabUnderwater }, { Creatures.Bloodpaw.Name, Creatures.Bloodpaw }, { Creatures.BlueDjinn.Name, Creatures.BlueDjinn }, { Creatures.BogRaider.Name, Creatures.BogRaider }, { Creatures.Bonebeast.Name, Creatures.Bonebeast }, { Creatures.Bones.Name, Creatures.Bones }, { Creatures.Boogey.Name, Creatures.Boogey }, { Creatures.Boreth.Name, Creatures.Boreth }, { Creatures.Bovinus.Name, Creatures.Bovinus }, { Creatures.Braindeath.Name, Creatures.Braindeath }, { Creatures.BrideofNight.Name, Creatures.BrideofNight }, { Creatures.BrutusBloodbeard.Name, Creatures.BrutusBloodbeard }, { Creatures.Bug.Name, Creatures.Bug }, { Creatures.ButterflyBlue.Name, Creatures.ButterflyBlue }, { Creatures.ButterflyPurple.Name, Creatures.ButterflyPurple }, { Creatures.ButterflyRed.Name, Creatures.ButterflyRed }, { Creatures.CaptainJones.Name, Creatures.CaptainJones }, { Creatures.Carniphila.Name, Creatures.Carniphila }, { Creatures.CarrionWorm.Name, Creatures.CarrionWorm }, { Creatures.Cat.Name, Creatures.Cat }, { Creatures.CaveRat.Name, Creatures.CaveRat }, { Creatures.Centipede.Name, Creatures.Centipede }, { Creatures.ChakoyaToolshaper.Name, Creatures.ChakoyaToolshaper }, { Creatures.ChakoyaTribewarden.Name, Creatures.ChakoyaTribewarden }, { Creatures.ChakoyaWindcaller.Name, Creatures.ChakoyaWindcaller }, { Creatures.ChargedEnergyElemental.Name, Creatures.ChargedEnergyElemental }, { Creatures.Chicken.Name, Creatures.Chicken }, { Creatures.ChizzorontheDistorter.Name, Creatures.ChizzorontheDistorter }, { Creatures.Cobra.Name, Creatures.Cobra }, { Creatures.Cockroach.Name, Creatures.Cockroach }, { Creatures.Coldheart.Name, Creatures.Coldheart }, { Creatures.ColeriantheBarbarian.Name, Creatures.ColeriantheBarbarian }, { Creatures.CoralFrog.Name, Creatures.CoralFrog }, { Creatures.CountessSorrow.Name, Creatures.CountessSorrow }, { Creatures.Crab.Name, Creatures.Crab }, { Creatures.CrazedBeggar.Name, Creatures.CrazedBeggar }, { Creatures.CrimsonFrog.Name, Creatures.CrimsonFrog }, { Creatures.Crocodile.Name, Creatures.Crocodile }, { Creatures.CryptShambler.Name, Creatures.CryptShambler }, { Creatures.CrystalSpider.Name, Creatures.CrystalSpider }, { Creatures.CublarcthePlunderer.Name, Creatures.CublarcthePlunderer }, { Creatures.CursedGladiator.Name, Creatures.CursedGladiator }, { Creatures.Cyclops.Name, Creatures.Cyclops }, { Creatures.CyclopsDrone.Name, Creatures.CyclopsDrone }, { Creatures.CyclopsSmith.Name, Creatures.CyclopsSmith }, { Creatures.Daemon.Name, Creatures.Daemon }, { Creatures.DamagedWorkerGolem.Name, Creatures.DamagedWorkerGolem }, { Creatures.DarakantheExecutioner.Name, Creatures.DarakantheExecutioner }, { Creatures.DarkApprentice.Name, Creatures.DarkApprentice }, { Creatures.DarkMagician.Name, Creatures.DarkMagician }, { Creatures.DarkMonk.Name, Creatures.DarkMonk }, { Creatures.DarkTorturer.Name, Creatures.DarkTorturer }, { Creatures.DeadeyeDevious.Name, Creatures.DeadeyeDevious }, { Creatures.DeathBlob.Name, Creatures.DeathBlob }, { Creatures.Deathbringer.Name, Creatures.Deathbringer }, { Creatures.Deathslicer.Name, Creatures.Deathslicer }, { Creatures.Deathspawn.Name, Creatures.Deathspawn }, { Creatures.Deer.Name, Creatures.Deer }, { Creatures.Defiler.Name, Creatures.Defiler }, { Creatures.Demodras.Name, Creatures.Demodras }, { Creatures.Demon.Name, Creatures.Demon }, { Creatures.DemonParrot.Name, Creatures.DemonParrot }, { Creatures.DemonSkeleton.Name, Creatures.DemonSkeleton }, { Creatures.Demongoblin.Name, Creatures.Demongoblin }, { Creatures.Destroyer.Name, Creatures.Destroyer }, { Creatures.Dharalion.Name, Creatures.Dharalion }, { Creatures.DiabolicImp.Name, Creatures.DiabolicImp }, { Creatures.DiblistheFair.Name, Creatures.DiblistheFair }, { Creatures.Dipthrah.Name, Creatures.Dipthrah }, { Creatures.DirePenguin.Name, Creatures.DirePenguin }, { Creatures.Dirtbeard.Name, Creatures.Dirtbeard }, { Creatures.DiseasedBill.Name, Creatures.DiseasedBill }, { Creatures.DiseasedDan.Name, Creatures.DiseasedDan }, { Creatures.DiseasedFred.Name, Creatures.DiseasedFred }, { Creatures.DoctorPerhaps.Name, Creatures.DoctorPerhaps }, { Creatures.Dog.Name, Creatures.Dog }, { Creatures.DoomDeer.Name, Creatures.DoomDeer }, { Creatures.Doomhowl.Name, Creatures.Doomhowl }, { Creatures.DoomsdayCultist.Name, Creatures.DoomsdayCultist }, { Creatures.Dracola.Name, Creatures.Dracola }, { Creatures.Dragon.Name, Creatures.Dragon }, { Creatures.DragonHatchling.Name, Creatures.DragonHatchling }, { Creatures.DragonLord.Name, Creatures.DragonLord }, { Creatures.DragonLordHatchling.Name, Creatures.DragonLordHatchling }, { Creatures.DrakenSpellweaver.Name, Creatures.DrakenSpellweaver }, { Creatures.DrakenWarmaster.Name, Creatures.DrakenWarmaster }, { Creatures.Drasilla.Name, Creatures.Drasilla }, { Creatures.Dreadbeast.Name, Creatures.Dreadbeast }, { Creatures.Dreadmaw.Name, Creatures.Dreadmaw }, { Creatures.Dreadwing.Name, Creatures.Dreadwing }, { Creatures.Dryad.Name, Creatures.Dryad }, { Creatures.Duskbringer.Name, Creatures.Duskbringer }, { Creatures.Dwarf.Name, Creatures.Dwarf }, { Creatures.DwarfDispenser.Name, Creatures.DwarfDispenser }, { Creatures.DwarfGeomancer.Name, Creatures.DwarfGeomancer }, { Creatures.DwarfGuard.Name, Creatures.DwarfGuard }, { Creatures.DwarfHenchman.Name, Creatures.DwarfHenchman }, { Creatures.DwarfMiner.Name, Creatures.DwarfMiner }, { Creatures.DwarfSoldier.Name, Creatures.DwarfSoldier }, { Creatures.DworcFleshhunter.Name, Creatures.DworcFleshhunter }, { Creatures.DworcVenomsniper.Name, Creatures.DworcVenomsniper }, { Creatures.DworcVoodoomaster.Name, Creatures.DworcVoodoomaster }, { Creatures.EarthElemental.Name, Creatures.EarthElemental }, { Creatures.EarthOverlord.Name, Creatures.EarthOverlord }, { Creatures.EclipseKnight.Name, Creatures.EclipseKnight }, { Creatures.Efreet.Name, Creatures.Efreet }, { Creatures.ElderBeholder.Name, Creatures.ElderBeholder }, { Creatures.Elephant.Name, Creatures.Elephant }, { Creatures.Elf.Name, Creatures.Elf }, { Creatures.ElfArcanist.Name, Creatures.ElfArcanist }, { Creatures.ElfScout.Name, Creatures.ElfScout }, { Creatures.EnergyElemental.Name, Creatures.EnergyElemental }, { Creatures.EnergyOverlord.Name, Creatures.EnergyOverlord }, { Creatures.EnlightenedoftheCult.Name, Creatures.EnlightenedoftheCult }, { Creatures.EnragedBookworm.Name, Creatures.EnragedBookworm }, { Creatures.EnragedSquirrel.Name, Creatures.EnragedSquirrel }, { Creatures.Esmeralda.Name, Creatures.Esmeralda }, { Creatures.EssenceofDarkness.Name, Creatures.EssenceofDarkness }, { Creatures.EternalGuardian.Name, Creatures.EternalGuardian }, { Creatures.EvilMastermind.Name, Creatures.EvilMastermind }, { Creatures.EvilSheep.Name, Creatures.EvilSheep }, { Creatures.EvilSheepLord.Name, Creatures.EvilSheepLord }, { Creatures.EyeoftheSeven.Name, Creatures.EyeoftheSeven }, { Creatures.FahimTheWise.Name, Creatures.FahimTheWise }, { Creatures.FallenMooh.Name, Creatures.FallenMooh }, { Creatures.Fatality.Name, Creatures.Fatality }, { Creatures.Fernfang.Name, Creatures.Fernfang }, { Creatures.Ferumbras.Name, Creatures.Ferumbras }, { Creatures.FireDevil.Name, Creatures.FireDevil }, { Creatures.FireElemental.Name, Creatures.FireElemental }, { Creatures.FireOverlord.Name, Creatures.FireOverlord }, { Creatures.FlamecallerZazrak.Name, Creatures.FlamecallerZazrak }, { Creatures.Flamethrower.Name, Creatures.Flamethrower }, { Creatures.Flamingo.Name, Creatures.Flamingo }, { Creatures.Fleabringer.Name, Creatures.Fleabringer }, { Creatures.Fluffy.Name, Creatures.Fluffy }, { Creatures.ForemanKneebiter.Name, Creatures.ForemanKneebiter }, { Creatures.Freegoiz.Name, Creatures.Freegoiz }, { Creatures.FrostDragon.Name, Creatures.FrostDragon }, { Creatures.FrostDragonHatchling.Name, Creatures.FrostDragonHatchling }, { Creatures.FrostGiant.Name, Creatures.FrostGiant }, { Creatures.FrostGiantess.Name, Creatures.FrostGiantess }, { Creatures.FrostTroll.Name, Creatures.FrostTroll }, { Creatures.Frostfur.Name, Creatures.Frostfur }, { Creatures.FuriousTroll.Name, Creatures.FuriousTroll }, { Creatures.Fury.Name, Creatures.Fury }, { Creatures.Gamemaster.Name, Creatures.Gamemaster }, { Creatures.GangMember.Name, Creatures.GangMember }, { Creatures.Gargoyle.Name, Creatures.Gargoyle }, { Creatures.Gazer.Name, Creatures.Gazer }, { Creatures.GeneralMurius.Name, Creatures.GeneralMurius }, { Creatures.GhastlyDragon.Name, Creatures.GhastlyDragon }, { Creatures.Ghazbaran.Name, Creatures.Ghazbaran }, { Creatures.Ghost.Name, Creatures.Ghost }, { Creatures.GhostlyApparition.Name, Creatures.GhostlyApparition }, { Creatures.Ghoul.Name, Creatures.Ghoul }, { Creatures.GiantSpider.Name, Creatures.GiantSpider }, { Creatures.Gladiator.Name, Creatures.Gladiator }, { Creatures.Gloombringer.Name, Creatures.Gloombringer }, { Creatures.Gnarlhound.Name, Creatures.Gnarlhound }, { Creatures.GnorreChyllson.Name, Creatures.GnorreChyllson }, { Creatures.Goblin.Name, Creatures.Goblin }, { Creatures.GoblinAssassin.Name, Creatures.GoblinAssassin }, { Creatures.GoblinLeader.Name, Creatures.GoblinLeader }, { Creatures.GoblinScavenger.Name, Creatures.GoblinScavenger }, { Creatures.Golgordan.Name, Creatures.Golgordan }, { Creatures.Gozzler.Name, Creatures.Gozzler }, { Creatures.GrandMotherFoulscale.Name, Creatures.GrandMotherFoulscale }, { Creatures.GrandfatherTridian.Name, Creatures.GrandfatherTridian }, { Creatures.GravelordOshuran.Name, Creatures.GravelordOshuran }, { Creatures.GreenDjinn.Name, Creatures.GreenDjinn }, { Creatures.GreenFrog.Name, Creatures.GreenFrog }, { Creatures.GrimReaper.Name, Creatures.GrimReaper }, { Creatures.GrimgorGuteater.Name, Creatures.GrimgorGuteater }, { Creatures.Grorlam.Name, Creatures.Grorlam }, { Creatures.GrynchClanGoblin.Name, Creatures.GrynchClanGoblin }, { Creatures.Hacker.Name, Creatures.Hacker }, { Creatures.HairmanTheHuge.Name, Creatures.HairmanTheHuge }, { Creatures.HandofCursedFate.Name, Creatures.HandofCursedFate }, { Creatures.HarbingerofDarkness.Name, Creatures.HarbingerofDarkness }, { Creatures.HauntedTreeling.Name, Creatures.HauntedTreeling }, { Creatures.Haunter.Name, Creatures.Haunter }, { Creatures.HellHole.Name, Creatures.HellHole }, { Creatures.HellfireFighter.Name, Creatures.HellfireFighter }, { Creatures.Hellgorak.Name, Creatures.Hellgorak }, { Creatures.Hellhound.Name, Creatures.Hellhound }, { Creatures.Hellspawn.Name, Creatures.Hellspawn }, { Creatures.HeraldofGloom.Name, Creatures.HeraldofGloom }, { Creatures.Hero.Name, Creatures.Hero }, { Creatures.Hide.Name, Creatures.Hide }, { Creatures.HighTemplarCobrass.Name, Creatures.HighTemplarCobrass }, { Creatures.HotDog.Name, Creatures.HotDog }, { Creatures.Hunter.Name, Creatures.Hunter }, { Creatures.Husky.Name, Creatures.Husky }, { Creatures.Hyaena.Name, Creatures.Hyaena }, { Creatures.Hydra.Name, Creatures.Hydra }, { Creatures.IceGolem.Name, Creatures.IceGolem }, { Creatures.IceOverlord.Name, Creatures.IceOverlord }, { Creatures.IceWitch.Name, Creatures.IceWitch }, { Creatures.Incineron.Name, Creatures.Incineron }, { Creatures.InfernalFrog.Name, Creatures.InfernalFrog }, { Creatures.Infernalist.Name, Creatures.Infernalist }, { Creatures.Infernatil.Name, Creatures.Infernatil }, { Creatures.Inky.Name, Creatures.Inky }, { Creatures.InsectSwarm.Name, Creatures.InsectSwarm }, { Creatures.IslandTroll.Name, Creatures.IslandTroll }, { Creatures.JaggedEarthElemental.Name, Creatures.JaggedEarthElemental }, { Creatures.Juggernaut.Name, Creatures.Juggernaut }, { Creatures.KillerCaiman.Name, Creatures.KillerCaiman }, { Creatures.KillerRabbit.Name, Creatures.KillerRabbit }, { Creatures.Kitty.Name, Creatures.Kitty }, { Creatures.Kongra.Name, Creatures.Kongra }, { Creatures.KongraAntiBotter.Name, Creatures.KongraAntiBotter }, { Creatures.KosheitheDeathless.Name, Creatures.KosheitheDeathless }, { Creatures.KreeboshtheExile.Name, Creatures.KreeboshtheExile }, { Creatures.LancerBeetle.Name, Creatures.LancerBeetle }, { Creatures.Larva.Name, Creatures.Larva }, { Creatures.Latrivan.Name, Creatures.Latrivan }, { Creatures.Lavahole.Name, Creatures.Lavahole }, { Creatures.Lersatio.Name, Creatures.Lersatio }, { Creatures.LethalLissy.Name, Creatures.LethalLissy }, { Creatures.Leviathan.Name, Creatures.Leviathan }, { Creatures.Lich.Name, Creatures.Lich }, { Creatures.Lion.Name, Creatures.Lion }, { Creatures.ListofCreaturesbyConvinceCost.Name, Creatures.ListofCreaturesbyConvinceCost }, { Creatures.LizardChosen.Name, Creatures.LizardChosen }, { Creatures.LizardDragonPriest.Name, Creatures.LizardDragonPriest }, { Creatures.LizardGateGuardian.Name, Creatures.LizardGateGuardian }, { Creatures.LizardHighGuard.Name, Creatures.LizardHighGuard }, { Creatures.LizardLegionnaire.Name, Creatures.LizardLegionnaire }, { Creatures.LizardSentinel.Name, Creatures.LizardSentinel }, { Creatures.LizardSnakecharmer.Name, Creatures.LizardSnakecharmer }, { Creatures.LizardTemplar.Name, Creatures.LizardTemplar }, { Creatures.LizardZaogun.Name, Creatures.LizardZaogun }, { Creatures.LordoftheElements.Name, Creatures.LordoftheElements }, { Creatures.LostSoul.Name, Creatures.LostSoul }, { Creatures.MadScientist.Name, Creatures.MadScientist }, { Creatures.MadSheep.Name, Creatures.MadSheep }, { Creatures.MadTechnomancer.Name, Creatures.MadTechnomancer }, { Creatures.Madareth.Name, Creatures.Madareth }, { Creatures.MagicPillar.Name, Creatures.MagicPillar }, { Creatures.Magicthrower.Name, Creatures.Magicthrower }, { Creatures.Mahrdis.Name, Creatures.Mahrdis }, { Creatures.Mammoth.Name, Creatures.Mammoth }, { Creatures.ManintheCave.Name, Creatures.ManintheCave }, { Creatures.Marid.Name, Creatures.Marid }, { Creatures.Marziel.Name, Creatures.Marziel }, { Creatures.Massacre.Name, Creatures.Massacre }, { Creatures.MassiveEarthElemental.Name, Creatures.MassiveEarthElemental }, { Creatures.MassiveEnergyElemental.Name, Creatures.MassiveEnergyElemental }, { Creatures.MassiveFireElemental.Name, Creatures.MassiveFireElemental }, { Creatures.MassiveWaterElemental.Name, Creatures.MassiveWaterElemental }, { Creatures.MechanicalFighter.Name, Creatures.MechanicalFighter }, { Creatures.Medusa.Name, Creatures.Medusa }, { Creatures.Menace.Name, Creatures.Menace }, { Creatures.Mephiles.Name, Creatures.Mephiles }, { Creatures.MercuryBlob.Name, Creatures.MercuryBlob }, { Creatures.MerikhtheSlaughterer.Name, Creatures.MerikhtheSlaughterer }, { Creatures.Merlkin.Name, Creatures.Merlkin }, { Creatures.MerlkinAntiBotter.Name, Creatures.MerlkinAntiBotter }, { Creatures.MidnightSpawn.Name, Creatures.MidnightSpawn }, { Creatures.MidnightWarrior.Name, Creatures.MidnightWarrior }, { Creatures.Mimic.Name, Creatures.Mimic }, { Creatures.Minishabaal.Name, Creatures.Minishabaal }, { Creatures.Minotaur.Name, Creatures.Minotaur }, { Creatures.MinotaurArcher.Name, Creatures.MinotaurArcher }, { Creatures.MinotaurGuard.Name, Creatures.MinotaurGuard }, { Creatures.MinotaurMage.Name, Creatures.MinotaurMage }, { Creatures.Monk.Name, Creatures.Monk }, { Creatures.Monstor.Name, Creatures.Monstor }, { Creatures.Mooh.Name, Creatures.Mooh }, { Creatures.Morgaroth.Name, Creatures.Morgaroth }, { Creatures.Morguthis.Name, Creatures.Morguthis }, { Creatures.MoriktheGladiator.Name, Creatures.MoriktheGladiator }, { Creatures.MrPunish.Name, Creatures.MrPunish }, { Creatures.MuddyEarthElemental.Name, Creatures.MuddyEarthElemental }, { Creatures.Mummy.Name, Creatures.Mummy }, { Creatures.Munster.Name, Creatures.Munster }, { Creatures.MutatedBat.Name, Creatures.MutatedBat }, { Creatures.MutatedHuman.Name, Creatures.MutatedHuman }, { Creatures.MutatedRat.Name, Creatures.MutatedRat }, { Creatures.MutatedTiger.Name, Creatures.MutatedTiger }, { Creatures.Necromancer.Name, Creatures.Necromancer }, { Creatures.Necropharus.Name, Creatures.Necropharus }, { Creatures.Nightmare.Name, Creatures.Nightmare }, { Creatures.NightmareScion.Name, Creatures.NightmareScion }, { Creatures.Nightslayer.Name, Creatures.Nightslayer }, { Creatures.Nightstalker.Name, Creatures.Nightstalker }, { Creatures.Nomad.Name, Creatures.Nomad }, { Creatures.NorgleGlacierbeard.Name, Creatures.NorgleGlacierbeard }, { Creatures.NoviceoftheCult.Name, Creatures.NoviceoftheCult }, { Creatures.Omruc.Name, Creatures.Omruc }, { Creatures.Orc.Name, Creatures.Orc }, { Creatures.OrcBerserker.Name, Creatures.OrcBerserker }, { Creatures.OrcLeader.Name, Creatures.OrcLeader }, { Creatures.OrcMarauder.Name, Creatures.OrcMarauder }, { Creatures.OrcRider.Name, Creatures.OrcRider }, { Creatures.OrcShaman.Name, Creatures.OrcShaman }, { Creatures.OrcSpearman.Name, Creatures.OrcSpearman }, { Creatures.OrcWarlord.Name, Creatures.OrcWarlord }, { Creatures.OrcWarrior.Name, Creatures.OrcWarrior }, { Creatures.OrchidFrog.Name, Creatures.OrchidFrog }, { Creatures.OrcustheCruel.Name, Creatures.OrcustheCruel }, { Creatures.Orshabaal.Name, Creatures.Orshabaal }, { Creatures.OverchargedEnergyElement.Name, Creatures.OverchargedEnergyElement }, { Creatures.Panda.Name, Creatures.Panda }, { Creatures.Parrot.Name, Creatures.Parrot }, { Creatures.Penguin.Name, Creatures.Penguin }, { Creatures.Phantasm.Name, Creatures.Phantasm }, { Creatures.Pig.Name, Creatures.Pig }, { Creatures.Pillar.Name, Creatures.Pillar }, { Creatures.PirateBuccaneer.Name, Creatures.PirateBuccaneer }, { Creatures.PirateCorsair.Name, Creatures.PirateCorsair }, { Creatures.PirateCutthroat.Name, Creatures.PirateCutthroat }, { Creatures.PirateGhost.Name, Creatures.PirateGhost }, { Creatures.PirateMarauder.Name, Creatures.PirateMarauder }, { Creatures.PirateSkeleton.Name, Creatures.PirateSkeleton }, { Creatures.Plaguesmith.Name, Creatures.Plaguesmith }, { Creatures.Plaguethrower.Name, Creatures.Plaguethrower }, { Creatures.Poacher.Name, Creatures.Poacher }, { Creatures.PoisonSpider.Name, Creatures.PoisonSpider }, { Creatures.PolarBear.Name, Creatures.PolarBear }, { Creatures.Priestess.Name, Creatures.Priestess }, { Creatures.Primitive.Name, Creatures.Primitive }, { Creatures.PythiustheRotten.Name, Creatures.PythiustheRotten }, { Creatures.QuaraConstrictor.Name, Creatures.QuaraConstrictor }, { Creatures.QuaraConstrictorScout.Name, Creatures.QuaraConstrictorScout }, { Creatures.QuaraHydromancer.Name, Creatures.QuaraHydromancer }, { Creatures.QuaraHydromancerScout.Name, Creatures.QuaraHydromancerScout }, { Creatures.QuaraMantassin.Name, Creatures.QuaraMantassin }, { Creatures.QuaraMantassinScout.Name, Creatures.QuaraMantassinScout }, { Creatures.QuaraPincher.Name, Creatures.QuaraPincher }, { Creatures.QuaraPincherScout.Name, Creatures.QuaraPincherScout }, { Creatures.QuaraPredator.Name, Creatures.QuaraPredator }, { Creatures.QuaraPredatorScout.Name, Creatures.QuaraPredatorScout }, { Creatures.Rabbit.Name, Creatures.Rabbit }, { Creatures.Rahemos.Name, Creatures.Rahemos }, { Creatures.Rat.Name, Creatures.Rat }, { Creatures.RenegadeOrc.Name, Creatures.RenegadeOrc }, { Creatures.RiftBrood.Name, Creatures.RiftBrood }, { Creatures.RiftLord.Name, Creatures.RiftLord }, { Creatures.RiftPhantom.Name, Creatures.RiftPhantom }, { Creatures.RiftScythe.Name, Creatures.RiftScythe }, { Creatures.RiftWorm.Name, Creatures.RiftWorm }, { Creatures.RoaringWaterElemental.Name, Creatures.RoaringWaterElemental }, { Creatures.Rocko.Name, Creatures.Rocko }, { Creatures.Rocky.Name, Creatures.Rocky }, { Creatures.RontheRipper.Name, Creatures.RontheRipper }, { Creatures.RottietheRotworm.Name, Creatures.RottietheRotworm }, { Creatures.Rotworm.Name, Creatures.Rotworm }, { Creatures.RotwormQueen.Name, Creatures.RotwormQueen }, { Creatures.RukorZad.Name, Creatures.RukorZad }, { Creatures.Sandcrawler.Name, Creatures.Sandcrawler }, { Creatures.Scarab.Name, Creatures.Scarab }, { Creatures.Scorpion.Name, Creatures.Scorpion }, { Creatures.SeaSerpent.Name, Creatures.SeaSerpent }, { Creatures.Seagull.Name, Creatures.Seagull }, { Creatures.SerpentSpawn.Name, Creatures.SerpentSpawn }, { Creatures.ServantGolem.Name, Creatures.ServantGolem }, { Creatures.ShadowHound.Name, Creatures.ShadowHound }, { Creatures.ShadowofBoreth.Name, Creatures.ShadowofBoreth }, { Creatures.ShadowofLersatio.Name, Creatures.ShadowofLersatio }, { Creatures.ShadowofMarziel.Name, Creatures.ShadowofMarziel }, { Creatures.ShardofCorruption.Name, Creatures.ShardofCorruption }, { Creatures.Shardhead.Name, Creatures.Shardhead }, { Creatures.Sharptooth.Name, Creatures.Sharptooth }, { Creatures.Sheep.Name, Creatures.Sheep }, { Creatures.Shredderthrower.Name, Creatures.Shredderthrower }, { Creatures.Sibang.Name, Creatures.Sibang }, { Creatures.SilverRabbit.Name, Creatures.SilverRabbit }, { Creatures.SirValorcrest.Name, Creatures.SirValorcrest }, { Creatures.Skeleton.Name, Creatures.Skeleton }, { Creatures.SkeletonWarrior.Name, Creatures.SkeletonWarrior }, { Creatures.Skunk.Name, Creatures.Skunk }, { Creatures.SlickWaterElemental.Name, Creatures.SlickWaterElemental }, { Creatures.Slim.Name, Creatures.Slim }, { Creatures.Slime.Name, Creatures.Slime }, { Creatures.Smuggler.Name, Creatures.Smuggler }, { Creatures.SmugglerBaronSilvertoe.Name, Creatures.SmugglerBaronSilvertoe }, { Creatures.Snake.Name, Creatures.Snake }, { Creatures.SonofVerminor.Name, Creatures.SonofVerminor }, { Creatures.SpawnofDespair.Name, Creatures.SpawnofDespair }, { Creatures.Spectre.Name, Creatures.Spectre }, { Creatures.Spider.Name, Creatures.Spider }, { Creatures.SpiritofEarth.Name, Creatures.SpiritofEarth }, { Creatures.SpiritofFire.Name, Creatures.SpiritofFire }, { Creatures.SpiritofLight.Name, Creatures.SpiritofLight }, { Creatures.SpiritofWater.Name, Creatures.SpiritofWater }, { Creatures.SpitNettle.Name, Creatures.SpitNettle }, { Creatures.Splasher.Name, Creatures.Splasher }, { Creatures.Squirrel.Name, Creatures.Squirrel }, { Creatures.Stalker.Name, Creatures.Stalker }, { Creatures.StoneGolem.Name, Creatures.StoneGolem }, { Creatures.Stonecracker.Name, Creatures.Stonecracker }, { Creatures.SvorenTheMad.Name, Creatures.SvorenTheMad }, { Creatures.SwampTroll.Name, Creatures.SwampTroll }, { Creatures.Tarantula.Name, Creatures.Tarantula }, { Creatures.TargetDummy.Name, Creatures.TargetDummy }, { Creatures.Terramite.Name, Creatures.Terramite }, { Creatures.TerrorBird.Name, Creatures.TerrorBird }, { Creatures.Thalas.Name, Creatures.Thalas }, { Creatures.TheAbomination.Name, Creatures.TheAbomination }, { Creatures.TheAxeorcist.Name, Creatures.TheAxeorcist }, { Creatures.TheBigBadOne.Name, Creatures.TheBigBadOne }, { Creatures.TheBlightfather.Name, Creatures.TheBlightfather }, { Creatures.TheBloodtusk.Name, Creatures.TheBloodtusk }, { Creatures.TheCollector.Name, Creatures.TheCollector }, { Creatures.TheCount.Name, Creatures.TheCount }, { Creatures.TheDarkDancer.Name, Creatures.TheDarkDancer }, { Creatures.TheDreadorian.Name, Creatures.TheDreadorian }, { Creatures.TheEvilEye.Name, Creatures.TheEvilEye }, { Creatures.TheFrogPrince.Name, Creatures.TheFrogPrince }, { Creatures.TheHag.Name, Creatures.TheHag }, { Creatures.TheHairyOne.Name, Creatures.TheHairyOne }, { Creatures.TheHalloweenHare.Name, Creatures.TheHalloweenHare }, { Creatures.TheHandmaiden.Name, Creatures.TheHandmaiden }, { Creatures.TheHornedFox.Name, Creatures.TheHornedFox }, { Creatures.TheImperor.Name, Creatures.TheImperor }, { Creatures.TheMany.Name, Creatures.TheMany }, { Creatures.TheMaskedMarauder.Name, Creatures.TheMaskedMarauder }, { Creatures.TheMutatedPumpkin.Name, Creatures.TheMutatedPumpkin }, { Creatures.TheNoxiousSpawn.Name, Creatures.TheNoxiousSpawn }, { Creatures.TheObliverator.Name, Creatures.TheObliverator }, { Creatures.TheOldWhopper.Name, Creatures.TheOldWhopper }, { Creatures.TheOldWidow.Name, Creatures.TheOldWidow }, { Creatures.ThePitLord.Name, Creatures.ThePitLord }, { Creatures.ThePlasmother.Name, Creatures.ThePlasmother }, { Creatures.TheRuthlessHerald.Name, Creatures.TheRuthlessHerald }, { Creatures.TheSnapper.Name, Creatures.TheSnapper }, { Creatures.TheVoiceofRuin.Name, Creatures.TheVoiceofRuin }, { Creatures.TheWeakenedCount.Name, Creatures.TheWeakenedCount }, { Creatures.Thief.Name, Creatures.Thief }, { Creatures.ThievingSquirrel.Name, Creatures.ThievingSquirrel }, { Creatures.ThornbackTortoise.Name, Creatures.ThornbackTortoise }, { Creatures.Thul.Name, Creatures.Thul }, { Creatures.TibiaBug.Name, Creatures.TibiaBug }, { Creatures.Tiger.Name, Creatures.Tiger }, { Creatures.TiquandasRevenge.Name, Creatures.TiquandasRevenge }, { Creatures.Tirecz.Name, Creatures.Tirecz }, { Creatures.Toad.Name, Creatures.Toad }, { Creatures.TormentedGhost.Name, Creatures.TormentedGhost }, { Creatures.Tortoise.Name, Creatures.Tortoise }, { Creatures.TortoiseAntiBotter.Name, Creatures.TortoiseAntiBotter }, { Creatures.Tremorak.Name, Creatures.Tremorak }, { Creatures.Troll.Name, Creatures.Troll }, { Creatures.TrollChampion.Name, Creatures.TrollChampion }, { Creatures.TrollLegionnaire.Name, Creatures.TrollLegionnaire }, { Creatures.UndeadDragon.Name, Creatures.UndeadDragon }, { Creatures.UndeadGladiator.Name, Creatures.UndeadGladiator }, { Creatures.UndeadJester.Name, Creatures.UndeadJester }, { Creatures.UndeadMineWorker.Name, Creatures.UndeadMineWorker }, { Creatures.UndeadMinion.Name, Creatures.UndeadMinion }, { Creatures.UndeadProspector.Name, Creatures.UndeadProspector }, { Creatures.Ungreez.Name, Creatures.Ungreez }, { Creatures.Ushuriel.Name, Creatures.Ushuriel }, }; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Tests { public partial class BooleanTests { [Fact] public void TrueString_Get_ReturnsTrue() { Assert.Equal("True", bool.TrueString); } [Fact] public void FalseString_Get_ReturnsFalse() { Assert.Equal("False", bool.FalseString); } public static IEnumerable<object[]> Parse_Valid_TestData() { yield return new object[] { "True", true }; yield return new object[] { "true", true }; yield return new object[] { "TRUE", true }; yield return new object[] { "tRuE", true }; yield return new object[] { " True ", true }; yield return new object[] { "True\0", true }; yield return new object[] { " \0 \0 True \0 ", true }; yield return new object[] { "False", false }; yield return new object[] { "false", false }; yield return new object[] { "FALSE", false }; yield return new object[] { "fAlSe", false }; yield return new object[] { "False ", false }; yield return new object[] { "False\0", false }; yield return new object[] { " False \0\0\0 ", false }; } [Theory] [MemberData(nameof(Parse_Valid_TestData))] public void Parse_ValidValue_ReturnsExpected(string value, bool expected) { Assert.True(bool.TryParse(value, out bool result)); Assert.Equal(expected, result); Assert.Equal(expected, bool.Parse(value)); } public static IEnumerable<object[]> Parse_Invalid_TestData() { yield return new object[] { null, typeof(ArgumentNullException) }; yield return new object[] { "", typeof(FormatException) }; yield return new object[] { " ", typeof(FormatException) }; yield return new object[] { "Garbage", typeof(FormatException) }; yield return new object[] { "True\0Garbage", typeof(FormatException) }; yield return new object[] { "True\0True", typeof(FormatException) }; yield return new object[] { "True True", typeof(FormatException) }; yield return new object[] { "True False", typeof(FormatException) }; yield return new object[] { "False True", typeof(FormatException) }; yield return new object[] { "Fa lse", typeof(FormatException) }; yield return new object[] { "T", typeof(FormatException) }; yield return new object[] { "0", typeof(FormatException) }; yield return new object[] { "1", typeof(FormatException) }; } [Theory] [MemberData(nameof(Parse_Invalid_TestData))] public void Parse_InvalidValue_ThrowsException(string value, Type exceptionType) { Assert.Throws(exceptionType, () => bool.Parse(value)); Assert.False(bool.TryParse(value, out bool result)); Assert.False(result); } [Theory] [InlineData(true, "True")] [InlineData(false, "False")] public void ToString_Invoke_ReturnsExpected(bool value, string expected) { Assert.Equal(expected, value.ToString()); } [Theory] [InlineData(true, true, 0)] [InlineData(true, false, 1)] [InlineData(true, null, 1)] [InlineData(false, false, 0)] [InlineData(false, true, -1)] [InlineData(false, null, 1)] public void CompareTo_Other_ReturnsExpected(bool b, object obj, int expected) { if (obj is bool boolValue) { Assert.Equal(expected, Math.Sign(b.CompareTo(boolValue))); } Assert.Equal(expected, Math.Sign(b.CompareTo(obj))); } [Theory] [InlineData(true, 1)] [InlineData(true, "true")] [InlineData(false, 0)] [InlineData(false, "false")] public void CompareTo_ObjectNotBool_ThrowsArgumentException(bool b, object obj) { AssertExtensions.Throws<ArgumentException>(null, () => b.CompareTo(obj)); } [Theory] [InlineData(true, true, true)] [InlineData(true, false, false)] [InlineData(true, "1", false)] [InlineData(true, "True", false)] [InlineData(true, null, false)] [InlineData(false, false, true)] [InlineData(false, true, false)] [InlineData(false, "0", false)] [InlineData(false, "False", false)] [InlineData(false, null, false)] public void Equals_Other_ReturnsExpected(bool b1, object obj, bool expected) { if (obj is bool boolValue) { Assert.Equal(expected, b1.Equals(boolValue)); Assert.Equal(expected, b1.GetHashCode().Equals(obj.GetHashCode())); } Assert.Equal(expected, b1.Equals(obj)); } [Theory] [InlineData(true, 1)] [InlineData(false, 0)] public void GetHashCode_Invoke_ReturnsExpected(bool value, int expected) { Assert.Equal(expected, value.GetHashCode()); } [Fact] public void GetTypeCode_Invoke_ReturnsBoolean() { Assert.Equal(TypeCode.Boolean, true.GetTypeCode()); } public static IEnumerable<object[]> Parse_ValidWithOffsetCount_TestData() { foreach (object[] inputs in Parse_Valid_TestData()) { yield return new object[] { inputs[0], 0, ((string)inputs[0]).Length, inputs[1] }; } yield return new object[] { " \0 \0 TrueFalse \0 ", 6, 4, true }; yield return new object[] { " \0 \0 TrueFalse \0 ", 10, 5, false }; } [Theory] [MemberData(nameof(Parse_ValidWithOffsetCount_TestData))] public static void Parse_Span_Valid(string value, int offset, int count, bool expected) { Assert.Equal(expected, bool.Parse(value.AsSpan(offset, count))); Assert.True(bool.TryParse(value.AsSpan(offset, count), out bool result)); Assert.Equal(expected, result); } [Theory] [MemberData(nameof(Parse_Invalid_TestData))] public static void Parse_Span_Invalid(string value, Type exceptionType) { if (value != null) { Assert.Throws(exceptionType, () => bool.Parse(value.AsSpan())); Assert.False(bool.TryParse(value.AsSpan(), out bool result)); Assert.False(result); } } [Theory] [InlineData(true, "True")] [InlineData(false, "False")] public static void TryFormat(bool i, string expected) { char[] actual; int charsWritten; // Just right actual = new char[expected.Length]; Assert.True(i.TryFormat(actual.AsSpan(), out charsWritten)); Assert.Equal(expected.Length, charsWritten); Assert.Equal(expected, new string(actual)); // Longer than needed actual = new char[expected.Length + 1]; Assert.True(i.TryFormat(actual.AsSpan(), out charsWritten)); Assert.Equal(expected.Length, charsWritten); Assert.Equal(expected, new string(actual, 0, charsWritten)); // Too short if (expected.Length > 0) { actual = new char[expected.Length - 1]; Assert.False(i.TryFormat(actual.AsSpan(), out charsWritten)); Assert.Equal(0, charsWritten); } } } }
// // Copyright 2011-2013, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Android.App; using Android.Content; using Android.Database; using Android.OS; using Android.Provider; using Environment = Android.OS.Environment; using FileNotFoundException = Java.IO.FileNotFoundException; using Uri = Android.Net.Uri; namespace Xamarin.Media { [Activity] internal class MediaPickerActivity : Activity { internal const String ExtraAction = "action"; internal const String ExtraId = "id"; internal const String ExtraLocation = "location"; internal const String ExtraPath = "path"; internal const String ExtraTasked = "tasked"; internal const String ExtraType = "type"; private String action; private String description; private Int32 id; private Boolean isPhoto; /// <summary> /// The user's destination path. /// </summary> private Uri path; private VideoQuality quality; private Int32 seconds; private Boolean tasked; private String title; private String type; internal static event EventHandler<MediaPickedEventArgs> MediaPicked; protected override void OnActivityResult( Int32 requestCode, Result resultCode, Intent data ) { base.OnActivityResult( requestCode, resultCode, data ); if(tasked) { Task<MediaPickedEventArgs> future; if(resultCode == Result.Canceled) { future = TaskFromResult( new MediaPickedEventArgs( requestCode, isCanceled: true ) ); } else { future = GetMediaFileAsync( this, requestCode, action, isPhoto, ref path, (data != null) ? data.Data : null ); } Finish(); future.ContinueWith( t => OnMediaPicked( t.Result ) ); } else { if(resultCode == Result.Canceled) { SetResult( Result.Canceled ); } else { Intent resultData = new Intent(); resultData.PutExtra( MediaFile.ExtraName, (data != null) ? data.Data : null ); resultData.PutExtra( "path", path ); resultData.PutExtra( "isPhoto", isPhoto ); resultData.PutExtra( "action", action ); SetResult( Result.Ok, resultData ); } Finish(); } } protected override void OnCreate( Bundle savedInstanceState ) { base.OnCreate( savedInstanceState ); Bundle b = (savedInstanceState ?? Intent.Extras); Boolean ran = b.GetBoolean( "ran", defaultValue: false ); title = b.GetString( MediaStore.MediaColumns.Title ); description = b.GetString( MediaStore.Images.ImageColumns.Description ); tasked = b.GetBoolean( ExtraTasked ); id = b.GetInt( ExtraId, 0 ); type = b.GetString( ExtraType ); if(type == "image/*") { isPhoto = true; } action = b.GetString( ExtraAction ); Intent pickIntent = null; try { pickIntent = new Intent( action ); if(action == Intent.ActionPick) { pickIntent.SetType( type ); } else { if(!isPhoto) { seconds = b.GetInt( MediaStore.ExtraDurationLimit, 0 ); if(seconds != 0) { pickIntent.PutExtra( MediaStore.ExtraDurationLimit, seconds ); } } quality = (VideoQuality)b.GetInt( MediaStore.ExtraVideoQuality, (int)VideoQuality.High ); pickIntent.PutExtra( MediaStore.ExtraVideoQuality, GetVideoQuality( quality ) ); if(!ran) { path = GetOutputMediaFile( this, b.GetString( ExtraPath ), title, isPhoto ); Touch(); pickIntent.PutExtra( MediaStore.ExtraOutput, path ); } else { path = Uri.Parse( b.GetString( ExtraPath ) ); } } if(!ran) { StartActivityForResult( pickIntent, id ); } } catch(Exception ex) { OnMediaPicked( new MediaPickedEventArgs( id, ex ) ); } finally { if(pickIntent != null) { pickIntent.Dispose(); } } } protected override void OnSaveInstanceState( Bundle outState ) { outState.PutBoolean( "ran", true ); outState.PutString( MediaStore.MediaColumns.Title, title ); outState.PutString( MediaStore.Images.ImageColumns.Description, description ); outState.PutInt( ExtraId, id ); outState.PutString( ExtraType, type ); outState.PutString( ExtraAction, action ); outState.PutInt( MediaStore.ExtraDurationLimit, seconds ); outState.PutInt( MediaStore.ExtraVideoQuality, (int)quality ); outState.PutBoolean( ExtraTasked, tasked ); if(path != null) { outState.PutString( ExtraPath, path.Path ); } base.OnSaveInstanceState( outState ); } private void Touch() { if(path.Scheme != "file") { return; } File.Create( GetLocalPath( path ) ).Close(); } internal static Task<Tuple<string, bool>> GetFileForUriAsync( Context context, Uri uri, bool isPhoto ) { var tcs = new TaskCompletionSource<Tuple<string, bool>>(); if(uri.Scheme == "file") { tcs.SetResult( new Tuple<string, bool>( new System.Uri( uri.ToString() ).LocalPath, false ) ); } else if(uri.Scheme == "content") { Task.Factory.StartNew( () => { ICursor cursor = null; try { cursor = context.ContentResolver.Query( uri, null, null, null, null ); if(cursor == null || !cursor.MoveToNext()) { tcs.SetResult( new Tuple<string, bool>( null, false ) ); } else { int column = cursor.GetColumnIndex( MediaStore.MediaColumns.Data ); string contentPath = null; if(column != -1) { contentPath = cursor.GetString( column ); } bool copied = false; // If they don't follow the "rules", try to copy the file locally if(contentPath == null || !contentPath.StartsWith( "file" )) { copied = true; Uri outputPath = GetOutputMediaFile( context, "temp", null, isPhoto ); try { using(Stream input = context.ContentResolver.OpenInputStream( uri )) using(Stream output = File.Create( outputPath.Path )) input.CopyTo( output ); contentPath = outputPath.Path; } catch(FileNotFoundException) { // If there's no data associated with the uri, we don't know // how to open this. contentPath will be null which will trigger // MediaFileNotFoundException. } } tcs.SetResult( new Tuple<string, bool>( contentPath, copied ) ); } } finally { if(cursor != null) { cursor.Close(); cursor.Dispose(); } } }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default ); } else { tcs.SetResult( new Tuple<string, bool>( null, false ) ); } return tcs.Task; } internal static Task<MediaPickedEventArgs> GetMediaFileAsync( Context context, int requestCode, string action, bool isPhoto, ref Uri path, Uri data ) { Task<Tuple<string, bool>> pathFuture; string originalPath = null; if(action != Intent.ActionPick) { originalPath = path.Path; // Not all camera apps respect EXTRA_OUTPUT, some will instead // return a content or file uri from data. if(data != null && data.Path != originalPath) { originalPath = data.ToString(); string currentPath = path.Path; pathFuture = TryMoveFileAsync( context, data, path, isPhoto ) .ContinueWith( t => new Tuple<string, bool>( t.Result ? currentPath : null, false ) ); } else { pathFuture = TaskFromResult( new Tuple<string, bool>( path.Path, false ) ); } } else if(data != null) { originalPath = data.ToString(); path = data; pathFuture = GetFileForUriAsync( context, path, isPhoto ); } else { pathFuture = TaskFromResult<Tuple<string, bool>>( null ); } return pathFuture.ContinueWith( t => { string resultPath = t.Result.Item1; if(resultPath != null && File.Exists( t.Result.Item1 )) { var mf = new MediaFile( resultPath, deletePathOnDispose: t.Result.Item2 ); return new MediaPickedEventArgs( requestCode, false, mf ); } else { return new MediaPickedEventArgs( requestCode, new MediaFileNotFoundException( originalPath ) ); } } ); } private static string GetLocalPath( Uri uri ) { return new System.Uri( uri.ToString() ).LocalPath; } private static Uri GetOutputMediaFile( Context context, string subdir, string name, bool isPhoto ) { subdir = subdir ?? String.Empty; if(String.IsNullOrWhiteSpace( name )) { string timestamp = DateTime.Now.ToString( "yyyyMMdd_HHmmss" ); if(isPhoto) { name = "IMG_" + timestamp + ".jpg"; } else { name = "VID_" + timestamp + ".mp4"; } } string mediaType = (isPhoto) ? Environment.DirectoryPictures : Environment.DirectoryMovies; using(Java.IO.File mediaStorageDir = new Java.IO.File( context.GetExternalFilesDir( mediaType ), subdir )) { if(!mediaStorageDir.Exists()) { if(!mediaStorageDir.Mkdirs()) { throw new IOException( "Couldn't create directory, have you added the WRITE_EXTERNAL_STORAGE permission?" ); } // Ensure this media doesn't show up in gallery apps using(Java.IO.File nomedia = new Java.IO.File( mediaStorageDir, ".nomedia" )) nomedia.CreateNewFile(); } return Uri.FromFile( new Java.IO.File( GetUniquePath( mediaStorageDir.Path, name, isPhoto ) ) ); } } private static string GetUniquePath( string folder, string name, bool isPhoto ) { string ext = Path.GetExtension( name ); if(ext == String.Empty) { ext = ((isPhoto) ? ".jpg" : ".mp4"); } name = Path.GetFileNameWithoutExtension( name ); string nname = name + ext; int i = 1; while(File.Exists( Path.Combine( folder, nname ) )) { nname = name + "_" + (i++) + ext; } return Path.Combine( folder, nname ); } private static int GetVideoQuality( VideoQuality videoQuality ) { switch(videoQuality) { case VideoQuality.Medium: case VideoQuality.High: return 1; default: return 0; } } private static void OnMediaPicked( MediaPickedEventArgs e ) { var picked = MediaPicked; if(picked != null) { picked( null, e ); } } private static Task<T> TaskFromResult<T>( T result ) { var tcs = new TaskCompletionSource<T>(); tcs.SetResult( result ); return tcs.Task; } private static Task<bool> TryMoveFileAsync( Context context, Uri url, Uri path, bool isPhoto ) { string moveTo = GetLocalPath( path ); return GetFileForUriAsync( context, url, isPhoto ).ContinueWith( t => { if(t.Result.Item1 == null) { return false; } File.Delete( moveTo ); File.Move( t.Result.Item1, moveTo ); if(url.Scheme == "content") { context.ContentResolver.Delete( url, null, null ); } return true; }, TaskScheduler.Default ); } } internal class MediaPickedEventArgs : EventArgs { public MediaPickedEventArgs( int id, Exception error ) { if(error == null) { throw new ArgumentNullException( "error" ); } RequestId = id; Error = error; } public MediaPickedEventArgs( int id, bool isCanceled, MediaFile media = null ) { RequestId = id; IsCanceled = isCanceled; if(!IsCanceled && media == null) { throw new ArgumentNullException( "media" ); } Media = media; } public Exception Error { get; private set; } public bool IsCanceled { get; private set; } public MediaFile Media { get; private set; } public int RequestId { get; private set; } public Task<MediaFile> ToTask() { var tcs = new TaskCompletionSource<MediaFile>(); if(IsCanceled) { tcs.SetCanceled(); } else if(Error != null) { tcs.SetException( Error ); } else { tcs.SetResult( Media ); } return tcs.Task; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; using System.Web.Configuration; using System.Web.Hosting; using System.Web.Routing; using System.Web.Security; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Security; namespace Umbraco.Core.Configuration { //NOTE: Do not expose this class ever until we cleanup all configuration including removal of static classes, etc... // we have this two tasks logged: // http://issues.umbraco.org/issue/U4-58 // http://issues.umbraco.org/issue/U4-115 //TODO: Replace checking for if the app settings exist and returning an empty string, instead return the defaults! /// <summary> /// The GlobalSettings Class contains general settings information for the entire Umbraco instance based on information from web.config appsettings /// </summary> internal class GlobalSettings { #region Private static fields private static Version _version; private static readonly object Locker = new object(); //make this volatile so that we can ensure thread safety with a double check lock private static volatile string _reservedUrlsCache; private static string _reservedPathsCache; private static HashSet<string> _reservedList = new HashSet<string>(); private static string _reservedPaths; private static string _reservedUrls; //ensure the built on (non-changeable) reserved paths are there at all times private const string StaticReservedPaths = "~/app_plugins/,~/install/,"; private const string StaticReservedUrls = "~/config/splashes/booting.aspx,~/config/splashes/noNodes.aspx,~/VSEnterpriseHelper.axd,"; #endregion /// <summary> /// Used in unit testing to reset all config items that were set with property setters (i.e. did not come from config) /// </summary> private static void ResetInternal() { _reservedUrlsCache = null; _reservedPaths = null; _reservedUrls = null; } /// <summary> /// Resets settings that were set programmatically, to their initial values. /// </summary> /// <remarks>To be used in unit tests.</remarks> internal static void Reset() { ResetInternal(); } /// <summary> /// Gets the reserved urls from web.config. /// </summary> /// <value>The reserved urls.</value> public static string ReservedUrls { get { if (_reservedUrls == null) { var urls = ConfigurationManager.AppSettings.ContainsKey("umbracoReservedUrls") ? ConfigurationManager.AppSettings["umbracoReservedUrls"] : string.Empty; //ensure the built on (non-changeable) reserved paths are there at all times _reservedUrls = StaticReservedUrls + urls; } return _reservedUrls; } internal set { _reservedUrls = value; } } /// <summary> /// Gets the reserved paths from web.config /// </summary> /// <value>The reserved paths.</value> public static string ReservedPaths { get { if (_reservedPaths == null) { var reservedPaths = StaticReservedPaths; //always add the umbraco path to the list if (ConfigurationManager.AppSettings.ContainsKey("umbracoPath") && !ConfigurationManager.AppSettings["umbracoPath"].IsNullOrWhiteSpace()) { reservedPaths += ConfigurationManager.AppSettings["umbracoPath"].EnsureEndsWith(','); } var allPaths = ConfigurationManager.AppSettings.ContainsKey("umbracoReservedPaths") ? ConfigurationManager.AppSettings["umbracoReservedPaths"] : string.Empty; _reservedPaths = reservedPaths + allPaths; } return _reservedPaths; } internal set { _reservedPaths = value; } } /// <summary> /// Gets the name of the content XML file. /// </summary> /// <value>The content XML.</value> /// <remarks> /// Defaults to ~/App_Data/umbraco.config /// </remarks> public static string ContentXmlFile { get { return ConfigurationManager.AppSettings.ContainsKey("umbracoContentXML") ? ConfigurationManager.AppSettings["umbracoContentXML"] : "~/App_Data/umbraco.config"; } } /// <summary> /// Gets the path to the storage directory (/data by default). /// </summary> /// <value>The storage directory.</value> public static string StorageDirectory { get { return ConfigurationManager.AppSettings.ContainsKey("umbracoStorageDirectory") ? ConfigurationManager.AppSettings["umbracoStorageDirectory"] : "~/App_Data"; } } /// <summary> /// Gets the path to umbraco's root directory (/umbraco by default). /// </summary> /// <value>The path.</value> public static string Path { get { return ConfigurationManager.AppSettings.ContainsKey("umbracoPath") ? IOHelper.ResolveUrl(ConfigurationManager.AppSettings["umbracoPath"]) : string.Empty; } } /// <summary> /// This returns the string of the MVC Area route. /// </summary> /// <remarks> /// THIS IS TEMPORARY AND SHOULD BE REMOVED WHEN WE MIGRATE/UPDATE THE CONFIG SETTINGS TO BE A REAL CONFIG SECTION /// AND SHOULD PROBABLY BE HANDLED IN A MORE ROBUST WAY. /// /// This will return the MVC area that we will route all custom routes through like surface controllers, etc... /// We will use the 'Path' (default ~/umbraco) to create it but since it cannot contain '/' and people may specify a path of ~/asdf/asdf/admin /// we will convert the '/' to '-' and use that as the path. its a bit lame but will work. /// /// We also make sure that the virtual directory (SystemDirectories.Root) is stripped off first, otherwise we'd end up with something /// like "MyVirtualDirectory-Umbraco" instead of just "Umbraco". /// </remarks> public static string UmbracoMvcArea { get { if (Path.IsNullOrWhiteSpace()) { throw new InvalidOperationException("Cannot create an MVC Area path without the umbracoPath specified"); } var path = Path; if (path.StartsWith(SystemDirectories.Root)) // beware of TrimStart, see U4-2518 path = path.Substring(SystemDirectories.Root.Length); return path.TrimStart('~').TrimStart('/').Replace('/', '-').Trim().ToLower(); } } /// <summary> /// Gets the path to umbraco's client directory (/umbraco_client by default). /// This is a relative path to the Umbraco Path as it always must exist beside the 'umbraco' /// folder since the CSS paths to images depend on it. /// </summary> /// <value>The path.</value> public static string ClientPath { get { return Path + "/../umbraco_client"; } } /// <summary> /// Gets the database connection string /// </summary> /// <value>The database connection string.</value> [Obsolete("Use System.Configuration.ConfigurationManager.ConnectionStrings[\"umbracoDbDSN\"] instead")] public static string DbDsn { get { var settings = ConfigurationManager.ConnectionStrings[UmbracoConnectionName]; var connectionString = string.Empty; if (settings != null) { connectionString = settings.ConnectionString; // The SqlCe connectionString is formatted slightly differently, so we need to update it if (settings.ProviderName.Contains("SqlServerCe")) connectionString = string.Format("datalayer=SQLCE4Umbraco.SqlCEHelper,SQLCE4Umbraco;{0}", connectionString); } return connectionString; } set { if (DbDsn != value) { if (value.ToLower().Contains("SQLCE4Umbraco.SqlCEHelper".ToLower())) { ApplicationContext.Current.DatabaseContext.ConfigureEmbeddedDatabaseConnection(); } else { ApplicationContext.Current.DatabaseContext.ConfigureDatabaseConnection(value); } } } } //TODO: Move these to constants! public const string UmbracoConnectionName = "umbracoDbDSN"; public const string UmbracoMigrationName = "Umbraco"; /// <summary> /// Gets or sets the configuration status. This will return the version number of the currently installed umbraco instance. /// </summary> /// <value>The configuration status.</value> public static string ConfigurationStatus { get { return ConfigurationManager.AppSettings.ContainsKey("umbracoConfigurationStatus") ? ConfigurationManager.AppSettings["umbracoConfigurationStatus"] : string.Empty; } set { SaveSetting("umbracoConfigurationStatus", value); } } /// <summary> /// Gets or sets the Umbraco members membership providers' useLegacyEncoding state. This will return a boolean /// </summary> /// <value>The useLegacyEncoding status.</value> public static bool UmbracoMembershipProviderLegacyEncoding { get { return IsConfiguredMembershipProviderUsingLegacyEncoding(Constants.Conventions.Member.UmbracoMemberProviderName); } set { SetMembershipProvidersLegacyEncoding(Constants.Conventions.Member.UmbracoMemberProviderName, value); } } /// <summary> /// Gets or sets the Umbraco users membership providers' useLegacyEncoding state. This will return a boolean /// </summary> /// <value>The useLegacyEncoding status.</value> public static bool UmbracoUsersMembershipProviderLegacyEncoding { get { return IsConfiguredMembershipProviderUsingLegacyEncoding(UmbracoConfig.For.UmbracoSettings().Providers.DefaultBackOfficeUserProvider); } set { SetMembershipProvidersLegacyEncoding(UmbracoConfig.For.UmbracoSettings().Providers.DefaultBackOfficeUserProvider, value); } } /// <summary> /// Saves a setting into the configuration file. /// </summary> /// <param name="key">Key of the setting to be saved.</param> /// <param name="value">Value of the setting to be saved.</param> internal static void SaveSetting(string key, string value) { var fileName = IOHelper.MapPath(string.Format("{0}/web.config", SystemDirectories.Root)); var xml = XDocument.Load(fileName, LoadOptions.PreserveWhitespace); var appSettings = xml.Root.DescendantsAndSelf("appSettings").Single(); // Update appSetting if it exists, or else create a new appSetting for the given key and value var setting = appSettings.Descendants("add").FirstOrDefault(s => s.Attribute("key").Value == key); if (setting == null) appSettings.Add(new XElement("add", new XAttribute("key", key), new XAttribute("value", value))); else setting.Attribute("value").Value = value; xml.Save(fileName, SaveOptions.DisableFormatting); ConfigurationManager.RefreshSection("appSettings"); } /// <summary> /// Removes a setting from the configuration file. /// </summary> /// <param name="key">Key of the setting to be removed.</param> internal static void RemoveSetting(string key) { var fileName = IOHelper.MapPath(string.Format("{0}/web.config", SystemDirectories.Root)); var xml = XDocument.Load(fileName, LoadOptions.PreserveWhitespace); var appSettings = xml.Root.DescendantsAndSelf("appSettings").Single(); var setting = appSettings.Descendants("add").FirstOrDefault(s => s.Attribute("key").Value == key); if (setting != null) { setting.Remove(); xml.Save(fileName, SaveOptions.DisableFormatting); ConfigurationManager.RefreshSection("appSettings"); } } private static void SetMembershipProvidersLegacyEncoding(string providerName, bool useLegacyEncoding) { //check if this can even be configured. var membershipProvider = Membership.Providers[providerName] as MembershipProviderBase; if (membershipProvider == null) { return; } if (membershipProvider.GetType().Namespace == "umbraco.providers.members") { //its the legacy one, this cannot be changed return; } var webConfigFilename = IOHelper.MapPath(string.Format("{0}/web.config", SystemDirectories.Root)); var webConfigXml = XDocument.Load(webConfigFilename, LoadOptions.PreserveWhitespace); var membershipConfigs = webConfigXml.XPathSelectElements("configuration/system.web/membership/providers/add").ToList(); if (membershipConfigs.Any() == false) return; var provider = membershipConfigs.SingleOrDefault(c => c.Attribute("name") != null && c.Attribute("name").Value == providerName); if (provider == null) return; provider.SetAttributeValue("useLegacyEncoding", useLegacyEncoding); webConfigXml.Save(webConfigFilename, SaveOptions.DisableFormatting); } private static bool IsConfiguredMembershipProviderUsingLegacyEncoding(string providerName) { //check if this can even be configured. var membershipProvider = Membership.Providers[providerName] as MembershipProviderBase; if (membershipProvider == null) { return false; } return membershipProvider.UseLegacyEncoding; } /// <summary> /// Gets the full path to root. /// </summary> /// <value>The fullpath to root.</value> public static string FullpathToRoot { get { return IOHelper.GetRootDirectorySafe(); } } /// <summary> /// Gets a value indicating whether umbraco is running in [debug mode]. /// </summary> /// <value><c>true</c> if [debug mode]; otherwise, <c>false</c>.</value> public static bool DebugMode { get { try { if (HttpContext.Current != null) { return HttpContext.Current.IsDebuggingEnabled; } //go and get it from config directly var section = ConfigurationManager.GetSection("system.web/compilation") as CompilationSection; return section != null && section.Debug; } catch { return false; } } } /// <summary> /// Gets a value indicating whether the current version of umbraco is configured. /// </summary> /// <value><c>true</c> if configured; otherwise, <c>false</c>.</value> [Obsolete("Do not use this, it is no longer in use and will be removed from the codebase in future versions")] internal static bool Configured { get { try { string configStatus = ConfigurationStatus; string currentVersion = UmbracoVersion.GetSemanticVersion().ToSemanticString(); if (currentVersion != configStatus) { LogHelper.Debug<GlobalSettings>("CurrentVersion different from configStatus: '" + currentVersion + "','" + configStatus + "'"); } return (configStatus == currentVersion); } catch { return false; } } } /// <summary> /// Gets the time out in minutes. /// </summary> /// <value>The time out in minutes.</value> public static int TimeOutInMinutes { get { try { return int.Parse(ConfigurationManager.AppSettings["umbracoTimeOutInMinutes"]); } catch { return 20; } } } /// <summary> /// Gets a value indicating whether umbraco uses directory urls. /// </summary> /// <value><c>true</c> if umbraco uses directory urls; otherwise, <c>false</c>.</value> public static bool UseDirectoryUrls { get { try { return bool.Parse(ConfigurationManager.AppSettings["umbracoUseDirectoryUrls"]); } catch { return false; } } } /// <summary> /// Returns a string value to determine if umbraco should skip version-checking. /// </summary> /// <value>The version check period in days (0 = never).</value> public static int VersionCheckPeriod { get { try { return int.Parse(ConfigurationManager.AppSettings["umbracoVersionCheckPeriod"]); } catch { return 7; } } } /// <summary> /// Returns a string value to determine if umbraco should disbable xslt extensions /// </summary> /// <value><c>"true"</c> if version xslt extensions are disabled, otherwise, <c>"false"</c></value> [Obsolete("This is no longer used and will be removed from the codebase in future releases")] public static string DisableXsltExtensions { get { return ConfigurationManager.AppSettings.ContainsKey("umbracoDisableXsltExtensions") ? ConfigurationManager.AppSettings["umbracoDisableXsltExtensions"] : "false"; } } internal static bool ContentCacheXmlStoredInCodeGen { get { //defaults to false return ConfigurationManager.AppSettings.ContainsKey("umbracoContentXMLUseLocalTemp") && bool.Parse(ConfigurationManager.AppSettings["umbracoContentXMLUseLocalTemp"]); //default to false } } /// <summary> /// Returns a string value to determine if umbraco should use Xhtml editing mode in the wysiwyg editor /// </summary> /// <value><c>"true"</c> if Xhtml mode is enable, otherwise, <c>"false"</c></value> [Obsolete("This is no longer used and will be removed from the codebase in future releases")] public static string EditXhtmlMode { get { return "true"; } } /// <summary> /// Gets the default UI language. /// </summary> /// <value>The default UI language.</value> public static string DefaultUILanguage { get { return ConfigurationManager.AppSettings.ContainsKey("umbracoDefaultUILanguage") ? ConfigurationManager.AppSettings["umbracoDefaultUILanguage"] : string.Empty; } } /// <summary> /// Gets the profile URL. /// </summary> /// <value>The profile URL.</value> public static string ProfileUrl { get { //the default will be 'profiler' return ConfigurationManager.AppSettings.ContainsKey("umbracoProfileUrl") ? ConfigurationManager.AppSettings["umbracoProfileUrl"] : "profiler"; } } /// <summary> /// Gets a value indicating whether umbraco should hide top level nodes from generated urls. /// </summary> /// <value> /// <c>true</c> if umbraco hides top level nodes from urls; otherwise, <c>false</c>. /// </value> public static bool HideTopLevelNodeFromPath { get { try { return bool.Parse(ConfigurationManager.AppSettings["umbracoHideTopLevelNodeFromPath"]); } catch { return false; } } } /// <summary> /// Gets the current version. /// </summary> /// <value>The current version.</value> [Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)] public static string CurrentVersion { get { return UmbracoVersion.GetSemanticVersion().ToSemanticString(); } } /// <summary> /// Gets the major version number. /// </summary> /// <value>The major version number.</value> [Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)] public static int VersionMajor { get { return UmbracoVersion.Current.Major; } } /// <summary> /// Gets the minor version number. /// </summary> /// <value>The minor version number.</value> [Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)] public static int VersionMinor { get { return UmbracoVersion.Current.Minor; } } /// <summary> /// Gets the patch version number. /// </summary> /// <value>The patch version number.</value> [Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)] public static int VersionPatch { get { return UmbracoVersion.Current.Build; } } /// <summary> /// Gets the version comment (like beta or RC). /// </summary> /// <value>The version comment.</value> [Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)] public static string VersionComment { get { return Umbraco.Core.Configuration.UmbracoVersion.CurrentComment; } } /// <summary> /// Requests the is in umbraco application directory structure. /// </summary> /// <param name="context">The context.</param> /// <returns></returns> public static bool RequestIsInUmbracoApplication(HttpContext context) { return context.Request.Path.ToLower().IndexOf(IOHelper.ResolveUrl(SystemDirectories.Umbraco).ToLower()) > -1; } public static bool RequestIsInUmbracoApplication(HttpContextBase context) { return context.Request.Path.ToLower().IndexOf(IOHelper.ResolveUrl(SystemDirectories.Umbraco).ToLower()) > -1; } /// <summary> /// Gets a value indicating whether umbraco should force a secure (https) connection to the backoffice. /// </summary> /// <value><c>true</c> if [use SSL]; otherwise, <c>false</c>.</value> public static bool UseSSL { get { try { return bool.Parse(ConfigurationManager.AppSettings["umbracoUseSSL"]); } catch { return false; } } } /// <summary> /// Gets the umbraco license. /// </summary> /// <value>The license.</value> public static string License { get { string license = "<A href=\"http://umbraco.org/redir/license\" target=\"_blank\">the open source license MIT</A>. The umbraco UI is freeware licensed under the umbraco license."; var versionDoc = new XmlDocument(); var versionReader = new XmlTextReader(IOHelper.MapPath(SystemDirectories.Umbraco + "/version.xml")); versionDoc.Load(versionReader); versionReader.Close(); // check for license try { string licenseUrl = versionDoc.SelectSingleNode("/version/licensing/licenseUrl").FirstChild.Value; string licenseValidation = versionDoc.SelectSingleNode("/version/licensing/licenseValidation").FirstChild.Value; string licensedTo = versionDoc.SelectSingleNode("/version/licensing/licensedTo").FirstChild.Value; if (licensedTo != "" && licenseUrl != "") { license = "umbraco Commercial License<br/><b>Registered to:</b><br/>" + licensedTo.Replace("\n", "<br/>") + "<br/><b>For use with domain:</b><br/>" + licenseUrl; } } catch { } return license; } } /// <summary> /// Determines whether the current request is reserved based on the route table and /// whether the specified URL is reserved or is inside a reserved path. /// </summary> /// <param name="url"></param> /// <param name="httpContext"></param> /// <param name="routes">The route collection to lookup the request in</param> /// <returns></returns> public static bool IsReservedPathOrUrl(string url, HttpContextBase httpContext, RouteCollection routes) { if (httpContext == null) throw new ArgumentNullException("httpContext"); if (routes == null) throw new ArgumentNullException("routes"); //check if the current request matches a route, if so then it is reserved. var route = routes.GetRouteData(httpContext); if (route != null) return true; //continue with the standard ignore routine return IsReservedPathOrUrl(url); } /// <summary> /// Determines whether the specified URL is reserved or is inside a reserved path. /// </summary> /// <param name="url">The URL to check.</param> /// <returns> /// <c>true</c> if the specified URL is reserved; otherwise, <c>false</c>. /// </returns> public static bool IsReservedPathOrUrl(string url) { if (_reservedUrlsCache == null) { lock (Locker) { if (_reservedUrlsCache == null) { // store references to strings to determine changes _reservedPathsCache = GlobalSettings.ReservedPaths; _reservedUrlsCache = GlobalSettings.ReservedUrls; // add URLs and paths to a new list var newReservedList = new HashSet<string>(); foreach (var reservedUrlTrimmed in _reservedUrlsCache .Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.Trim().ToLowerInvariant()) .Where(x => x.IsNullOrWhiteSpace() == false) .Select(reservedUrl => IOHelper.ResolveUrl(reservedUrl).Trim().EnsureStartsWith("/")) .Where(reservedUrlTrimmed => reservedUrlTrimmed.IsNullOrWhiteSpace() == false)) { newReservedList.Add(reservedUrlTrimmed); } foreach (var reservedPathTrimmed in _reservedPathsCache .Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.Trim().ToLowerInvariant()) .Where(x => x.IsNullOrWhiteSpace() == false) .Select(reservedPath => IOHelper.ResolveUrl(reservedPath).Trim().EnsureStartsWith("/").EnsureEndsWith("/")) .Where(reservedPathTrimmed => reservedPathTrimmed.IsNullOrWhiteSpace() == false)) { newReservedList.Add(reservedPathTrimmed); } // use the new list from now on _reservedList = newReservedList; } } } //The url should be cleaned up before checking: // * If it doesn't contain an '.' in the path then we assume it is a path based URL, if that is the case we should add an trailing '/' because all of our reservedPaths use a trailing '/' // * We shouldn't be comparing the query at all var pathPart = url.Split(new[] {'?'}, StringSplitOptions.RemoveEmptyEntries)[0].ToLowerInvariant(); if (pathPart.Contains(".") == false) { pathPart = pathPart.EnsureEndsWith('/'); } // return true if url starts with an element of the reserved list return _reservedList.Any(x => pathPart.InvariantStartsWith(x)); } } }
// StreamManipulator.cs // // Copyright (C) 2001 Mike Krueger // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams { /// <summary> /// This class allows us to retrieve a specified number of bits from /// the input buffer, as well as copy big byte blocks. /// /// It uses an int buffer to store up to 31 bits for direct /// manipulation. This guarantees that we can get at least 16 bits, /// but we only need at most 15, so this is all safe. /// /// There are some optimizations in this class, for example, you must /// never peek more than 8 bits more than needed, and you must first /// peek bits before you may drop them. This is not a general purpose /// class but optimized for the behaviour of the Inflater. /// /// authors of the original java version : John Leuner, Jochen Hoenicke /// </summary> public class StreamManipulator { #region Instance Fields private byte[] window_; private int windowStart_; private int windowEnd_; private uint buffer_; private int bitsInBuffer_; #endregion #region Constructors /// <summary> /// Constructs a default StreamManipulator with all buffers empty /// </summary> public StreamManipulator() { } #endregion /// <summary> /// Get the next sequence of bits but don't increase input pointer. bitCount must be /// less or equal 16 and if this call succeeds, you must drop /// at least n - 8 bits in the next call. /// </summary> /// <param name="bitCount">The number of bits to peek.</param> /// <returns> /// the value of the bits, or -1 if not enough bits available. */ /// </returns> public int PeekBits(int bitCount) { if (bitsInBuffer_ < bitCount) { if (windowStart_ == windowEnd_) { return -1; // ok } buffer_ |= (uint)((window_[windowStart_++] & 0xff | (window_[windowStart_++] & 0xff) << 8) << bitsInBuffer_); bitsInBuffer_ += 16; } return (int)(buffer_ & ((1 << bitCount) - 1)); } /// <summary> /// Drops the next n bits from the input. You should have called PeekBits /// with a bigger or equal n before, to make sure that enough bits are in /// the bit buffer. /// </summary> /// <param name="bitCount">The number of bits to drop.</param> public void DropBits(int bitCount) { buffer_ >>= bitCount; bitsInBuffer_ -= bitCount; } /// <summary> /// Gets the next n bits and increases input pointer. This is equivalent /// to <see cref="PeekBits"/> followed by <see cref="DropBits"/>, except for correct error handling. /// </summary> /// <param name="bitCount">The number of bits to retrieve.</param> /// <returns> /// the value of the bits, or -1 if not enough bits available. /// </returns> public int GetBits(int bitCount) { int bits = PeekBits(bitCount); if (bits >= 0) { DropBits(bitCount); } return bits; } /// <summary> /// Gets the number of bits available in the bit buffer. This must be /// only called when a previous PeekBits() returned -1. /// </summary> /// <returns> /// the number of bits available. /// </returns> public int AvailableBits { get { return bitsInBuffer_; } } /// <summary> /// Gets the number of bytes available. /// </summary> /// <returns> /// The number of bytes available. /// </returns> public int AvailableBytes { get { return windowEnd_ - windowStart_ + (bitsInBuffer_ >> 3); } } /// <summary> /// Skips to the next byte boundary. /// </summary> public void SkipToByteBoundary() { buffer_ >>= (bitsInBuffer_ & 7); bitsInBuffer_ &= ~7; } /// <summary> /// Returns true when SetInput can be called /// </summary> public bool IsNeedingInput { get { return windowStart_ == windowEnd_; } } /// <summary> /// Copies bytes from input buffer to output buffer starting /// at output[offset]. You have to make sure, that the buffer is /// byte aligned. If not enough bytes are available, copies fewer /// bytes. /// </summary> /// <param name="output"> /// The buffer to copy bytes to. /// </param> /// <param name="offset"> /// The offset in the buffer at which copying starts /// </param> /// <param name="length"> /// The length to copy, 0 is allowed. /// </param> /// <returns> /// The number of bytes copied, 0 if no bytes were available. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// Length is less than zero /// </exception> /// <exception cref="InvalidOperationException"> /// Bit buffer isnt byte aligned /// </exception> public int CopyBytes(byte[] output, int offset, int length) { if (length < 0) { throw new ArgumentOutOfRangeException("length"); } if ((bitsInBuffer_ & 7) != 0) { // bits_in_buffer may only be 0 or a multiple of 8 throw new InvalidOperationException("Bit buffer is not byte aligned!"); } int count = 0; while ((bitsInBuffer_ > 0) && (length > 0)) { output[offset++] = (byte) buffer_; buffer_ >>= 8; bitsInBuffer_ -= 8; length--; count++; } if (length == 0) { return count; } int avail = windowEnd_ - windowStart_; if (length > avail) { length = avail; } System.Array.Copy(window_, windowStart_, output, offset, length); windowStart_ += length; if (((windowStart_ - windowEnd_) & 1) != 0) { // We always want an even number of bytes in input, see peekBits buffer_ = (uint)(window_[windowStart_++] & 0xff); bitsInBuffer_ = 8; } return count + length; } /// <summary> /// Resets state and empties internal buffers /// </summary> public void Reset() { buffer_ = 0; windowStart_ = windowEnd_ = bitsInBuffer_ = 0; } /// <summary> /// Add more input for consumption. /// Only call when IsNeedingInput returns true /// </summary> /// <param name="buffer">data to be input</param> /// <param name="offset">offset of first byte of input</param> /// <param name="count">number of bytes of input to add.</param> public void SetInput(byte[] buffer, int offset, int count) { if ( buffer == null ) { throw new ArgumentNullException("buffer"); } if ( offset < 0 ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("offset"); #else throw new ArgumentOutOfRangeException("offset", "Cannot be negative"); #endif } if ( count < 0 ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("count"); #else throw new ArgumentOutOfRangeException("count", "Cannot be negative"); #endif } if (windowStart_ < windowEnd_) { throw new InvalidOperationException("Old input was not completely processed"); } int end = offset + count; // We want to throw an ArrayIndexOutOfBoundsException early. // Note the check also handles integer wrap around. if ((offset > end) || (end > buffer.Length) ) { throw new ArgumentOutOfRangeException("count"); } if ((count & 1) != 0) { // We always want an even number of bytes in input, see PeekBits buffer_ |= (uint)((buffer[offset++] & 0xff) << bitsInBuffer_); bitsInBuffer_ += 8; } window_ = buffer; windowStart_ = offset; windowEnd_ = end; } } }
using System; using System.IO; using System.Globalization; namespace AWIComponentLib.Utility.Logging { public class LogClass { #region vars public static bool logging; private bool fileCreated; private string fileName; private string path; private long maxSize; private FileStream wfile; private StreamWriter writer; #endregion #region constructor public LogClass() { CultureInfo ci = new CultureInfo("sv-SE", true); System.Threading.Thread.CurrentThread.CurrentCulture = ci; ci.DateTimeFormat.DateSeparator = "-"; logging = false; fileCreated = false; fileName = ""; path = ""; maxSize = 102400000; //bytes - 100,000k default 100Meg } #endregion #region destructor ~LogClass() { CultureInfo ci = new CultureInfo("sv-SE", true); System.Threading.Thread.CurrentThread.CurrentCulture = ci; ci.DateTimeFormat.DateSeparator = "-"; if (logging) { try { if (WriteLine(DateTime.Now.ToString() + " Logging Stopped.") < 0) Console.WriteLine("LOG ERROR: Failed to write to Log file."); } catch (Exception) { try { Console.WriteLine("LOG ERROR: Failed to write to Log file."); } catch {} } logging = false; try { writer.Close(); } catch {} } if (fileCreated) { fileCreated = false; try { wfile.Close(); } catch {}; } } #endregion #region StartLogging() public void StartLogging() { logging = true; try { if (WriteLine(DateTime.Now.ToString() + " Logging Started.") < 0) Console.WriteLine("LOG ERROR: Failed to write to Log file."); } catch { Console.WriteLine("LOG ERROR: Failed to write to Log file."); } } #endregion #region StopLogging() public void StopLogging() { if (logging) { try { if (WriteLine(DateTime.Now.ToString() + " Logging Stopped.") < 0) Console.WriteLine("LOG ERROR: Failed to write to Log file."); } catch { Console.WriteLine("LOG ERROR: Failed to write to Log file."); } logging = false; try { writer.Close(); } catch {} } if (fileCreated) { fileCreated = false; try { wfile.Close(); } catch {} } } #endregion #region CreateLogFile() public int CreateLogFile(string fName, string fPath, short type) { string fullFileName = fPath + fName; try { if (type == 1) //new { //check if the file exits, notify application if (File.Exists(fullFileName)) return(-2); wfile = new FileStream (fullFileName, FileMode.CreateNew, FileAccess.Write); } else if (type == 2) //append wfile = new FileStream (fullFileName, FileMode.Append, FileAccess.Write); else if (type == 3) //new overwrite wfile = new FileStream (fullFileName, FileMode.Create, FileAccess.Write); writer = new StreamWriter(wfile); } catch (Exception ex) { Console.WriteLine(ex.Message); return(-1); } writer.AutoFlush = true; fileName = fName; path = fPath; fileCreated = true; return (0); } #endregion #region WriteLine() public int WriteLine(string data) { if (logging && wfile.CanWrite) { if (data.Length == 0) return (-1); if (wfile.Length < maxSize) writer.WriteLine(data); return(0); } else return (-1); } #endregion #region ReadLine() public string ReadLine() { return (""); } #endregion #region Flush() public void Flush() { writer.Flush(); writer.Close(); wfile.Flush(); wfile.Close(); } #endregion #region ClearFile() public void ClearFile() { wfile.SetLength(0); } #endregion #region GetPath() public string GetPath() { return (path); } #endregion #region GetFileName() public string GetFileName() { return (fileName); } #endregion #region GetFileSize() public long GetFileSize() { return (wfile.Length); } #endregion #region GetMaxSize() public long GetMaxSize() { return (maxSize); } #endregion #region SetMaxSize(int max) public void GetMaxSize(long max) { maxSize = max; } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEngine; using System; namespace HoloToolkit.Unity.InputModule { /// <summary> /// Component that allows dragging an object with your hand on HoloLens. /// Dragging is done by calculating the angular delta and z-delta between the current and previous hand positions, /// and then repositioning the object based on that. /// </summary> public class HandDraggable : MonoBehaviour, IFocusable, IInputHandler, ISourceStateHandler { /// <summary> /// Event triggered when dragging starts. /// </summary> public event Action StartedDragging; /// <summary> /// Event triggered when dragging stops. /// </summary> public event Action StoppedDragging; [Tooltip("Transform that will be dragged. Defaults to the object of the component.")] public Transform HostTransform; [Tooltip("Scale by which hand movement in z is multiplied to move the dragged object.")] public float DistanceScale = 2f; public enum RotationModeEnum { Default, LockObjectRotation, OrientTowardUser, OrientTowardUserAndKeepUpright } public RotationModeEnum RotationMode = RotationModeEnum.Default; [Tooltip("Controls the speed at which the object will interpolate toward the desired position")] [Range(0.01f, 1.0f)] public float PositionLerpSpeed = 0.2f; [Tooltip("Controls the speed at which the object will interpolate toward the desired rotation")] [Range(0.01f, 1.0f)] public float RotationLerpSpeed = 0.2f; public bool IsDraggingEnabled = true; private bool isDragging; private bool isGazed; private Vector3 objRefForward; private Vector3 objRefUp; private float objRefDistance; private Quaternion gazeAngularOffset; private float handRefDistance; private Vector3 objRefGrabPoint; private Vector3 draggingPosition; private Quaternion draggingRotation; private IInputSource currentInputSource; private uint currentInputSourceId; private void Start() { if (HostTransform == null) { HostTransform = transform; } } private void OnDestroy() { if (isDragging) { StopDragging(); } if (isGazed) { OnFocusExit(); } } private void Update() { if (IsDraggingEnabled && isDragging) { UpdateDragging(); } } /// <summary> /// Starts dragging the object. /// </summary> public void StartDragging(Vector3 initialDraggingPosition) { if (!IsDraggingEnabled) { return; } if (isDragging) { return; } // TODO: robertes: Fix push/pop and single-handler model so that multiple HandDraggable components // can be active at once. // Add self as a modal input handler, to get all inputs during the manipulation InputManager.Instance.PushModalInputHandler(gameObject); isDragging = true; Transform cameraTransform = CameraCache.Main.transform; Vector3 handPosition; currentInputSource.TryGetPointerPosition(currentInputSourceId, out handPosition); Vector3 pivotPosition = GetHandPivotPosition(cameraTransform); handRefDistance = Vector3.Magnitude(handPosition - pivotPosition); objRefDistance = Vector3.Magnitude(initialDraggingPosition - pivotPosition); Vector3 objForward = HostTransform.forward; Vector3 objUp = HostTransform.up; // Store where the object was grabbed from objRefGrabPoint = cameraTransform.transform.InverseTransformDirection(HostTransform.position - initialDraggingPosition); Vector3 objDirection = Vector3.Normalize(initialDraggingPosition - pivotPosition); Vector3 handDirection = Vector3.Normalize(handPosition - pivotPosition); objForward = cameraTransform.InverseTransformDirection(objForward); // in camera space objUp = cameraTransform.InverseTransformDirection(objUp); // in camera space objDirection = cameraTransform.InverseTransformDirection(objDirection); // in camera space handDirection = cameraTransform.InverseTransformDirection(handDirection); // in camera space objRefForward = objForward; objRefUp = objUp; // Store the initial offset between the hand and the object, so that we can consider it when dragging gazeAngularOffset = Quaternion.FromToRotation(handDirection, objDirection); draggingPosition = initialDraggingPosition; StartedDragging.RaiseEvent(); } /// <summary> /// Gets the pivot position for the hand, which is approximated to the base of the neck. /// </summary> /// <returns>Pivot position for the hand.</returns> private Vector3 GetHandPivotPosition(Transform cameraTransform) { Vector3 pivot = cameraTransform.position + new Vector3(0, -0.2f, 0) - cameraTransform.forward * 0.2f; // a bit lower and behind return pivot; } /// <summary> /// Enables or disables dragging. /// </summary> /// <param name="isEnabled">Indicates whether dragging should be enabled or disabled.</param> public void SetDragging(bool isEnabled) { if (IsDraggingEnabled == isEnabled) { return; } IsDraggingEnabled = isEnabled; if (isDragging) { StopDragging(); } } /// <summary> /// Update the position of the object being dragged. /// </summary> private void UpdateDragging() { Vector3 newHandPosition; Transform cameraTransform = CameraCache.Main.transform; currentInputSource.TryGetPointerPosition(currentInputSourceId, out newHandPosition); Vector3 pivotPosition = GetHandPivotPosition(cameraTransform); Vector3 newHandDirection = Vector3.Normalize(newHandPosition - pivotPosition); newHandDirection = cameraTransform.InverseTransformDirection(newHandDirection); // in camera space Vector3 targetDirection = Vector3.Normalize(gazeAngularOffset * newHandDirection); targetDirection = cameraTransform.TransformDirection(targetDirection); // back to world space float currentHandDistance = Vector3.Magnitude(newHandPosition - pivotPosition); float distanceRatio = currentHandDistance / handRefDistance; float distanceOffset = distanceRatio > 0 ? (distanceRatio - 1f) * DistanceScale : 0; float targetDistance = objRefDistance + distanceOffset; draggingPosition = pivotPosition + (targetDirection * targetDistance); if (RotationMode == RotationModeEnum.OrientTowardUser || RotationMode == RotationModeEnum.OrientTowardUserAndKeepUpright) { draggingRotation = Quaternion.LookRotation(HostTransform.position - pivotPosition); } else if (RotationMode == RotationModeEnum.LockObjectRotation) { draggingRotation = HostTransform.rotation; } else // RotationModeEnum.Default { Vector3 objForward = cameraTransform.TransformDirection(objRefForward); // in world space Vector3 objUp = cameraTransform.TransformDirection(objRefUp); // in world space draggingRotation = Quaternion.LookRotation(objForward, objUp); } // Apply Final Position HostTransform.position = Vector3.Lerp(HostTransform.position, draggingPosition + cameraTransform.TransformDirection(objRefGrabPoint), PositionLerpSpeed); // Apply Final Rotation HostTransform.rotation = Quaternion.Lerp(HostTransform.rotation, draggingRotation, RotationLerpSpeed); if (RotationMode == RotationModeEnum.OrientTowardUserAndKeepUpright) { Quaternion upRotation = Quaternion.FromToRotation(HostTransform.up, Vector3.up); HostTransform.rotation = upRotation * HostTransform.rotation; } } /// <summary> /// Stops dragging the object. /// </summary> public void StopDragging() { if (!isDragging) { return; } // Remove self as a modal input handler InputManager.Instance.PopModalInputHandler(); isDragging = false; currentInputSource = null; StoppedDragging.RaiseEvent(); } public void OnFocusEnter() { if (!IsDraggingEnabled) { return; } if (isGazed) { return; } isGazed = true; } public void OnFocusExit() { if (!IsDraggingEnabled) { return; } if (!isGazed) { return; } isGazed = false; } public void OnInputUp(InputEventData eventData) { if (currentInputSource != null && eventData.SourceId == currentInputSourceId) { eventData.Use(); // Mark the event as used, so it doesn't fall through to other handlers. StopDragging(); } } public void OnInputDown(InputEventData eventData) { if (isDragging) { // We're already handling drag input, so we can't start a new drag operation. return; } if (!eventData.InputSource.SupportsInputInfo(eventData.SourceId, SupportedInputInfo.Position)) { // The input source must provide positional data for this script to be usable return; } eventData.Use(); // Mark the event as used, so it doesn't fall through to other handlers. currentInputSource = eventData.InputSource; currentInputSourceId = eventData.SourceId; FocusDetails? details = FocusManager.Instance.TryGetFocusDetails(eventData); Vector3 initialDraggingPosition = (details == null) ? HostTransform.position : details.Value.Point; StartDragging(initialDraggingPosition); } public void OnSourceDetected(SourceStateEventData eventData) { // Nothing to do } public void OnSourceLost(SourceStateEventData eventData) { if (currentInputSource != null && eventData.SourceId == currentInputSourceId) { StopDragging(); } } } }
// // Copyright 2012, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Threading.Tasks; using System.Net; using System.Collections.Generic; using Xamarin.Utilities; namespace Xamarin.Auth { /// <summary> /// Type of method used to fetch the username of an account /// after it has been successfully authenticated. /// </summary> #if XAMARIN_AUTH_INTERNAL internal delegate Task<string> GetUsernameAsyncFunc (IDictionary<string, string> accountProperties); #else public delegate Task<string> GetUsernameAsyncFunc (IDictionary<string, string> accountProperties); #endif /// <summary> /// OAuth 1.0 authenticator. /// </summary> #if XAMARIN_AUTH_INTERNAL internal class OAuth1Authenticator : WebAuthenticator #else public class OAuth1Authenticator : WebAuthenticator #endif { string consumerKey; string consumerSecret; Uri requestTokenUrl; Uri authorizeUrl; Uri accessTokenUrl; Uri callbackUrl; GetUsernameAsyncFunc getUsernameAsync; string token; string tokenSecret; string verifier; /// <summary> /// Initializes a new instance of the <see cref="Xamarin.Auth.OAuth1Authenticator"/> class. /// </summary> /// <param name='consumerKey'> /// Consumer key. /// </param> /// <param name='consumerSecret'> /// Consumer secret. /// </param> /// <param name='requestTokenUrl'> /// Request token URL. /// </param> /// <param name='authorizeUrl'> /// Authorize URL. /// </param> /// <param name='accessTokenUrl'> /// Access token URL. /// </param> /// <param name='callbackUrl'> /// Callback URL. /// </param> /// <param name='getUsernameAsync'> /// Method used to fetch the username of an account /// after it has been successfully authenticated. /// </param> public OAuth1Authenticator (string consumerKey, string consumerSecret, Uri requestTokenUrl, Uri authorizeUrl, Uri accessTokenUrl, Uri callbackUrl, GetUsernameAsyncFunc getUsernameAsync = null) { if (string.IsNullOrEmpty (consumerKey)) { throw new ArgumentException ("consumerKey must be provided", "consumerKey"); } this.consumerKey = consumerKey; if (string.IsNullOrEmpty (consumerSecret)) { throw new ArgumentException ("consumerSecret must be provided", "consumerSecret"); } this.consumerSecret = consumerSecret; if (requestTokenUrl == null) { throw new ArgumentNullException ("requestTokenUrl"); } this.requestTokenUrl = requestTokenUrl; if (authorizeUrl == null) { throw new ArgumentNullException ("authorizeUrl"); } this.authorizeUrl = authorizeUrl; if (accessTokenUrl == null) { throw new ArgumentNullException ("accessTokenUrl"); } this.accessTokenUrl = accessTokenUrl; if (callbackUrl == null) { throw new ArgumentNullException ("callbackUrl"); } this.callbackUrl = callbackUrl; this.getUsernameAsync = getUsernameAsync; } /// <summary> /// Method that returns the initial URL to be displayed in the web browser. /// </summary> /// <returns> /// A task that will return the initial URL. /// </returns> public override Task<Uri> GetInitialUrlAsync () { var req = OAuth1.CreateRequest ( "GET", requestTokenUrl, new Dictionary<string, string>() { { "oauth_callback", callbackUrl.AbsoluteUri }, }, consumerKey, consumerSecret, ""); return req.GetResponseAsync ().ContinueWith (respTask => { var content = respTask.Result.GetResponseText (); var r = WebEx.FormDecode (content); token = r["oauth_token"]; tokenSecret = r["oauth_token_secret"]; string paramType = authorizeUrl.AbsoluteUri.IndexOf("?") >= 0 ? "&" : "?"; var url = authorizeUrl.AbsoluteUri + paramType + "oauth_token=" + Uri.EscapeDataString (token); return new Uri (url); }); } /// <summary> /// Event handler that watches for the callback URL to be loaded. /// </summary> /// <param name='url'> /// The URL of the loaded page. /// </param> public override void OnPageLoaded (Uri url) { if (url.Host == callbackUrl.Host && url.AbsolutePath == callbackUrl.AbsolutePath) { var query = url.Query; var r = WebEx.FormDecode (query); r.TryGetValue ("oauth_verifier", out verifier); GetAccessTokenAsync ().ContinueWith (getTokenTask => { if (getTokenTask.IsCanceled) { OnCancelled (); } else if (getTokenTask.IsFaulted) { OnError (getTokenTask.Exception); } }, TaskContinuationOptions.NotOnRanToCompletion); } } Task GetAccessTokenAsync () { var requestParams = new Dictionary<string, string> { { "oauth_token", token } }; if (verifier != null) requestParams["oauth_verifier"] = verifier; var req = OAuth1.CreateRequest ( "GET", accessTokenUrl, requestParams, consumerKey, consumerSecret, tokenSecret); return req.GetResponseAsync ().ContinueWith (respTask => { var content = respTask.Result.GetResponseText (); var accountProperties = WebEx.FormDecode (content); accountProperties["oauth_consumer_key"] = consumerKey; accountProperties["oauth_consumer_secret"] = consumerSecret; if (getUsernameAsync != null) { getUsernameAsync (accountProperties).ContinueWith (uTask => { if (uTask.IsFaulted) { OnError (uTask.Exception); } else { OnSucceeded (uTask.Result, accountProperties); } }); } else { OnSucceeded ("", accountProperties); } }); } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * 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 OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text.RegularExpressions; using System.Threading; using System.Web; using System.Net; using log4net; using Nwc.XmlRpc; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Communications.Cache; using OpenSim.Framework.Statistics; using OpenSim.Data; namespace OpenSim.Framework.Communications.Services { public abstract class LoginService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected string m_welcomeMessage = "Welcome to InWorldz"; protected string m_MapServerURI = ""; protected int m_minLoginLevel = 0; protected UserManagerBase m_userManager = null; /// <summary> /// Used during login to send the skeleton of the OpenSim Library to the client. /// </summary> protected LibraryRootFolder m_libraryRootFolder; protected uint m_defaultHomeX; protected uint m_defaultHomeY; private const string BAD_VIEWERS_FILE = "badviewers.txt"; private List<string> _badViewerStrings = new List<string>(); // For new users' first-time logins private const string DEFAULT_LOGINS_FILE = "defaultlogins.txt"; private List<string> _DefaultLoginsList = new List<string>(); // For returning users' where the preferred region is down private const string DEFAULT_REGIONS_FILE = "defaultregions.txt"; private List<string> _DefaultRegionsList = new List<string>(); /// <summary> /// LoadStringListFromFile /// </summary> /// <param name="theList"></param> /// <param name="fn"></param> /// <param name="desc"></param> private void LoadStringListFromFile(List<string> theList, string fn, string desc) { if (File.Exists(fn)) { using (System.IO.StreamReader file = new System.IO.StreamReader(fn)) { string line; while ((line = file.ReadLine()) != null) { line = line.Trim(); if ((line != "") && !line.StartsWith(";") && !line.StartsWith("//")) { theList.Add(line); m_log.InfoFormat("[LOGINSERVICE] Added {0} {1}", desc, line); } } } } } /// <summary> /// Constructor /// </summary> /// <param name="userManager"></param> /// <param name="libraryRootFolder"></param> /// <param name="welcomeMess"></param> public LoginService(UserManagerBase userManager, LibraryRootFolder libraryRootFolder, string welcomeMess, string mapServerURI) { m_userManager = userManager; m_libraryRootFolder = libraryRootFolder; if (welcomeMess != String.Empty) m_welcomeMessage = welcomeMess; if (mapServerURI != String.Empty) m_MapServerURI = mapServerURI; // For new users' first-time logins LoadDefaultLoginsFromFile(DEFAULT_LOGINS_FILE); // For returning users' where the preferred region is down LoadDefaultRegionsFromFile(DEFAULT_REGIONS_FILE); LoadStringListFromFile(_badViewerStrings, BAD_VIEWERS_FILE, "blacklisted viewer"); } /// <summary> /// If the user is already logged in, try to notify the region that the user they've got is dead. /// </summary> /// <param name="theUser"></param> public virtual void LogOffUser(UserProfileData theUser, string message) { } public void DumpRegionsList(List<string> theList, string desc) { m_log.Info(desc + ":"); foreach (string location in theList) m_log.Info(" " + location); } public List<string> LoadRegionsFromFile(string fileName, string desc) { List<string> newList = new List<string>(); LoadStringListFromFile(newList, fileName, desc); if (newList.Count < 1) m_log.Error("No locations found."); else m_log.InfoFormat("{0} updated with {1} locations.", desc, newList.Count); return newList; } // For new users' first-time logins public void LoadDefaultLoginsFromFile(string fileName) { if (fileName.Length == 0) DumpRegionsList(_DefaultLoginsList, "Default login locations for new users"); else _DefaultLoginsList = LoadRegionsFromFile(fileName, "Default login locations for new users"); } // For returning users' where the preferred region is down public void LoadDefaultRegionsFromFile(string fileName) { if (fileName.Length == 0) DumpRegionsList(_DefaultRegionsList, "Default region locations"); else _DefaultRegionsList = LoadRegionsFromFile(fileName, "Default region locations"); } private HashSet<string> _loginsProcessing = new HashSet<string>(); /// <summary> /// Called when we receive the client's initial XMLRPC login_to_simulator request message /// </summary> /// <param name="request">The XMLRPC request</param> /// <returns>The response to send</returns> public virtual XmlRpcResponse XmlRpcLoginMethod(XmlRpcRequest request, IPEndPoint remoteClient) { string loginUsername = null; try { XmlRpcResponse response = new XmlRpcResponse(); Hashtable requestData = (Hashtable)request.Params[0]; SniffLoginKey((Uri)request.Params[2], requestData); bool GoodXML = (requestData.Contains("first") && requestData.Contains("last") && (requestData.Contains("passwd") || requestData.Contains("web_login_key"))); string firstname = null; string lastname = null; LoginResponse logResponse = new LoginResponse(); if (GoodXML) { //make sure the user isn't already trying to log in firstname = (string)requestData["first"]; lastname = (string)requestData["last"]; loginUsername = firstname + " " + lastname; lock (_loginsProcessing) { if (_loginsProcessing.Contains(loginUsername)) { return logResponse.CreateAlreadyLoggedInResponse(); } else { _loginsProcessing.Add(loginUsername); } } } string startLocationRequest = "last"; UserProfileData userProfile; string clientVersion = "Unknown"; if (GoodXML) { if (requestData.Contains("start")) { startLocationRequest = (string)requestData["start"]; } m_log.InfoFormat( "[LOGIN BEGIN]: XMLRPC Received login request message from user '{0}' '{1}'", firstname, lastname); if (requestData.Contains("version")) { clientVersion = (string)requestData["version"]; } if (this.IsViewerBlacklisted(clientVersion)) { m_log.DebugFormat("[LOGIN]: Denying login, Client {0} is blacklisted", clientVersion); return logResponse.CreateViewerNotAllowedResponse(); } m_log.DebugFormat( "[LOGIN]: XMLRPC Client is {0}, start location is {1}", clientVersion, startLocationRequest); if (!TryAuthenticateXmlRpcLogin(request, firstname, lastname, out userProfile)) { return logResponse.CreateLoginFailedResponse(); } } else { m_log.Info("[LOGIN END]: XMLRPC login_to_simulator login message did not contain all the required data"); return logResponse.CreateGridErrorResponse(); } if (userProfile.GodLevel < m_minLoginLevel) { return logResponse.CreateLoginBlockedResponse(); } else { // If we already have a session... if (userProfile.CurrentAgent != null && userProfile.CurrentAgent.AgentOnline) { // Force a refresh for this due to Commit below UUID userID = userProfile.ID; m_userManager.PurgeUserFromCaches(userID); userProfile = m_userManager.GetUserProfile(userID); // on an error, return the former error we returned before recovery was supported. if (userProfile == null) return logResponse.CreateAlreadyLoggedInResponse(); //TODO: The following statements can cause trouble: // If agentOnline could not turn from true back to false normally // because of some problem, for instance, the crashment of server or client, // the user cannot log in any longer. userProfile.CurrentAgent.AgentOnline = false; userProfile.CurrentAgent.LogoutTime = Util.UnixTimeSinceEpoch(); m_userManager.CommitAgent(ref userProfile); // try to tell the region that their user is dead. LogOffUser(userProfile, " XMLRPC You were logged off because you logged in from another location"); // Don't reject the login. We've already cleaned it up, above. m_log.InfoFormat( "[LOGIN END]: XMLRPC Reset user {0} {1} that we believe is already logged in", firstname, lastname); // return logResponse.CreateAlreadyLoggedInResponse(); } // Otherwise... // Create a new agent session m_userManager.ResetAttachments(userProfile.ID); CreateAgent(userProfile, request); // We need to commit the agent right here, even though the userProfile info is not complete // at this point. There is another commit further down. // This is for the new sessionID to be stored so that the region can check it for session authentication. // CustomiseResponse->PrepareLoginToRegion CommitAgent(ref userProfile); try { UUID agentID = userProfile.ID; InventoryData inventData = null; try { inventData = GetInventorySkeleton(agentID); } catch (Exception e) { m_log.ErrorFormat( "[LOGIN END]: Error retrieving inventory skeleton of agent {0} - {1}", agentID, e); return logResponse.CreateLoginInventoryFailedResponse(); } if (inventData != null) { ArrayList AgentInventoryArray = inventData.InventoryArray; Hashtable InventoryRootHash = new Hashtable(); InventoryRootHash["folder_id"] = inventData.RootFolderID.ToString(); ArrayList InventoryRoot = new ArrayList(); InventoryRoot.Add(InventoryRootHash); userProfile.RootInventoryFolderID = inventData.RootFolderID; logResponse.InventoryRoot = InventoryRoot; logResponse.InventorySkeleton = AgentInventoryArray; } // Inventory Library Section Hashtable InventoryLibRootHash = new Hashtable(); InventoryLibRootHash["folder_id"] = "00000112-000f-0000-0000-000100bba000"; ArrayList InventoryLibRoot = new ArrayList(); InventoryLibRoot.Add(InventoryLibRootHash); logResponse.InventoryLibRoot = InventoryLibRoot; logResponse.InventoryLibraryOwner = GetLibraryOwner(); logResponse.InventoryLibrary = GetInventoryLibrary(); logResponse.CircuitCode = Util.RandomClass.Next(); logResponse.Lastname = userProfile.SurName; logResponse.Firstname = userProfile.FirstName; logResponse.AgentID = agentID; logResponse.SessionID = userProfile.CurrentAgent.SessionID; logResponse.SecureSessionID = userProfile.CurrentAgent.SecureSessionID; logResponse.Message = GetMessage(); logResponse.MapServerURI = m_MapServerURI; logResponse.BuddList = ConvertFriendListItem(m_userManager.GetUserFriendList(agentID)); logResponse.StartLocation = startLocationRequest; // m_log.WarnFormat("[LOGIN END]: >>> Login response for {0} SSID={1}", logResponse.AgentID, logResponse.SecureSessionID); if (CustomiseResponse(logResponse, userProfile, startLocationRequest, clientVersion)) { userProfile.LastLogin = userProfile.CurrentAgent.LoginTime; CommitAgent(ref userProfile); // If we reach this point, then the login has successfully logged onto the grid if (StatsManager.UserStats != null) StatsManager.UserStats.AddSuccessfulLogin(); m_log.DebugFormat( "[LOGIN END]: XMLRPC Authentication of user {0} {1} successful. Sending response to client.", firstname, lastname); return logResponse.ToXmlRpcResponse(); } else { m_log.ErrorFormat("[LOGIN END]: XMLRPC informing user {0} {1} that login failed due to an unavailable region", firstname, lastname); return logResponse.CreateDeadRegionResponse(); } } catch (Exception e) { m_log.Error("[LOGIN END]: XMLRPC Login failed, " + e); m_log.Error(e.StackTrace); } } m_log.Info("[LOGIN END]: XMLRPC Login failed. Sending back blank XMLRPC response"); return response; } finally { if (loginUsername != null) { lock (_loginsProcessing) { _loginsProcessing.Remove(loginUsername); } } } } private bool IsViewerBlacklisted(string clientVersion) { foreach (string badClient in _badViewerStrings) { if (clientVersion.Contains(badClient)) { return true; } } return false; } protected virtual bool TryAuthenticateXmlRpcLogin( XmlRpcRequest request, string firstname, string lastname, out UserProfileData userProfile) { Hashtable requestData = (Hashtable)request.Params[0]; bool GoodLogin = false; userProfile = GetTheUser(firstname, lastname); if (userProfile == null) { m_log.Info("[LOGIN END]: XMLRPC Could not find a profile for " + firstname + " " + lastname); } else { if (requestData.Contains("passwd")) { string passwd = (string)requestData["passwd"]; GoodLogin = AuthenticateUser(userProfile, passwd); } if (!GoodLogin && (requestData.Contains("web_login_key"))) { try { UUID webloginkey = new UUID((string)requestData["web_login_key"]); GoodLogin = AuthenticateUser(userProfile, webloginkey); } catch (Exception e) { m_log.InfoFormat( "[LOGIN END]: XMLRPC Bad web_login_key: {0} for user {1} {2}, exception {3}", requestData["web_login_key"], firstname, lastname, e); } } } return GoodLogin; } protected virtual bool TryAuthenticateLLSDLogin(string firstname, string lastname, string passwd, out UserProfileData userProfile) { bool GoodLogin = false; userProfile = GetTheUser(firstname, lastname); if (userProfile == null) { m_log.Info("[LOGIN]: LLSD Could not find a profile for " + firstname + " " + lastname); return false; } GoodLogin = AuthenticateUser(userProfile, passwd); return GoodLogin; } public Hashtable ProcessHTMLLogin(Hashtable keysvals) { // Matches all unspecified characters // Currently specified,; lowercase letters, upper case letters, numbers, underline // period, space, parens, and dash. Regex wfcut = new Regex("[^a-zA-Z0-9_\\.\\$ \\(\\)\\-]"); Hashtable returnactions = new Hashtable(); int statuscode = 200; string firstname = String.Empty; string lastname = String.Empty; string location = String.Empty; string region = String.Empty; string grid = String.Empty; string channel = String.Empty; string version = String.Empty; string lang = String.Empty; string password = String.Empty; string errormessages = String.Empty; // the client requires the HTML form field be named 'username' // however, the data it sends when it loads the first time is 'firstname' // another one of those little nuances. if (keysvals.Contains("firstname")) firstname = wfcut.Replace((string)keysvals["firstname"], String.Empty, 99999); if (keysvals.Contains("username")) firstname = wfcut.Replace((string)keysvals["username"], String.Empty, 99999); if (keysvals.Contains("lastname")) lastname = wfcut.Replace((string)keysvals["lastname"], String.Empty, 99999); if (keysvals.Contains("location")) location = wfcut.Replace((string)keysvals["location"], String.Empty, 99999); if (keysvals.Contains("region")) region = wfcut.Replace((string)keysvals["region"], String.Empty, 99999); if (keysvals.Contains("grid")) grid = wfcut.Replace((string)keysvals["grid"], String.Empty, 99999); if (keysvals.Contains("channel")) channel = wfcut.Replace((string)keysvals["channel"], String.Empty, 99999); if (keysvals.Contains("version")) version = wfcut.Replace((string)keysvals["version"], String.Empty, 99999); if (keysvals.Contains("lang")) lang = wfcut.Replace((string)keysvals["lang"], String.Empty, 99999); if (keysvals.Contains("password")) password = wfcut.Replace((string)keysvals["password"], String.Empty, 99999); // load our login form. string loginform = GetLoginForm(firstname, lastname, location, region, grid, channel, version, lang, password, errormessages); if (keysvals.ContainsKey("show_login_form")) { UserProfileData user = GetTheUser(firstname, lastname); bool goodweblogin = false; if (user != null) goodweblogin = AuthenticateUser(user, password); if (goodweblogin) { UUID webloginkey = UUID.Random(); m_userManager.StoreWebLoginKey(user.ID, webloginkey); //statuscode = 301; // string redirectURL = "about:blank?redirect-http-hack=" + // HttpUtility.UrlEncode("secondlife:///app/login?first_name=" + firstname + "&last_name=" + // lastname + // "&location=" + location + "&grid=Other&web_login_key=" + webloginkey.ToString()); //m_log.Info("[WEB]: R:" + redirectURL); returnactions["int_response_code"] = statuscode; //returnactions["str_redirect_location"] = redirectURL; //returnactions["str_response_string"] = "<HTML><BODY>GoodLogin</BODY></HTML>"; returnactions["str_response_string"] = webloginkey.ToString(); } else { errormessages = "The Username and password supplied did not match our records. Check your caps lock and try again"; loginform = GetLoginForm(firstname, lastname, location, region, grid, channel, version, lang, password, errormessages); returnactions["int_response_code"] = statuscode; returnactions["str_response_string"] = loginform; } } else { returnactions["int_response_code"] = statuscode; returnactions["str_response_string"] = loginform; } return returnactions; } public string GetLoginForm(string firstname, string lastname, string location, string region, string grid, string channel, string version, string lang, string password, string errormessages) { // inject our values in the form at the markers string loginform = String.Empty; string file = Path.Combine(Util.configDir(), "http_loginform.html"); if (!File.Exists(file)) { loginform = GetDefaultLoginForm(); } else { StreamReader sr = File.OpenText(file); loginform = sr.ReadToEnd(); sr.Close(); } loginform = loginform.Replace("[$firstname]", firstname); loginform = loginform.Replace("[$lastname]", lastname); loginform = loginform.Replace("[$location]", location); loginform = loginform.Replace("[$region]", region); loginform = loginform.Replace("[$grid]", grid); loginform = loginform.Replace("[$channel]", channel); loginform = loginform.Replace("[$version]", version); loginform = loginform.Replace("[$lang]", lang); loginform = loginform.Replace("[$password]", password); loginform = loginform.Replace("[$errors]", errormessages); return loginform; } public string GetDefaultLoginForm() { string responseString = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"; responseString += "<html xmlns=\"http://www.w3.org/1999/xhtml\">"; responseString += "<head>"; responseString += "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"; responseString += "<meta http-equiv=\"cache-control\" content=\"no-cache\">"; responseString += "<meta http-equiv=\"Pragma\" content=\"no-cache\">"; responseString += "<title>InWorldz Login</title>"; responseString += "<body><br />"; responseString += "<div id=\"login_box\">"; responseString += "<form action=\"/go.cgi\" method=\"GET\" id=\"login-form\">"; responseString += "<div id=\"message\">[$errors]</div>"; responseString += "<fieldset id=\"firstname\">"; responseString += "<legend>First Name:</legend>"; responseString += "<input type=\"text\" id=\"firstname_input\" size=\"15\" maxlength=\"100\" name=\"username\" value=\"[$firstname]\" />"; responseString += "</fieldset>"; responseString += "<fieldset id=\"lastname\">"; responseString += "<legend>Last Name:</legend>"; responseString += "<input type=\"text\" size=\"15\" maxlength=\"100\" name=\"lastname\" value=\"[$lastname]\" />"; responseString += "</fieldset>"; responseString += "<fieldset id=\"password\">"; responseString += "<legend>Password:</legend>"; responseString += "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">"; responseString += "<tr>"; responseString += "<td colspan=\"2\"><input type=\"password\" size=\"15\" maxlength=\"100\" name=\"password\" value=\"[$password]\" /></td>"; responseString += "</tr>"; responseString += "<tr>"; responseString += "<td valign=\"middle\"><input type=\"checkbox\" name=\"remember_password\" id=\"remember_password\" [$remember_password] style=\"margin-left:0px;\"/></td>"; responseString += "<td><label for=\"remember_password\">Remember password</label></td>"; responseString += "</tr>"; responseString += "</table>"; responseString += "</fieldset>"; responseString += "<input type=\"hidden\" name=\"show_login_form\" value=\"FALSE\" />"; responseString += "<input type=\"hidden\" name=\"method\" value=\"login\" />"; responseString += "<input type=\"hidden\" id=\"grid\" name=\"grid\" value=\"[$grid]\" />"; responseString += "<input type=\"hidden\" id=\"region\" name=\"region\" value=\"[$region]\" />"; responseString += "<input type=\"hidden\" id=\"location\" name=\"location\" value=\"[$location]\" />"; responseString += "<input type=\"hidden\" id=\"channel\" name=\"channel\" value=\"[$channel]\" />"; responseString += "<input type=\"hidden\" id=\"version\" name=\"version\" value=\"[$version]\" />"; responseString += "<input type=\"hidden\" id=\"lang\" name=\"lang\" value=\"[$lang]\" />"; responseString += "<div id=\"submitbtn\">"; responseString += "<input class=\"input_over\" type=\"submit\" value=\"Connect\" />"; responseString += "</div>"; responseString += "<div id=\"connecting\" style=\"visibility:hidden\"> Connecting...</div>"; responseString += "<div id=\"helplinks\"><!---"; responseString += "<a href=\"#join now link\" target=\"_blank\"></a> | "; responseString += "<a href=\"#forgot password link\" target=\"_blank\"></a>"; responseString += "---></div>"; responseString += "<div id=\"channelinfo\"> [$channel] | [$version]=[$lang]</div>"; responseString += "</form>"; responseString += "<script language=\"JavaScript\">"; responseString += "document.getElementById('firstname_input').focus();"; responseString += "</script>"; responseString += "</div>"; responseString += "</div>"; responseString += "</body>"; responseString += "</html>"; return responseString; } /// <summary> /// Saves a target agent to the database /// </summary> /// <param name="profile">The users profile</param> /// <returns>Successful?</returns> public bool CommitAgent(ref UserProfileData profile) { return m_userManager.CommitAgent(ref profile); } /// <summary> /// Checks a user against it's password hash /// </summary> /// <param name="profile">The users profile</param> /// <param name="password">The supplied password</param> /// <returns>Authenticated?</returns> public virtual bool AuthenticateUser(UserProfileData profile, string password) { bool passwordSuccess = false; //m_log.InfoFormat("[LOGIN]: Authenticating {0} {1} ({2})", profile.FirstName, profile.SurName, profile.ID); // Web Login method seems to also occasionally send the hashed password itself // we do this to get our hash in a form that the server password code can consume // when the web-login-form submits the password in the clear (supposed to be over SSL!) if (!password.StartsWith("$1$")) password = "$1$" + Util.Md5Hash(password); password = password.Remove(0, 3); //remove $1$ string s = Util.Md5Hash(password + ":" + profile.PasswordSalt); // Testing... //m_log.Info("[LOGIN]: SubHash:" + s + " userprofile:" + profile.passwordHash); //m_log.Info("[LOGIN]: userprofile:" + profile.passwordHash + " SubCT:" + password); passwordSuccess = (profile.PasswordHash.Equals(s.ToString(), StringComparison.InvariantCultureIgnoreCase) || profile.PasswordHash.Equals(password, StringComparison.InvariantCultureIgnoreCase)); return passwordSuccess; } public virtual bool AuthenticateUser(UserProfileData profile, UUID webloginkey) { bool passwordSuccess = false; m_log.InfoFormat("[LOGIN]: Authenticating {0} {1} ({2})", profile.FirstName, profile.SurName, profile.ID); // Match web login key unless it's the default weblogin key UUID.Zero passwordSuccess = ((profile.WebLoginKey == webloginkey) && profile.WebLoginKey != UUID.Zero); return passwordSuccess; } /// <summary> /// /// </summary> /// <param name="profile"></param> /// <param name="request"></param> public void CreateAgent(UserProfileData profile, XmlRpcRequest request) { m_userManager.CreateAgent(profile, request); } public void CreateAgent(UserProfileData profile, OSD request) { m_userManager.CreateAgent(profile, request); } /// <summary> /// /// </summary> /// <param name="firstname"></param> /// <param name="lastname"></param> /// <returns></returns> public virtual UserProfileData GetTheUser(string firstname, string lastname) { return m_userManager.GetUserProfile(firstname, lastname); } /// <summary> /// /// </summary> /// <returns></returns> public virtual string GetMessage() { return m_welcomeMessage; } private static LoginResponse.BuddyList ConvertFriendListItem(List<FriendListItem> LFL) { LoginResponse.BuddyList buddylistreturn = new LoginResponse.BuddyList(); foreach (FriendListItem fl in LFL) { LoginResponse.BuddyList.BuddyInfo buddyitem = new LoginResponse.BuddyList.BuddyInfo(fl.Friend); buddyitem.BuddyID = fl.Friend; buddyitem.BuddyRightsHave = (int)fl.FriendListOwnerPerms; buddyitem.BuddyRightsGiven = (int)fl.FriendPerms; buddylistreturn.AddNewBuddy(buddyitem); } return buddylistreturn; } /// <summary> /// Converts the inventory library skeleton into the form required by the rpc request. /// </summary> /// <returns></returns> protected virtual ArrayList GetInventoryLibrary() { Dictionary<UUID, InventoryFolderImpl> rootFolders = m_libraryRootFolder.RequestSelfAndDescendentFolders(); ArrayList folderHashes = new ArrayList(); foreach (InventoryFolderBase folder in rootFolders.Values) { Hashtable TempHash = new Hashtable(); TempHash["name"] = folder.Name; TempHash["parent_id"] = folder.ParentID.ToString(); TempHash["version"] = (Int32)folder.Version; TempHash["type_default"] = (Int32)folder.Type; TempHash["folder_id"] = folder.ID.ToString(); folderHashes.Add(TempHash); } return folderHashes; } /// <summary> /// /// </summary> /// <returns></returns> protected virtual ArrayList GetLibraryOwner() { //for now create random inventory library owner Hashtable TempHash = new Hashtable(); TempHash["agent_id"] = "11111111-1111-0000-0000-000100bba000"; ArrayList inventoryLibOwner = new ArrayList(); inventoryLibOwner.Add(TempHash); return inventoryLibOwner; } public class InventoryData { public ArrayList InventoryArray = null; public UUID RootFolderID = UUID.Zero; public InventoryData(ArrayList invList, UUID rootID) { InventoryArray = invList; RootFolderID = rootID; } } protected void SniffLoginKey(Uri uri, Hashtable requestData) { string uri_str = uri.ToString(); string[] parts = uri_str.Split(new char[] { '=' }); if (parts.Length > 1) { string web_login_key = parts[1]; requestData.Add("web_login_key", web_login_key); m_log.InfoFormat("[LOGIN]: Login with web_login_key {0}", web_login_key); } } protected bool PrepareLoginToREURI(Regex reURI, LoginResponse response, UserProfileData theUser, string startLocationRequest, string StartLocationType, string desc, string clientVersion) { string region; RegionInfo regionInfo = null; Match uriMatch = reURI.Match(startLocationRequest); if (uriMatch == null) { m_log.InfoFormat("[LOGIN]: Got {0} {1}, but can't process it", desc, startLocationRequest); return false; } region = uriMatch.Groups["region"].ToString(); regionInfo = RequestClosestRegion(region); if (regionInfo == null) { m_log.InfoFormat("[LOGIN]: Got {0} {1}, can't locate region {2}", desc, startLocationRequest, region); return false; } theUser.CurrentAgent.Position = new Vector3(float.Parse(uriMatch.Groups["x"].Value), float.Parse(uriMatch.Groups["y"].Value), float.Parse(uriMatch.Groups["z"].Value)); response.LookAt = "[r0,r1,r0]"; // can be: last, home, safe, url response.StartLocation = StartLocationType; return PrepareLoginToRegion(regionInfo, theUser, response, clientVersion); } protected bool PrepareNextRegion(LoginResponse response, UserProfileData theUser, List<string> theList, string startLocationRequest, string clientVersion) { Regex reURI = new Regex(@"^(?<region>[^&]+)/(?<x>\d+)/(?<y>\d+)/(?<z>\d+)$"); if ((startLocationRequest != "home") && (startLocationRequest != "last")) startLocationRequest = "safe"; foreach (string location in theList) { if (PrepareLoginToREURI(reURI, response, theUser, location, "safe", "default region", clientVersion)) return true; } return false; } // For new users' first-time logins protected bool PrepareNextDefaultLogin(LoginResponse response, UserProfileData theUser, string startLocationRequest, string clientVersion) { return PrepareNextRegion(response, theUser, _DefaultLoginsList, startLocationRequest, clientVersion); } // For returning users' where the preferred region is down protected bool PrepareNextDefaultRegion(LoginResponse response, UserProfileData theUser, string clientVersion) { return PrepareNextRegion(response, theUser, _DefaultRegionsList, "safe", clientVersion); } /// <summary> /// Customises the login response and fills in missing values. This method also tells the login region to /// expect a client connection. /// </summary> /// <param name="response">The existing response</param> /// <param name="theUser">The user profile</param> /// <param name="startLocationRequest">The requested start location</param> /// <returns>true on success, false if the region was not successfully told to expect a user connection</returns> public bool CustomiseResponse(LoginResponse response, UserProfileData theUser, string startLocationRequest, string clientVersion) { // add active gestures to login-response AddActiveGestures(response, theUser); // HomeLocation RegionInfo homeInfo = null; // use the homeRegionID if it is stored already. If not, use the regionHandle as before UUID homeRegionId = theUser.HomeRegionID; ulong homeRegionHandle = theUser.HomeRegion; if (homeRegionId != UUID.Zero) { homeInfo = GetRegionInfo(homeRegionId); } else { homeInfo = GetRegionInfo(homeRegionHandle); } if (homeInfo != null) { response.Home = string.Format( "{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}", (homeInfo.RegionLocX * Constants.RegionSize), (homeInfo.RegionLocY * Constants.RegionSize), theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z, theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z); } else { m_log.InfoFormat("not found the region at {0} {1}", theUser.HomeRegionX, theUser.HomeRegionY); // Emergency mode: Home-region isn't available, so we can't request the region info. // Use the stored home regionHandle instead. // NOTE: If the home-region moves, this will be wrong until the users update their user-profile again ulong regionX = homeRegionHandle >> 32; ulong regionY = homeRegionHandle & 0xffffffff; response.Home = string.Format( "{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}", regionX, regionY, theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z, theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z); m_log.InfoFormat("[LOGIN] Home region of user {0} {1} is not available; using computed region position {2} {3}", theUser.FirstName, theUser.SurName, regionX, regionY); } // StartLocation RegionInfo regionInfo = null; if (theUser.LastLogin == 0) { // New user first login if (PrepareNextDefaultLogin(response, theUser, startLocationRequest, clientVersion)) return true; } else { // Returning user login if (startLocationRequest == "home") { regionInfo = homeInfo; theUser.CurrentAgent.Position = theUser.HomeLocation; response.LookAt = String.Format("[r{0},r{1},r{2}]", theUser.HomeLookAt.X.ToString(), theUser.HomeLookAt.Y.ToString(), theUser.HomeLookAt.Z.ToString()); } else if (startLocationRequest == "last") { UUID lastRegion = theUser.CurrentAgent.Region; regionInfo = GetRegionInfo(lastRegion); response.LookAt = String.Format("[r{0},r{1},r{2}]", theUser.CurrentAgent.LookAt.X.ToString(), theUser.CurrentAgent.LookAt.Y.ToString(), theUser.CurrentAgent.LookAt.Z.ToString()); } else { // Logging in to a specific URL... try to find the region Regex reURI = new Regex(@"^uri:(?<region>[^&]+)&(?<x>\d+)&(?<y>\d+)&(?<z>\d+)$"); if (PrepareLoginToREURI(reURI, response, theUser, startLocationRequest, "url", "Custom Login URL", clientVersion)) return true; } // Logging in to home or last... try to find the region if ((regionInfo != null) && (PrepareLoginToRegion(regionInfo, theUser, response, clientVersion))) { return true; } // StartLocation not available, send him to a nearby region instead // regionInfo = m_gridService.RequestClosestRegion(""); //m_log.InfoFormat("[LOGIN]: StartLocation not available sending to region {0}", regionInfo.regionName); // Normal login failed, try to find a default region from the list if (PrepareNextDefaultRegion(response, theUser, clientVersion)) return true; } // No default regions available either. // Send him to global default region home location instead (e.g. 1000,1000) ulong defaultHandle = (((ulong)m_defaultHomeX * Constants.RegionSize) << 32) | ((ulong)m_defaultHomeY * Constants.RegionSize); if ((regionInfo != null) && (defaultHandle == regionInfo.RegionHandle)) { m_log.ErrorFormat("[LOGIN]: Not trying the default region since this is the same as the selected region"); return false; } m_log.Error("[LOGIN]: Sending user to default region " + defaultHandle + " instead"); regionInfo = GetRegionInfo(defaultHandle); if (regionInfo == null) { m_log.ErrorFormat("[LOGIN]: No default region available. Aborting."); return false; } theUser.CurrentAgent.Position = new Vector3(128, 128, 0); response.StartLocation = "safe"; return PrepareLoginToRegion(regionInfo, theUser, response, clientVersion); } protected const string COF_NAME = "Current Outfit"; protected bool FixCurrentOutFitFolder(UUID user, ref AvatarAppearance avappearance) { IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>(); IInventoryStorage inventoryService = inventorySelect.GetProvider(user); InventoryFolderBase CurrentOutfitFolder = null; bool changed = false; try { CurrentOutfitFolder = inventoryService.FindFolderForType(user, AssetType.CurrentOutfitFolder); } catch (InventoryStorageException) { // could not find it by type. load root and try to find it by name. InventorySubFolderBase foundFolder = null; InventoryFolderBase rootFolder = inventoryService.FindFolderForType(user, AssetType.RootFolder); foreach (var subfolder in rootFolder.SubFolders) { if (subfolder.Name == COF_NAME) { foundFolder = subfolder; break; } } if (foundFolder != null) { CurrentOutfitFolder = inventoryService.GetFolder(foundFolder.ID); if (CurrentOutfitFolder != null) { CurrentOutfitFolder.Level = InventoryFolderBase.FolderLevel.TopLevel; inventoryService.SaveFolder(CurrentOutfitFolder); } } } if (CurrentOutfitFolder == null) return false; List<InventoryItemBase> ic = inventoryService.GetFolder(CurrentOutfitFolder.ID).Items; List<InventoryItemBase> brokenLinks = new List<InventoryItemBase>(); List<UUID> OtherStuff = new List<UUID>(); List<AvatarWearable> wearables = avappearance.GetWearables(); foreach (var i in ic) { InventoryItemBase linkedItem = null; try { linkedItem = inventoryService.GetItem(i.AssetID, UUID.Zero); } catch (InventoryStorageException) { linkedItem = null; } if (linkedItem == null) brokenLinks.Add(i); else if (linkedItem.ID == AvatarWearable.DEFAULT_EYES_ITEM || linkedItem.ID == AvatarWearable.DEFAULT_BODY_ITEM || linkedItem.ID == AvatarWearable.DEFAULT_HAIR_ITEM || linkedItem.ID == AvatarWearable.DEFAULT_PANTS_ITEM || linkedItem.ID == AvatarWearable.DEFAULT_SHIRT_ITEM || linkedItem.ID == AvatarWearable.DEFAULT_SKIN_ITEM) brokenLinks.Add(i); //Default item link, needs removed else if (wearables.Find((w)=>w.ItemID == i.AssetID) == null) brokenLinks.Add(i); else if (!OtherStuff.Contains(i.AssetID)) OtherStuff.Add(i.AssetID); else brokenLinks.Add(i); } foreach (AvatarWearable wearable in wearables) { if (wearable.ItemID == UUID.Zero) continue; if (!OtherStuff.Contains(wearable.ItemID)) { InventoryItemBase linkedItem = null; try { linkedItem = inventoryService.GetItem(wearable.ItemID, UUID.Zero); } catch (InventoryStorageException) { linkedItem = null; } if (linkedItem != null) { InventoryItemBase linkedItem3 = (InventoryItemBase)linkedItem.Clone(); linkedItem3.AssetID = linkedItem.ID; linkedItem3.AssetType = (int)AssetType.Link; linkedItem3.ID = UUID.Random(); linkedItem3.CurrentPermissions = linkedItem.NextPermissions; linkedItem3.EveryOnePermissions = linkedItem.NextPermissions; linkedItem3.Folder = CurrentOutfitFolder.ID; inventoryService.CreateItem(linkedItem3); changed = true; } } } List<UUID> items2UnAttach = new List<UUID>(); foreach (int ap in avappearance.GetAttachedPoints()) { foreach (AvatarAttachment attachment in avappearance.GetAttachmentsAtPoint(ap)) { if (attachment.ItemID == UUID.Zero) continue; if (!OtherStuff.Contains(attachment.ItemID)) { changed = true; InventoryItemBase linkedItem = null; try { linkedItem = inventoryService.GetItem(attachment.ItemID, UUID.Zero); } catch (InventoryStorageException) { linkedItem = null; } if(linkedItem != null) { InventoryItemBase linkedItem3 = (InventoryItemBase)linkedItem.Clone(); linkedItem3.AssetID = linkedItem.ID; linkedItem3.AssetType = (int)AssetType.Link; linkedItem3.ID = UUID.Random(); linkedItem3.CurrentPermissions = linkedItem.NextPermissions; linkedItem3.EveryOnePermissions = linkedItem.NextPermissions; linkedItem3.Folder = CurrentOutfitFolder.ID; inventoryService.CreateItem(linkedItem3); } else items2UnAttach.Add(attachment.ItemID); } } } foreach (UUID uuid in items2UnAttach) { avappearance.DetachAttachment(uuid); } if (brokenLinks.Count != 0) inventoryService.PurgeItems(brokenLinks); return changed || brokenLinks.Count > 0; } protected abstract RegionInfo RequestClosestRegion(string region); protected abstract RegionInfo GetRegionInfo(ulong homeRegionHandle); protected abstract RegionInfo GetRegionInfo(UUID homeRegionId); protected abstract bool PrepareLoginToRegion(RegionInfo regionInfo, UserProfileData user, LoginResponse response, string clientVersion); /// <summary> /// Add active gestures of the user to the login response. /// </summary> /// <param name="response"> /// A <see cref="LoginResponse"/> /// </param> /// <param name="theUser"> /// A <see cref="UserProfileData"/> /// </param> protected void AddActiveGestures(LoginResponse response, UserProfileData theUser) { IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>(); IInventoryStorage inventory = inventorySelect.GetProvider(theUser.ID); List<InventoryItemBase> gestures = null; try { gestures = inventory.GetActiveGestureItems(theUser.ID); } catch (Exception e) { m_log.Debug("[LOGIN]: Unable to retrieve active gestures from inventory server. Reason: " + e.Message); } //m_log.DebugFormat("[LOGIN]: AddActiveGestures, found {0}", gestures == null ? 0 : gestures.Count); ArrayList list = new ArrayList(); if (gestures != null) { foreach (InventoryItemBase gesture in gestures) { Hashtable item = new Hashtable(); item["item_id"] = gesture.ID.ToString(); item["asset_id"] = gesture.AssetID.ToString(); list.Add(item); } } response.ActiveGestures = list; } /// <summary> /// Get the initial login inventory skeleton (in other words, the folder structure) for the given user. /// </summary> /// <param name="userID"></param> /// <returns></returns> /// <exception cref='System.Exception'>This will be thrown if there is a problem with the inventory service</exception> protected InventoryData GetInventorySkeleton(UUID userID) { IInventoryProviderSelector inventorySelect = ProviderRegistry.Instance.Get<IInventoryProviderSelector>(); IInventoryStorage inventory = inventorySelect.GetProvider(userID); List<InventoryFolderBase> folders = inventory.GetInventorySkeleton(userID); if (folders == null || folders.Count == 0) { throw new Exception( String.Format( "A root inventory folder for user {0} could not be retrieved from the inventory service", userID)); } UUID rootID = UUID.Zero; ArrayList AgentInventoryArray = new ArrayList(); Hashtable TempHash; foreach (InventoryFolderBase InvFolder in folders) { if (InvFolder.ParentID == UUID.Zero) { rootID = InvFolder.ID; } TempHash = new Hashtable(); TempHash["name"] = InvFolder.Name; TempHash["parent_id"] = InvFolder.ParentID.ToString(); TempHash["version"] = (Int32)InvFolder.Version; TempHash["type_default"] = (Int32)InvFolder.Type; TempHash["folder_id"] = InvFolder.ID.ToString(); AgentInventoryArray.Add(TempHash); } return new InventoryData(AgentInventoryArray, rootID); } protected virtual bool AllowLoginWithoutInventory() { return false; } public XmlRpcResponse XmlRPCCheckAuthSession(XmlRpcRequest request, IPEndPoint remoteClient) { XmlRpcResponse response = new XmlRpcResponse(); Hashtable requestData = (Hashtable)request.Params[0]; string authed = "FALSE"; if (requestData.Contains("avatar_uuid") && requestData.Contains("session_id")) { UUID guess_aid; UUID guess_sid; try { UUID.TryParse((string)requestData["avatar_uuid"], out guess_aid); if (guess_aid == UUID.Zero) { return Util.CreateUnknownUserErrorResponse(); } UUID.TryParse((string)requestData["session_id"], out guess_sid); if (guess_sid == UUID.Zero) { return Util.CreateUnknownUserErrorResponse(); } if (m_userManager.VerifySession(guess_aid, guess_sid)) { authed = "TRUE"; m_log.InfoFormat("[UserManager]: CheckAuthSession TRUE for user {0}", guess_aid); } else { m_log.InfoFormat("[UserManager]: CheckAuthSession FALSE for user {0}, refreshing caches", guess_aid); //purge the cache and retry m_userManager.PurgeUserFromCaches(guess_aid); if (m_userManager.VerifySession(guess_aid, guess_sid)) { authed = "TRUE"; m_log.InfoFormat("[UserManager]: CheckAuthSession TRUE for user {0}", guess_aid); } else { m_log.InfoFormat("[UserManager]: CheckAuthSession FALSE"); return Util.CreateUnknownUserErrorResponse(); } } } catch (Exception e) { m_log.ErrorFormat("[UserManager]: Unable to check auth session: {0}", e); return Util.CreateUnknownUserErrorResponse(); } } Hashtable responseData = new Hashtable(); responseData["auth_session"] = authed; response.Value = responseData; return response; } } }
/* * SubSonic - http://subsonicproject.com * * The contents of this file are subject to the Mozilla Public * License Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. */ using System; namespace SubSonic { /// <summary> /// Summary for the SpecialString class /// </summary> public class SpecialString { public const string AGO = "ago"; public const string DAY = "day"; public const string HOUR = "hour"; public const string MINUTE = "minute"; public const string MONTH = "month"; public const string SECOND = "second"; public const string SPACE = " "; public const string YEAR = "year"; } /// <summary> /// Summary for the TemplateName class /// </summary> public class TemplateName { public const string ENUM = "EnumTemplate"; public const string CLASS = "ClassTemplate"; public const string DYNAMIC_SCAFFOLD = "DynamicScaffold"; public const string GENERATED_SCAFFOLD_CODE_BEHIND = "GeneratedScaffoldCodeBehind"; public const string GENERATED_SCAFFOLD_MARKUP = "GeneratedScaffoldMarkup"; public const string ODS_CONTROLLER = "ODSController"; public const string STORED_PROCEDURE = "SPTemplate"; public const string STRUCTS = "StructsTemplate"; public const string VIEW = "ViewTemplate"; } /// <summary> /// Summary for the TemplateVariable class /// </summary> public class TemplateVariable { public const string ARGUMENT_LIST = "#ARGLIST#"; public const string BIND_LIST = "#BINDLIST#"; public const string CLASS_NAME = "#CLASSNAME#"; public const string CLASS_NAME_COLLECTION = "#CLASSNAMECOLLECTION#"; public const string COLUMNS_STRUCT = "#COLUMNSSTRUCT#"; public const string CONTROL_PROPERTY = "#CONTROLPROPERTY#"; public const string DROP_LIST = "#DROPLIST#"; public const string EDITOR_ROWS = "#EDITORROWS#"; public const string FK_VAR = "#FKVAR#"; public const string FOREIGN_CLASS = "#FOREIGNCLASS#"; public const string FOREIGN_PK = "#FOREIGNPK#"; public const string FOREIGN_TABLE = "#FOREIGNTABLE#"; public const string GETTER = "#GETTER#"; public const string GRID_ROWS = "#GRIDROWS#"; public const string INSERT = "#INSERT#"; public const string JAVASCRIPT_BLOCK = "#JAVASCRIPTBLOCK#"; public const string LANGUAGE = "#LANGUAGE#"; public const string LANGUAGE_EXTENSION = "#LANGEXTENSION#"; public const string MANY_METHODS = "#MANYMETHODS#"; public const string MAP_TABLE = "#MAPTABLE#"; public const string MASTER_PAGE = "#MASTERPAGE#"; public const string METHOD_BODY = "#METHODBODY#"; public const string METHOD_LIST = "#METHODLIST#"; public const string METHOD_NAME = "#METHODNAME#"; public const string METHOD_TYPE = "#METHODTYPE#"; public const string NAMESPACE_USING = "#NAMESPACE_USING#"; public const string PAGE_BIND_LIST = "#PAGEBINDLIST#"; public const string PAGE_CLASS = "#PAGECLASS#"; public const string PAGE_CODE = "#PAGECODE#"; public const string PAGE_FILE = "#PAGEFILE#"; public const string PARAMETERS = "#PARAMS#"; public const string PK = "#PK#"; public const string PK_PROP = "#PKPROP#"; public const string PK_VAR = "#PKVAR#"; public const string PROPERTY_LIST = "#PROPLIST#"; public const string PROPERTY_NAME = "#PROPNAME#"; public const string PROPERTY_TYPE = "#PROPTYPE#"; public const string PROVIDER = "#PROVIDER#"; public const string SET_LIST = "#SETLIST#"; public const string SETTER = "#SETTER#"; public const string STORED_PROCEDURE_NAME = "#SPNAME#"; public const string STRUCT_ASSIGNMENTS = "#STRUCTASSIGNMENTS#"; public const string STRUCT_LIST = "#STRUCTLIST#"; public const string SUMMARY = "#SUMMARY#"; public const string TABLE = "#TABLE#"; public const string TABLE_NAME = "#TABLENAME#"; public const string TABLE_SCHEMA = "#TABLESCHEMA#"; public const string UPDATE = "#UPDATE#"; } /// <summary> /// Summary for the ReservedColumnName class /// </summary> public class ReservedColumnName { public const string CREATED_BY = "CreatedBy"; public const string CREATED_ON = "CreatedOn"; public const string DELETED = "Deleted"; public const string IS_ACTIVE = "IsActive"; public const string IS_DELETED = "IsDeleted"; public const string MODIFIED_BY = "ModifiedBy"; public const string MODIFIED_ON = "ModifiedOn"; } /// <summary> /// Summary for the ConfigurationSectionName class /// </summary> public class ConfigurationSectionName { public const string PROVIDERS = "providers"; public const string SUB_SONIC_SERVICE = "SubSonicService"; } /// <summary> /// Summary for the ConfigurationPropertyName class /// </summary> public class ConfigurationPropertyName { public const string ADDITIONAL_NAMESPACES = "additionalNamespaces"; public const string APPEND_WITH = "appendWith"; public const string CONNECTION_STRING_NAME = "connectionStringName"; public const string DEFAULT_PROVIDER = "defaultProvider"; public const string ENABLE_TRACE = "enableTrace"; public const string EXCLUDE_PROCEDURE_LIST = "excludeProcedureList"; public const string EXCLUDE_TABLE_LIST = "excludeTableList"; public const string ENUM_INCLUDE_LIST = "enumIncludeList"; public const string ENUM_EXCLUDE_LIST = "enumExcludeList"; public const string ENUM_SHOW_DEBUG_INFO = "enumShowDebugInfo"; public const string EXTRACT_CLASS_NAME_FROM_SP_NAME = "extractClassNameFromSPName"; public const string FIX_DATABASE_OBJECT_CASING = "fixDatabaseObjectCasing"; public const string FIX_PLURAL_CLASS_NAMES = "fixPluralClassNames"; public const string GENERATE_LAZY_LOADS = "generateLazyLoads"; public const string GENERATE_NULLABLE_PROPERTIES = "generateNullableProperties"; public const string GENERATE_ODS_CONTROLLERS = "generateODSControllers"; public const string GENERATE_RELATED_TABLES_AS_PROPERTIES = "generateRelatedTablesAsProperties"; public const string GENERATED_NAMESPACE = "generatedNamespace"; public const string INCLUDE_PROCEDURE_LIST = "includeProcedureList"; public const string INCLUDE_TABLE_LIST = "includeTableList"; public const string MANY_TO_MANY_SUFFIX = "manyToManySuffix"; public const string PROVIDER_TO_USE = "provider"; public const string REGEX_DICTIONARY_REPLACE = "regexDictionaryReplace"; public const string REGEX_IGNORE_CASE = "regexIgnoreCase"; public const string REGEX_MATCH_EXPRESSION = "regexMatchExpression"; public const string REGEX_REPLACE_EXPRESSION = "regexReplaceExpression"; public const string RELATED_TABLE_LOAD_PREFIX = "relatedTableLoadPrefix"; public const string REMOVE_UNDERSCORES = "removeUnderscores"; public const string SET_PROPERTY_DEFAULTS_FROM_DATABASE = "setPropertyDefaultsFromDatabase"; public const string SP_STARTS_WITH = "spStartsWith"; public const string STORED_PROCEDURE_BASE_CLASS = "spBaseClass"; public const string STORED_PROCEDURE_CLASS_NAME = "spClassName"; public const string STRIP_COLUMN_TEXT = "stripColumnText"; public const string STRIP_PARAM_TEXT = "stripParamText"; public const string STRIP_STORED_PROCEDURE_TEXT = "stripSPText"; public const string STRIP_TABLE_TEXT = "stripTableText"; public const string STRIP_VIEW_TEXT = "stripViewText"; public const string TABLE_BASE_CLASS = "tableBaseClass"; public const string TEMPLATE_DIRECTORY = "templateDirectory"; public const string USE_EXTENDED_PROPERTIES = "useExtendedProperties"; //SQL 2000/2005 Only public const string USE_STORED_PROCEDURES = "useSPs"; public const string USE_UTC_TIMES = "useUtc"; public const string VIEW_BASE_CLASS = "viewBaseClass"; public const string VIEW_STARTS_WITH = "viewStartsWith"; public const string GROUP_OUTPUT = "groupOutput"; } /// <summary> /// Summary for the DataProviderTypeName class /// </summary> public class DataProviderTypeName { public const string ENTERPRISE_LIBRARY = "ELib3DataProvider"; public const string MY_SQL = "MySqlDataProvider"; public const string ORACLE = "OracleDataProvider"; public const string SQL_CE = "SqlCEProvider"; public const string SQL_SERVER = "SqlDataProvider"; public const string SQLITE = "SQLiteDataProvider"; public const string VISTADB = "VistaDBDataProvider"; public const string MSACCESS = "AccessDataProvider"; } /// <summary> /// Summary for the ClassName class /// </summary> public class ClassName { public const string STORED_PROCEDURES = "SPs"; public const string TABLES = "Tables"; public const string VIEWS = "Views"; } /// <summary> /// Summary for the CodeBlock class /// </summary> public class CodeBlock { public static readonly string JS_BEGIN_SCRIPT = "<script language=\"javascript\" type=\"text/javascript\">" + Environment.NewLine; public static readonly string JS_END_SCRIPT = "</script>" + Environment.NewLine; } /// <summary> /// Summary for the FileExtension class /// </summary> public static class FileExtension { public const string ASPX = "aspx"; public const string CS = "cs"; public const string DOT_ASPX = ".aspx"; public const string DOT_CS = ".cs"; public const string DOT_VB = ".vb"; public const string VB = "vb"; public const string VB_DOT_NET = "vb.net"; } /// <summary> /// Summary for the ControlValueProperty class /// </summary> public class ControlValueProperty { public const string CALENDAR = "SelectedDate"; public const string CHECK_BOX = "Checked"; public const string DROP_DOWN_LIST = "SelectedValue"; public const string LABEL = "Text"; public const string TEXT_BOX = "Text"; } /// <summary> /// /// </summary> public class AggregateFunctionName { public const string AVERAGE = "AVG"; public const string COUNT = "COUNT"; public const string MAX = "MAX"; public const string MIN = "MIN"; public const string SUM = "SUM"; } /// <summary> /// Summary for the SqlFragment class /// </summary> public class SqlFragment { public const string AND = " AND "; public const string AS = " AS "; public const string ASC = " ASC"; public const string BETWEEN = " BETWEEN "; public const string CROSS_JOIN = " CROSS JOIN "; public const string DELETE_FROM = "DELETE FROM "; public const string DESC = " DESC"; public const string DISTINCT = "DISTINCT "; public const string EQUAL_TO = " = "; public const string FROM = " FROM "; public const string GROUP_BY = " GROUP BY "; public const string HAVING = " HAVING "; public const string IN = " IN "; public const string INNER_JOIN = " INNER JOIN "; public const string INSERT_INTO = "INSERT INTO "; public const string JOIN_PREFIX = "J"; public const string LEFT_INNER_JOIN = " LEFT INNER JOIN "; public const string LEFT_JOIN = " LEFT JOIN "; public const string LEFT_OUTER_JOIN = " LEFT OUTER JOIN "; public const string NOT_EQUAL_TO = " <> "; public const string NOT_IN = " NOT IN "; public const string ON = " ON "; public const string OR = " OR "; public const string ORDER_BY = " ORDER BY "; public const string OUTER_JOIN = " OUTER JOIN "; public const string RIGHT_INNER_JOIN = " RIGHT INNER JOIN "; public const string RIGHT_JOIN = " RIGHT JOIN "; public const string RIGHT_OUTER_JOIN = " RIGHT OUTER JOIN "; public const string SELECT = "SELECT "; public const string SET = " SET "; public const string SPACE = " "; public const string TOP = "TOP "; public const string UNEQUAL_JOIN = " JOIN "; public const string UPDATE = "UPDATE "; public const string WHERE = " WHERE "; } /// <summary> /// Summary for the SqlComparison class /// </summary> public class SqlComparison { public const string BLANK = " "; public const string EQUAL = " = "; public const string GREATER = " > "; public const string GREATER_OR_EQUAL = " >= "; public const string IN = " IN "; public const string IS = " IS "; public const string IS_NOT = " IS NOT "; public const string LESS = " < "; public const string LESS_OR_EQUAL = " <= "; public const string LIKE = " LIKE "; public const string NOT_EQUAL = " <> "; public const string NOT_IN = " NOT IN "; public const string NOT_LIKE = " NOT LIKE "; } /// <summary> /// Summary for the SqlSchemaVariable class /// </summary> public class SqlSchemaVariable { public const string COLUMN_DEFAULT = "DefaultSetting"; public const string COLUMN_NAME = "ColumnName"; public const string CONSTRAINT_TYPE = "constraintType"; public const string DATA_TYPE = "DataType"; public const string DEFAULT = "DEFAULT"; public const string FOREIGN_KEY = "FOREIGN KEY"; public const string IS_COMPUTED = "IsComputed"; public const string IS_IDENTITY = "IsIdentity"; public const string IS_NULLABLE = "IsNullable"; public const string MAX_LENGTH = "MaxLength"; public const string MODE = "mode"; public const string MODE_INOUT = "INOUT"; public const string NAME = "Name"; public const string NUMERIC_PRECISION = "NumericPrecision"; public const string NUMERIC_SCALE = "NumericScale"; public const string PARAMETER_PREFIX = "@"; public const string PRIMARY_KEY = "PRIMARY KEY"; public const string TABLE_NAME = "TableName"; } /// <summary> /// Summary for the OracleSchemaVariable class /// </summary> public class OracleSchemaVariable { public const string COLUMN_NAME = "COLUMN_NAME"; public const string CONSTRAINT_TYPE = "CONSTRAINT_TYPE"; public const string DATA_TYPE = "DATA_TYPE"; public const string IS_NULLABLE = "NULLABLE"; public const string MAX_LENGTH = "CHAR_LENGTH"; public const string MODE = "IN_OUT"; public const string MODE_INOUT = "IN/OUT"; public const string NAME = "ARGUMENT_NAME"; public const string NUMBER_PRECISION = "DATA_PRECISION"; public const string NUMBER_SCALE = "DATA_SCALE"; public const string PARAMETER_PREFIX = ":"; public const string TABLE_NAME = "TABLE_NAME"; } /// <summary> /// Summary for the MySqlSchemaVariable class /// </summary> public class MySqlSchemaVariable { public const string PARAMETER_PREFIX = "?"; } /// <summary> /// Summary for the AccessSchemaVariable class /// </summary> public class AccessSchemaVariable { // OleDB Schema Cols public const string TABLE_TYPE = "TABLE_TYPE"; public const string TABLE_NAME = "TABLE_NAME"; public const string COLUMN_NAME = "COLUMN_NAME"; public const string ORDINAL_POSITION = "ORDINAL_POSITION"; public const string DATA_TYPE = "DATA_TYPE"; public const string COLUMN_DEFAULT = "COLUMN_DEFAULT"; public const string MAX_LENGTH = "CHARACTER_MAXIMUM_LENGTH"; public const string IS_NULLABLE = "IS_NULLABLE"; public const string FK_COLUMN_NAME = "FK_COLUMN_NAME"; public const string FK_TABLE_NAME = "FK_TABLE_NAME"; public const string PK_COLUMN_NAME = "PK_COLUMN_NAME"; public const string PK_TABLE_NAME = "PK_TABLE_NAME"; public const string COLUMN_FLAGS = "COLUMN_FLAGS"; public const string PROCEDURE_NAME = "PROCEDURE_NAME"; public const string PROCEDURE_DEF = "PROCEDURE_DEFINITION"; public const string DEFAULT = "DEFAULT"; // Addl Cols manufactured from Access DAO public const string ALLOW_EMPTY_STRING = "ALLOW_EMPTY_STRING"; public const string AUTO_INCREMENT = "AUTO_INCREMENT"; // Addl calculated cols public const string PK_TYPE = "PK_TYPE"; // Stored Proc Columns public const string SP_SCHEMA = "SPSchema"; public const string SP_NAME = "SPName"; public const string SP_PARAM_ORDINALPOS = "OrdinalPosition"; public const string SP_PARAM_MODE = "mode"; public const string SP_PARAM_NAME = "Name"; public const string SP_PARAM_DBDATATYPE = "DataType"; public const string SP_PARAM_DATALENGTH = "DataLength"; public const string SP_PARAM_PREFIX = ""; // Addl cols from external sources public const string EXTPROP_IS_IDENTITY = "ColumnIsAutoNum"; public const string EXTPROP_ALLOW_EMPTYSTRING = "ColumnAllowZeroLengthString"; public const string GEN_PARAM_PREFIX = "PARM__"; } public class AccessSql { public const string GET_INT_IDENTITY = "SELECT @@IDENTITY;"; } /// <summary> /// Summary for the ServerVariable class /// </summary> public class ServerVariable { public const string SERVER_NAME = "SERVER_NAME"; public const string SERVER_PORT = "SERVER_PORT"; public const string SERVER_PORT_SECURE = "SERVER_PORT_SECURE"; } /// <summary> /// Summary for the Ports class /// </summary> public class Ports { public const string HTTP = "80"; public const string HTTPS = "443"; } /// <summary> /// Summary for the ProtocolPrefix class /// </summary> public class ProtocolPrefix { public const string HTTP = "http://"; public const string HTTPS = "https://"; } /// <summary> /// Summary for the CodeFragment class /// </summary> public class CodeFragment { public const string NULLABLE_VARIABLE = "?"; public const string NULLABLE_VARIABLE_VB = "Nullable(Of {0})"; } /// <summary> /// Summary for the ScaffoldCss class /// </summary> public class ScaffoldCss { public const string BUTTON = "scaffoldButton"; public const string CHECK_BOX = "scaffoldCheckBox"; public const string DROP_DOWN = "scaffoldDropDown"; public const string EDIT_ITEM = "scaffoldEditItem"; public const string EDIT_ITEM_CAPTION = "scaffoldEditItemCaption"; public const string EDIT_TABLE = "scaffoldEditTable"; public const string EDIT_TABLE_LABEL = "scaffoldEditTableLabel"; public const string GRID = "scaffoldGrid"; public const string TEXT_BOX = "scaffoldTextBox"; public const string WRAPPER = "scaffoldWrapper"; } /// <summary> /// Summary for the RegexPattern class /// </summary> public class RegexPattern { public const string ALPHA = "[^a-zA-Z]"; public const string ALPHA_NUMERIC = "[^a-zA-Z0-9]"; public const string ALPHA_NUMERIC_SPACE = @"[^a-zA-Z0-9\s]"; public const string CREDIT_CARD_AMERICAN_EXPRESS = @"^(?:(?:[3][4|7])(?:\d{13}))$"; public const string CREDIT_CARD_CARTE_BLANCHE = @"^(?:(?:[3](?:[0][0-5]|[6|8]))(?:\d{11,12}))$"; public const string CREDIT_CARD_DINERS_CLUB = @"^(?:(?:[3](?:[0][0-5]|[6|8]))(?:\d{11,12}))$"; public const string CREDIT_CARD_DISCOVER = @"^(?:(?:6011)(?:\d{12}))$"; public const string CREDIT_CARD_EN_ROUTE = @"^(?:(?:[2](?:014|149))(?:\d{11}))$"; public const string CREDIT_CARD_JCB = @"^(?:(?:(?:2131|1800)(?:\d{11}))$|^(?:(?:3)(?:\d{15})))$"; public const string CREDIT_CARD_MASTER_CARD = @"^(?:(?:[5][1-5])(?:\d{14}))$"; public const string CREDIT_CARD_STRIP_NON_NUMERIC = @"(\-|\s|\D)*"; public const string CREDIT_CARD_VISA = @"^(?:(?:[4])(?:\d{12}|\d{15}))$"; public const string EMAIL = @"^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$"; public const string EMBEDDED_CLASS_NAME_MATCH = "(?<=^_).*?(?=_)"; public const string EMBEDDED_CLASS_NAME_REPLACE = "^_.*?_"; public const string EMBEDDED_CLASS_NAME_UNDERSCORE_MATCH = "(?<=^UNDERSCORE).*?(?=UNDERSCORE)"; public const string EMBEDDED_CLASS_NAME_UNDERSCORE_REPLACE = "^UNDERSCORE.*?UNDERSCORE"; public const string GUID = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"; public const string IP_ADDRESS = @"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"; public const string LOWER_CASE = @"^[a-z]+$"; public const string NUMERIC = "[^0-9]"; public const string SOCIAL_SECURITY = @"^\d{3}[-]?\d{2}[-]?\d{4}$"; public const string SQL_EQUAL = @"\="; public const string SQL_GREATER = @"\>"; public const string SQL_GREATER_OR_EQUAL = @"\>.*\="; public const string SQL_IS = @"\x20is\x20"; public const string SQL_IS_NOT = @"\x20is\x20not\x20"; public const string SQL_LESS = @"\<"; public const string SQL_LESS_OR_EQUAL = @"\<.*\="; public const string SQL_LIKE = @"\x20like\x20"; public const string SQL_NOT_EQUAL = @"\<.*\>"; public const string SQL_NOT_LIKE = @"\x20not\x20like\x20"; public const string STRONG_PASSWORD = @"(?=^.{8,255}$)((?=.*\d)(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[^A-Za-z0-9])(?=.*[a-z])|(?=.*[^A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9]))^.*"; public const string UPPER_CASE = @"^[A-Z]+$"; public const string URL = @"^^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_=]*)?$"; public const string US_CURRENCY = @"^\$(([1-9]\d*|([1-9]\d{0,2}(\,\d{3})*))(\.\d{1,2})?|(\.\d{1,2}))$|^\$[0](.00)?$"; public const string US_TELEPHONE = @"^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$"; public const string US_ZIPCODE = @"^\d{5}$"; public const string US_ZIPCODE_PLUS_FOUR = @"^\d{5}((-|\s)?\d{4})$"; public const string US_ZIPCODE_PLUS_FOUR_OPTIONAL = @"^\d{5}((-|\s)?\d{4})?$"; } /// <summary> /// Summary for the ExtendedPropertyName class /// </summary> public class ExtendedPropertyName { public const string SSX_COLUMN_BINARY_FILE_EXTENSION = "SSX_COLUMN_BINARY_FILE_EXTENSION"; public const string SSX_COLUMN_DISPLAY_NAME = "SSX_COLUMN_DISPLAY_NAME"; public const string SSX_COLUMN_PROPERTY_NAME = "SSX_COLUMN_PROPERTY_NAME"; public const string SSX_TABLE_CLASS_NAME_PLURAL = "SSX_TABLE_CLASS_NAME_PLURAL"; public const string SSX_TABLE_CLASS_NAME_SINGULAR = "SSX_TABLE_CLASS_NAME_SINGULAR"; public const string SSX_TABLE_DISPLAY_NAME = "SSX_TABLE_DISPLAY_NAME"; } }
/* * 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 ParquetSharp.Example.Data; using ParquetSharp.Filter2.Compat; using ParquetSharp.Filter2.Predicate; using ParquetSharp.IO.Api; using Xunit; using static ParquetHadoopTests.Filter2.RecordLevel.PhoneBookWriter; using static ParquetSharp.Filter2.Predicate.FilterApi; using static ParquetSharp.Filter2.Predicate.Operators; namespace ParquetHadoopTests.Filter2.RecordLevel { public class TestRecordLevelFilters { public static List<User> makeUsers() { List<User> users = new List<User>(); users.Add(new User(17, null, null, null)); users.Add(new User(18, "bob", null, null)); users.Add(new User(19, "alice", new List<PhoneNumber>(), null)); users.Add(new User(20, "thing1", new List<PhoneNumber> { new PhoneNumber(5555555555L, null) }, null)); users.Add(new User(27, "thing2", new List<PhoneNumber> { new PhoneNumber(1111111111L, "home") }, null)); users.Add(new User(28, "popular", new List<PhoneNumber> { new PhoneNumber(1111111111L, "home"), new PhoneNumber(2222222222L, null), new PhoneNumber(3333333333L, "mobile") }, null)); users.Add(new User(30, null, new List<PhoneNumber> { new PhoneNumber(1111111111L, "home") }, null)); for (int i = 100; i < 200; i++) { Location location = null; if (i % 3 == 1) { location = new Location((double)i, (double)i * 2); } if (i % 3 == 2) { location = new Location((double)i, null); } users.Add(new User(i, "p" + i, new List<PhoneNumber> { new PhoneNumber(i, "cell") }, location)); } return users; } private static File phonebookFile; private static List<User> users; // @BeforeClass public static void setup() { users = makeUsers(); phonebookFile = PhoneBookWriter.writeToFile(users); } private static List<Group> getExpected(Predicate<User> f) { List<Group> expected = new List<Group>(); foreach (User u in users) { if (f(u)) { expected.Add(PhoneBookWriter.groupFromUser(u)); } } return expected; } private static void assertFilter(List<Group> found, Predicate<User> f) { List<Group> expected = getExpected(f); Assert.Equal(expected, found); } [Fact] public void testNoFilter() { List<Group> found = PhoneBookWriter.readFile(phonebookFile, FilterCompat.NOOP); assertFilter(found, user => true); } [Fact] public void testAllFilter() { BinaryColumn name = binaryColumn("name"); FilterPredicate pred = eq(name, Binary.fromString("no matches")); List<Group> found = PhoneBookWriter.readFile(phonebookFile, FilterCompat.get(pred)); Assert.Equal(new List<Group>(), found); } [Fact] public void testNameNotNull() { BinaryColumn name = binaryColumn("name"); FilterPredicate pred = notEq(name, null); List<Group> found = PhoneBookWriter.readFile(phonebookFile, FilterCompat.get(pred)); assertFilter(found, user => user.getName() != null); } public class StartWithP : UserDefinedPredicate<Binary> { public override bool keep(Binary value) { if (value == null) { return false; } return value.toStringUsingUTF8().StartsWith("p"); } public override bool canDrop(Statistics<Binary> statistics) { return false; } public override bool inverseCanDrop(Statistics<Binary> statistics) { return false; } } public class SetInFilter : UserDefinedPredicate<long> { private HashSet<long> hSet; public SetInFilter(HashSet<long> phSet) { hSet = phSet; } public override bool keep(long value) { if (value == null) { return false; } return hSet.Contains(value); } public override bool canDrop(Statistics<long> statistics) { return false; } public override bool inverseCanDrop(Statistics<long> statistics) { return false; } } [Fact] public void testNameNotStartWithP() { BinaryColumn name = binaryColumn("name"); FilterPredicate pred = not(userDefined(name, typeof(StartWithP))); List<Group> found = PhoneBookWriter.readFile(phonebookFile, FilterCompat.get(pred)); assertFilter(found, user => user.getName() == null || !user.getName().StartsWith("p")); } [Fact] public void testUserDefinedByInstance() { LongColumn name = longColumn("id"); HashSet<long> h = new HashSet<long>(); h.Add(20L); h.Add(27L); h.Add(28L); FilterPredicate pred = userDefined(name, new SetInFilter(h)); List<Group> found = PhoneBookWriter.readFile(phonebookFile, FilterCompat.get(pred)); assertFilter(found, user => user != null && h.Contains(user.getId())); } [Fact] public void testComplex() { BinaryColumn name = binaryColumn("name"); DoubleColumn lon = doubleColumn("location.lon"); DoubleColumn lat = doubleColumn("location.lat"); FilterPredicate pred = or(and(gt(lon, 150.0), notEq<double, DoubleColumn>(lat, null)), eq(name, Binary.fromString("alice"))); List<Group> found = PhoneBookWriter.readFile(phonebookFile, FilterCompat.get(pred)); assertFilter(found, user => { string name2 = user.getName(); double? lat2 = null; double? lon2 = null; if (user.getLocation() != null) { lat2 = user.getLocation().getLat(); lon2 = user.getLocation().getLon(); } return (lon2 != null && lon2 > 150.0 && lat2 != null) || "alice".Equals(name2); }); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Datastream; using Apache.Ignite.Core.DataStructures; using Apache.Ignite.Core.Events; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Cache; using Apache.Ignite.Core.Impl.Cluster; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Datastream; using Apache.Ignite.Core.Impl.DataStructures; using Apache.Ignite.Core.Impl.Handle; using Apache.Ignite.Core.Impl.Plugin; using Apache.Ignite.Core.Impl.Transactions; using Apache.Ignite.Core.Impl.Unmanaged; using Apache.Ignite.Core.Interop; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.Messaging; using Apache.Ignite.Core.PersistentStore; using Apache.Ignite.Core.Services; using Apache.Ignite.Core.Transactions; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// Native Ignite wrapper. /// </summary> internal class Ignite : PlatformTargetAdapter, ICluster, IIgniteInternal, IIgnite { /// <summary> /// Operation codes for PlatformProcessorImpl calls. /// </summary> private enum Op { GetCache = 1, CreateCache = 2, GetOrCreateCache = 3, CreateCacheFromConfig = 4, GetOrCreateCacheFromConfig = 5, DestroyCache = 6, GetAffinity = 7, GetDataStreamer = 8, GetTransactions = 9, GetClusterGroup = 10, GetExtension = 11, GetAtomicLong = 12, GetAtomicReference = 13, GetAtomicSequence = 14, GetIgniteConfiguration = 15, GetCacheNames = 16, CreateNearCache = 17, GetOrCreateNearCache = 18, LoggerIsLevelEnabled = 19, LoggerLog = 20, GetBinaryProcessor = 21, ReleaseStart = 22 } /** */ private readonly IgniteConfiguration _cfg; /** Grid name. */ private readonly string _name; /** Unmanaged node. */ private readonly IPlatformTargetInternal _proc; /** Marshaller. */ private readonly Marshaller _marsh; /** Initial projection. */ private readonly ClusterGroupImpl _prj; /** Binary. */ private readonly Binary.Binary _binary; /** Binary processor. */ private readonly BinaryProcessor _binaryProc; /** Lifecycle handlers. */ private readonly IList<LifecycleHandlerHolder> _lifecycleHandlers; /** Local node. */ private IClusterNode _locNode; /** Transactions facade. */ private readonly Lazy<TransactionsImpl> _transactions; /** Callbacks */ private readonly UnmanagedCallbacks _cbs; /** Node info cache. */ private readonly ConcurrentDictionary<Guid, ClusterNodeImpl> _nodes = new ConcurrentDictionary<Guid, ClusterNodeImpl>(); /** Client reconnect task completion source. */ private volatile TaskCompletionSource<bool> _clientReconnectTaskCompletionSource = new TaskCompletionSource<bool>(); /** Plugin processor. */ private readonly PluginProcessor _pluginProcessor; /// <summary> /// Constructor. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="name">Grid name.</param> /// <param name="proc">Interop processor.</param> /// <param name="marsh">Marshaller.</param> /// <param name="lifecycleHandlers">Lifecycle beans.</param> /// <param name="cbs">Callbacks.</param> public Ignite(IgniteConfiguration cfg, string name, IPlatformTargetInternal proc, Marshaller marsh, IList<LifecycleHandlerHolder> lifecycleHandlers, UnmanagedCallbacks cbs) : base(proc) { Debug.Assert(cfg != null); Debug.Assert(proc != null); Debug.Assert(marsh != null); Debug.Assert(lifecycleHandlers != null); Debug.Assert(cbs != null); _cfg = cfg; _name = name; _proc = proc; _marsh = marsh; _lifecycleHandlers = lifecycleHandlers; _cbs = cbs; marsh.Ignite = this; _prj = new ClusterGroupImpl(Target.OutObjectInternal((int) Op.GetClusterGroup), null); _binary = new Binary.Binary(marsh); _binaryProc = new BinaryProcessor(DoOutOpObject((int) Op.GetBinaryProcessor)); cbs.Initialize(this); // Grid is not completely started here, can't initialize interop transactions right away. _transactions = new Lazy<TransactionsImpl>( () => new TransactionsImpl(DoOutOpObject((int) Op.GetTransactions), GetLocalNode().Id)); // Set reconnected task to completed state for convenience. _clientReconnectTaskCompletionSource.SetResult(false); SetCompactFooter(); _pluginProcessor = new PluginProcessor(this); } /// <summary> /// Sets the compact footer setting. /// </summary> private void SetCompactFooter() { if (!string.IsNullOrEmpty(_cfg.SpringConfigUrl)) { // If there is a Spring config, use setting from Spring, // since we ignore .NET config in legacy mode. var cfg0 = GetConfiguration().BinaryConfiguration; if (cfg0 != null) _marsh.CompactFooter = cfg0.CompactFooter; } } /// <summary> /// On-start routine. /// </summary> internal void OnStart() { PluginProcessor.OnIgniteStart(); foreach (var lifecycleBean in _lifecycleHandlers) lifecycleBean.OnStart(this); } /** <inheritdoc /> */ public string Name { get { return _name; } } /** <inheritdoc /> */ public ICluster GetCluster() { return this; } /** <inheritdoc /> */ IIgnite IClusterGroup.Ignite { get { return this; } } /** <inheritdoc /> */ public IClusterGroup ForLocal() { return _prj.ForNodes(GetLocalNode()); } /** <inheritdoc /> */ public ICompute GetCompute() { return _prj.ForServers().GetCompute(); } /** <inheritdoc /> */ public IClusterGroup ForNodes(IEnumerable<IClusterNode> nodes) { return _prj.ForNodes(nodes); } /** <inheritdoc /> */ public IClusterGroup ForNodes(params IClusterNode[] nodes) { return _prj.ForNodes(nodes); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(IEnumerable<Guid> ids) { return _prj.ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(params Guid[] ids) { return _prj.ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForPredicate(Func<IClusterNode, bool> p) { IgniteArgumentCheck.NotNull(p, "p"); return _prj.ForPredicate(p); } /** <inheritdoc /> */ public IClusterGroup ForAttribute(string name, string val) { return _prj.ForAttribute(name, val); } /** <inheritdoc /> */ public IClusterGroup ForCacheNodes(string name) { return _prj.ForCacheNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForDataNodes(string name) { return _prj.ForDataNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForClientNodes(string name) { return _prj.ForClientNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForRemotes() { return _prj.ForRemotes(); } /** <inheritdoc /> */ public IClusterGroup ForDaemons() { return _prj.ForDaemons(); } /** <inheritdoc /> */ public IClusterGroup ForHost(IClusterNode node) { IgniteArgumentCheck.NotNull(node, "node"); return _prj.ForHost(node); } /** <inheritdoc /> */ public IClusterGroup ForRandom() { return _prj.ForRandom(); } /** <inheritdoc /> */ public IClusterGroup ForOldest() { return _prj.ForOldest(); } /** <inheritdoc /> */ public IClusterGroup ForYoungest() { return _prj.ForYoungest(); } /** <inheritdoc /> */ public IClusterGroup ForDotNet() { return _prj.ForDotNet(); } /** <inheritdoc /> */ public IClusterGroup ForServers() { return _prj.ForServers(); } /** <inheritdoc /> */ public ICollection<IClusterNode> GetNodes() { return _prj.GetNodes(); } /** <inheritdoc /> */ public IClusterNode GetNode(Guid id) { return _prj.GetNode(id); } /** <inheritdoc /> */ public IClusterNode GetNode() { return _prj.GetNode(); } /** <inheritdoc /> */ public IClusterMetrics GetMetrics() { return _prj.GetMetrics(); } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly", Justification = "There is no finalizer.")] [SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "_proxy", Justification = "Proxy does not need to be disposed.")] public void Dispose() { Ignition.Stop(Name, true); } /// <summary> /// Internal stop routine. /// </summary> /// <param name="cancel">Cancel flag.</param> internal unsafe void Stop(bool cancel) { var jniTarget = _proc as PlatformJniTarget; if (jniTarget == null) { throw new IgniteException("Ignition.Stop is not supported in thin client."); } UU.IgnitionStop(jniTarget.Target.Context, Name, cancel); _cbs.Cleanup(); } /// <summary> /// Called before node has stopped. /// </summary> internal void BeforeNodeStop() { var handler = Stopping; if (handler != null) handler.Invoke(this, EventArgs.Empty); } /// <summary> /// Called after node has stopped. /// </summary> internal void AfterNodeStop() { foreach (var bean in _lifecycleHandlers) bean.OnLifecycleEvent(LifecycleEventType.AfterNodeStop); var handler = Stopped; if (handler != null) handler.Invoke(this, EventArgs.Empty); } /** <inheritdoc /> */ public ICache<TK, TV> GetCache<TK, TV>(string name) { IgniteArgumentCheck.NotNull(name, "name"); return GetCache<TK, TV>(DoOutOpObject((int) Op.GetCache, w => w.WriteString(name))); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(string name) { IgniteArgumentCheck.NotNull(name, "name"); return GetCache<TK, TV>(DoOutOpObject((int) Op.GetOrCreateCache, w => w.WriteString(name))); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration) { return GetOrCreateCache<TK, TV>(configuration, null); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration) { return GetOrCreateCache<TK, TV>(configuration, nearConfiguration, Op.GetOrCreateCacheFromConfig); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(string name) { IgniteArgumentCheck.NotNull(name, "name"); var cacheTarget = DoOutOpObject((int) Op.CreateCache, w => w.WriteString(name)); return GetCache<TK, TV>(cacheTarget); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration) { return CreateCache<TK, TV>(configuration, null); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration) { return GetOrCreateCache<TK, TV>(configuration, nearConfiguration, Op.CreateCacheFromConfig); } /// <summary> /// Gets or creates the cache. /// </summary> private ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration, Op op) { IgniteArgumentCheck.NotNull(configuration, "configuration"); IgniteArgumentCheck.NotNull(configuration.Name, "CacheConfiguration.Name"); configuration.Validate(Logger); var cacheTarget = DoOutOpObject((int) op, s => { var w = BinaryUtils.Marshaller.StartMarshal(s); configuration.Write(w); if (nearConfiguration != null) { w.WriteBoolean(true); nearConfiguration.Write(w); } else { w.WriteBoolean(false); } }); return GetCache<TK, TV>(cacheTarget); } /** <inheritdoc /> */ public void DestroyCache(string name) { IgniteArgumentCheck.NotNull(name, "name"); DoOutOp((int) Op.DestroyCache, w => w.WriteString(name)); } /// <summary> /// Gets cache from specified native cache object. /// </summary> /// <param name="nativeCache">Native cache.</param> /// <param name="keepBinary">Keep binary flag.</param> /// <returns> /// New instance of cache wrapping specified native cache. /// </returns> public static ICache<TK, TV> GetCache<TK, TV>(IPlatformTargetInternal nativeCache, bool keepBinary = false) { return new CacheImpl<TK, TV>(nativeCache, false, keepBinary, false, false); } /** <inheritdoc /> */ public IClusterNode GetLocalNode() { return _locNode ?? (_locNode = GetNodes().FirstOrDefault(x => x.IsLocal) ?? ForDaemons().GetNodes().FirstOrDefault(x => x.IsLocal)); } /** <inheritdoc /> */ public bool PingNode(Guid nodeId) { return _prj.PingNode(nodeId); } /** <inheritdoc /> */ public long TopologyVersion { get { return _prj.TopologyVersion; } } /** <inheritdoc /> */ public ICollection<IClusterNode> GetTopology(long ver) { return _prj.Topology(ver); } /** <inheritdoc /> */ public void ResetMetrics() { _prj.ResetMetrics(); } /** <inheritdoc /> */ public Task<bool> ClientReconnectTask { get { return _clientReconnectTaskCompletionSource.Task; } } /** <inheritdoc /> */ public IDataStreamer<TK, TV> GetDataStreamer<TK, TV>(string cacheName) { IgniteArgumentCheck.NotNull(cacheName, "cacheName"); return GetDataStreamer<TK, TV>(cacheName, false); } /// <summary> /// Gets the data streamer. /// </summary> public IDataStreamer<TK, TV> GetDataStreamer<TK, TV>(string cacheName, bool keepBinary) { var streamerTarget = DoOutOpObject((int) Op.GetDataStreamer, w => { w.WriteString(cacheName); w.WriteBoolean(keepBinary); }); return new DataStreamerImpl<TK, TV>(streamerTarget, _marsh, cacheName, keepBinary); } /// <summary> /// Gets the public Ignite interface. /// </summary> public IIgnite GetIgnite() { return this; } /** <inheritdoc /> */ public IBinary GetBinary() { return _binary; } /** <inheritdoc /> */ public ICacheAffinity GetAffinity(string cacheName) { IgniteArgumentCheck.NotNull(cacheName, "cacheName"); var aff = DoOutOpObject((int) Op.GetAffinity, w => w.WriteString(cacheName)); return new CacheAffinityImpl(aff, false); } /** <inheritdoc /> */ public ITransactions GetTransactions() { return _transactions.Value; } /** <inheritdoc /> */ public IMessaging GetMessaging() { return _prj.GetMessaging(); } /** <inheritdoc /> */ public IEvents GetEvents() { return _prj.GetEvents(); } /** <inheritdoc /> */ public IServices GetServices() { return _prj.ForServers().GetServices(); } /** <inheritdoc /> */ public IAtomicLong GetAtomicLong(string name, long initialValue, bool create) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); var nativeLong = DoOutOpObject((int) Op.GetAtomicLong, w => { w.WriteString(name); w.WriteLong(initialValue); w.WriteBoolean(create); }); if (nativeLong == null) return null; return new AtomicLong(nativeLong, name); } /** <inheritdoc /> */ public IAtomicSequence GetAtomicSequence(string name, long initialValue, bool create) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); var nativeSeq = DoOutOpObject((int) Op.GetAtomicSequence, w => { w.WriteString(name); w.WriteLong(initialValue); w.WriteBoolean(create); }); if (nativeSeq == null) return null; return new AtomicSequence(nativeSeq, name); } /** <inheritdoc /> */ public IAtomicReference<T> GetAtomicReference<T>(string name, T initialValue, bool create) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); var refTarget = DoOutOpObject((int) Op.GetAtomicReference, w => { w.WriteString(name); w.WriteObject(initialValue); w.WriteBoolean(create); }); return refTarget == null ? null : new AtomicReference<T>(refTarget, name); } /** <inheritdoc /> */ public IgniteConfiguration GetConfiguration() { return DoInOp((int) Op.GetIgniteConfiguration, s => new IgniteConfiguration(BinaryUtils.Marshaller.StartUnmarshal(s), _cfg)); } /** <inheritdoc /> */ public ICache<TK, TV> CreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration) { return GetOrCreateNearCache0<TK, TV>(name, configuration, Op.CreateNearCache); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration) { return GetOrCreateNearCache0<TK, TV>(name, configuration, Op.GetOrCreateNearCache); } /** <inheritdoc /> */ public ICollection<string> GetCacheNames() { return Target.OutStream((int) Op.GetCacheNames, r => { var res = new string[r.ReadInt()]; for (var i = 0; i < res.Length; i++) res[i] = r.ReadString(); return (ICollection<string>) res; }); } /** <inheritdoc /> */ public ILogger Logger { get { return _cbs.Log; } } /** <inheritdoc /> */ public event EventHandler Stopping; /** <inheritdoc /> */ public event EventHandler Stopped; /** <inheritdoc /> */ public event EventHandler ClientDisconnected; /** <inheritdoc /> */ public event EventHandler<ClientReconnectEventArgs> ClientReconnected; /** <inheritdoc /> */ public T GetPlugin<T>(string name) where T : class { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); return PluginProcessor.GetProvider(name).GetPlugin<T>(); } /** <inheritdoc /> */ public void ResetLostPartitions(IEnumerable<string> cacheNames) { IgniteArgumentCheck.NotNull(cacheNames, "cacheNames"); _prj.ResetLostPartitions(cacheNames); } /** <inheritdoc /> */ public void ResetLostPartitions(params string[] cacheNames) { ResetLostPartitions((IEnumerable<string>) cacheNames); } /** <inheritdoc /> */ #pragma warning disable 618 public ICollection<IMemoryMetrics> GetMemoryMetrics() { return _prj.GetMemoryMetrics(); } /** <inheritdoc /> */ public IMemoryMetrics GetMemoryMetrics(string memoryPolicyName) { IgniteArgumentCheck.NotNullOrEmpty(memoryPolicyName, "memoryPolicyName"); return _prj.GetMemoryMetrics(memoryPolicyName); } #pragma warning restore 618 /** <inheritdoc /> */ public void SetActive(bool isActive) { _prj.SetActive(isActive); } /** <inheritdoc /> */ public bool IsActive() { return _prj.IsActive(); } /** <inheritdoc /> */ #pragma warning disable 618 public IPersistentStoreMetrics GetPersistentStoreMetrics() { return _prj.GetPersistentStoreMetrics(); } #pragma warning restore 618 /** <inheritdoc /> */ public ICollection<IDataRegionMetrics> GetDataRegionMetrics() { return _prj.GetDataRegionMetrics(); } /** <inheritdoc /> */ public IDataRegionMetrics GetDataRegionMetrics(string memoryPolicyName) { return _prj.GetDataRegionMetrics(memoryPolicyName); } /** <inheritdoc /> */ public IDataStorageMetrics GetDataStorageMetrics() { return _prj.GetDataStorageMetrics(); } /// <summary> /// Gets or creates near cache. /// </summary> private ICache<TK, TV> GetOrCreateNearCache0<TK, TV>(string name, NearCacheConfiguration configuration, Op op) { IgniteArgumentCheck.NotNull(configuration, "configuration"); var cacheTarget = DoOutOpObject((int) op, w => { w.WriteString(name); configuration.Write(w); }); return GetCache<TK, TV>(cacheTarget); } /// <summary> /// Gets internal projection. /// </summary> /// <returns>Projection.</returns> public ClusterGroupImpl ClusterGroup { get { return _prj; } } /// <summary> /// Gets the binary processor. /// </summary> public IBinaryProcessor BinaryProcessor { get { return _binaryProc; } } /// <summary> /// Configuration. /// </summary> public IgniteConfiguration Configuration { get { return _cfg; } } /// <summary> /// Handle registry. /// </summary> public HandleRegistry HandleRegistry { get { return _cbs.HandleRegistry; } } /// <summary> /// Updates the node information from stream. /// </summary> /// <param name="memPtr">Stream ptr.</param> public void UpdateNodeInfo(long memPtr) { var stream = IgniteManager.Memory.Get(memPtr).GetStream(); IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); var node = new ClusterNodeImpl(reader); node.Init(this); _nodes[node.Id] = node; } /// <summary> /// Gets the node from cache. /// </summary> /// <param name="id">Node id.</param> /// <returns>Cached node.</returns> public ClusterNodeImpl GetNode(Guid? id) { return id == null ? null : _nodes[id.Value]; } /// <summary> /// Gets the interop processor. /// </summary> internal IPlatformTargetInternal InteropProcessor { get { return _proc; } } /// <summary> /// Called when local client node has been disconnected from the cluster. /// </summary> internal void OnClientDisconnected() { _clientReconnectTaskCompletionSource = new TaskCompletionSource<bool>(); var handler = ClientDisconnected; if (handler != null) handler.Invoke(this, EventArgs.Empty); } /// <summary> /// Called when local client node has been reconnected to the cluster. /// </summary> /// <param name="clusterRestarted">Cluster restarted flag.</param> internal void OnClientReconnected(bool clusterRestarted) { _clientReconnectTaskCompletionSource.TrySetResult(clusterRestarted); var handler = ClientReconnected; if (handler != null) handler.Invoke(this, new ClientReconnectEventArgs(clusterRestarted)); } /// <summary> /// Gets the plugin processor. /// </summary> public PluginProcessor PluginProcessor { get { return _pluginProcessor; } } /// <summary> /// Notify processor that it is safe to use. /// </summary> internal void ProcessorReleaseStart() { Target.InLongOutLong((int) Op.ReleaseStart, 0); } /// <summary> /// Checks whether log level is enabled in Java logger. /// </summary> internal bool LoggerIsLevelEnabled(LogLevel logLevel) { return Target.InLongOutLong((int) Op.LoggerIsLevelEnabled, (long) logLevel) == True; } /// <summary> /// Logs to the Java logger. /// </summary> internal void LoggerLog(LogLevel level, string msg, string category, string err) { Target.InStreamOutLong((int) Op.LoggerLog, w => { w.WriteInt((int) level); w.WriteString(msg); w.WriteString(category); w.WriteString(err); }); } /// <summary> /// Gets the platform plugin extension. /// </summary> internal IPlatformTarget GetExtension(int id) { return ((IPlatformTarget) Target).InStreamOutObject((int) Op.GetExtension, w => w.WriteInt(id)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AddSingle() { var test = new SimpleBinaryOpTest__AddSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AddSingle { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Single); private const int Op2ElementCount = VectorSize / sizeof(Single); private const int RetElementCount = VectorSize / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector256<Single> _clsVar1; private static Vector256<Single> _clsVar2; private Vector256<Single> _fld1; private Vector256<Single> _fld2; private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable; static SimpleBinaryOpTest__AddSingle() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__AddSingle() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], VectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx.Add( Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx.Add( Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx.Add( Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx).GetMethod(nameof(Avx.Add), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx).GetMethod(nameof(Avx.Add), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) }) .Invoke(null, new object[] { Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx).GetMethod(nameof(Avx.Add), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx.Add( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr); var result = Avx.Add(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)); var result = Avx.Add(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)); var result = Avx.Add(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__AddSingle(); var result = Avx.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx.Add(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Single> left, Vector256<Single> right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { if (BitConverter.SingleToInt32Bits(left[0] + right[0]) != BitConverter.SingleToInt32Bits(result[0])) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(left[i] + right[i]) != BitConverter.SingleToInt32Bits(result[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.Add)}<Single>(Vector256<Single>, Vector256<Single>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// ------------------------------------------------------------------------------ // 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\EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type MultiValueLegacyExtendedPropertyRequest. /// </summary> public partial class MultiValueLegacyExtendedPropertyRequest : BaseRequest, IMultiValueLegacyExtendedPropertyRequest { /// <summary> /// Constructs a new MultiValueLegacyExtendedPropertyRequest. /// </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 MultiValueLegacyExtendedPropertyRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified MultiValueLegacyExtendedProperty using POST. /// </summary> /// <param name="multiValueLegacyExtendedPropertyToCreate">The MultiValueLegacyExtendedProperty to create.</param> /// <returns>The created MultiValueLegacyExtendedProperty.</returns> public System.Threading.Tasks.Task<MultiValueLegacyExtendedProperty> CreateAsync(MultiValueLegacyExtendedProperty multiValueLegacyExtendedPropertyToCreate) { return this.CreateAsync(multiValueLegacyExtendedPropertyToCreate, CancellationToken.None); } /// <summary> /// Creates the specified MultiValueLegacyExtendedProperty using POST. /// </summary> /// <param name="multiValueLegacyExtendedPropertyToCreate">The MultiValueLegacyExtendedProperty to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created MultiValueLegacyExtendedProperty.</returns> public async System.Threading.Tasks.Task<MultiValueLegacyExtendedProperty> CreateAsync(MultiValueLegacyExtendedProperty multiValueLegacyExtendedPropertyToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<MultiValueLegacyExtendedProperty>(multiValueLegacyExtendedPropertyToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified MultiValueLegacyExtendedProperty. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified MultiValueLegacyExtendedProperty. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<MultiValueLegacyExtendedProperty>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified MultiValueLegacyExtendedProperty. /// </summary> /// <returns>The MultiValueLegacyExtendedProperty.</returns> public System.Threading.Tasks.Task<MultiValueLegacyExtendedProperty> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified MultiValueLegacyExtendedProperty. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The MultiValueLegacyExtendedProperty.</returns> public async System.Threading.Tasks.Task<MultiValueLegacyExtendedProperty> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<MultiValueLegacyExtendedProperty>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified MultiValueLegacyExtendedProperty using PATCH. /// </summary> /// <param name="multiValueLegacyExtendedPropertyToUpdate">The MultiValueLegacyExtendedProperty to update.</param> /// <returns>The updated MultiValueLegacyExtendedProperty.</returns> public System.Threading.Tasks.Task<MultiValueLegacyExtendedProperty> UpdateAsync(MultiValueLegacyExtendedProperty multiValueLegacyExtendedPropertyToUpdate) { return this.UpdateAsync(multiValueLegacyExtendedPropertyToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified MultiValueLegacyExtendedProperty using PATCH. /// </summary> /// <param name="multiValueLegacyExtendedPropertyToUpdate">The MultiValueLegacyExtendedProperty to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated MultiValueLegacyExtendedProperty.</returns> public async System.Threading.Tasks.Task<MultiValueLegacyExtendedProperty> UpdateAsync(MultiValueLegacyExtendedProperty multiValueLegacyExtendedPropertyToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<MultiValueLegacyExtendedProperty>(multiValueLegacyExtendedPropertyToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <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 IMultiValueLegacyExtendedPropertyRequest 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 IMultiValueLegacyExtendedPropertyRequest Expand(Expression<Func<MultiValueLegacyExtendedProperty, 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 IMultiValueLegacyExtendedPropertyRequest 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 IMultiValueLegacyExtendedPropertyRequest Select(Expression<Func<MultiValueLegacyExtendedProperty, 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> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="multiValueLegacyExtendedPropertyToInitialize">The <see cref="MultiValueLegacyExtendedProperty"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(MultiValueLegacyExtendedProperty multiValueLegacyExtendedPropertyToInitialize) { } } }
using UnityEditor; using UnityEditorInternal; using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Fungus { [CustomEditor (typeof(Variable), true)] public class VariableEditor : CommandEditor { protected virtual void OnEnable() { Variable t = target as Variable; t.hideFlags = HideFlags.HideInInspector; } public static VariableInfoAttribute GetVariableInfo(System.Type variableType) { object[] attributes = variableType.GetCustomAttributes(typeof(VariableInfoAttribute), false); foreach (object obj in attributes) { VariableInfoAttribute variableInfoAttr = obj as VariableInfoAttribute; if (variableInfoAttr != null) { return variableInfoAttr; } } return null; } static public void VariableField(SerializedProperty property, GUIContent label, Flowchart flowchart, string defaultText, Func<Variable, bool> filter, Func<string, int, string[], int> drawer = null) { List<string> variableKeys = new List<string>(); List<Variable> variableObjects = new List<Variable>(); variableKeys.Add(defaultText); variableObjects.Add(null); List<Variable> variables = flowchart.variables; int index = 0; int selectedIndex = 0; Variable selectedVariable = property.objectReferenceValue as Variable; foreach (Variable v in variables) { if (filter != null) { if (!filter(v)) { continue; } } variableKeys.Add(v.key); variableObjects.Add(v); index++; if (v == selectedVariable) { selectedIndex = index; } } Flowchart[] fsList = GameObject.FindObjectsOfType<Flowchart>(); foreach (Flowchart fs in fsList) { if (fs == flowchart) { continue; } List<Variable> publicVars = fs.GetPublicVariables(); foreach (Variable v in publicVars) { if (filter != null) { if (!filter(v)) { continue; } } variableKeys.Add(fs.name + " / " + v.key); variableObjects.Add(v); index++; if (v == selectedVariable) { selectedIndex = index; } } } if (drawer == null) { selectedIndex = EditorGUILayout.Popup(label.text, selectedIndex, variableKeys.ToArray()); } else { selectedIndex = drawer(label.text, selectedIndex, variableKeys.ToArray()); } property.objectReferenceValue = variableObjects[selectedIndex]; } } [CustomPropertyDrawer(typeof(VariablePropertyAttribute))] public class VariableDrawer : PropertyDrawer { public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) { VariablePropertyAttribute variableProperty = attribute as VariablePropertyAttribute; if (variableProperty == null) { return; } EditorGUI.BeginProperty(position, label, property); // Filter the variables by the types listed in the VariableProperty attribute Func<Variable, bool> compare = v => { if (v == null) { return false; } if (variableProperty.VariableTypes.Length == 0) { return true; } return variableProperty.VariableTypes.Contains<System.Type>(v.GetType()); }; VariableEditor.VariableField(property, label, FlowchartWindow.GetFlowchart(), variableProperty.defaultText, compare, (s,t,u) => (EditorGUI.Popup(position, s, t, u))); EditorGUI.EndProperty(); } } public class VariableDataDrawer<T> : PropertyDrawer where T : Variable { public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty(position, label, property); // The variable reference and data properties must follow the naming convention 'typeRef', 'typeVal' VariableInfoAttribute typeInfo = VariableEditor.GetVariableInfo(typeof(T)); if (typeInfo == null) { return; } string propNameBase = typeInfo.VariableType; propNameBase = Char.ToLowerInvariant(propNameBase[0]) + propNameBase.Substring(1); SerializedProperty referenceProp = property.FindPropertyRelative(propNameBase + "Ref"); SerializedProperty valueProp = property.FindPropertyRelative(propNameBase + "Val"); if (referenceProp == null || valueProp == null) { return; } Command command = property.serializedObject.targetObject as Command; if (command == null) { return; } Flowchart flowchart = command.GetFlowchart() as Flowchart; if (flowchart == null) { return; } if (EditorGUI.GetPropertyHeight(valueProp, label) > EditorGUIUtility.singleLineHeight) { DrawMultiLineProperty(position, label, referenceProp, valueProp, flowchart); } else { DrawSingleLineProperty(position, label, referenceProp, valueProp, flowchart); } EditorGUI.EndProperty(); } protected virtual void DrawSingleLineProperty(Rect rect, GUIContent label, SerializedProperty referenceProp, SerializedProperty valueProp, Flowchart flowchart) { const int popupWidth = 100; Rect controlRect = EditorGUI.PrefixLabel(rect, label); Rect valueRect = controlRect; valueRect.width = controlRect.width - popupWidth - 5; Rect popupRect = controlRect; if (referenceProp.objectReferenceValue == null) { EditorGUI.PropertyField(valueRect, valueProp, new GUIContent("")); popupRect.x += valueRect.width + 5; popupRect.width = popupWidth; } EditorGUI.PropertyField(popupRect, referenceProp, new GUIContent("")); } protected virtual void DrawMultiLineProperty(Rect rect, GUIContent label, SerializedProperty referenceProp, SerializedProperty valueProp, Flowchart flowchart) { const int popupWidth = 100; Rect controlRect = rect; Rect valueRect = controlRect; valueRect.width = controlRect.width - 5; Rect popupRect = controlRect; if (referenceProp.objectReferenceValue == null) { EditorGUI.PropertyField(valueRect, valueProp, label); popupRect.x = rect.width - popupWidth + 5; popupRect.width = popupWidth; } else { popupRect = EditorGUI.PrefixLabel(rect, label); } EditorGUI.PropertyField(popupRect, referenceProp, new GUIContent("")); } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { VariableInfoAttribute typeInfo = VariableEditor.GetVariableInfo(typeof(T)); if (typeInfo == null) { return EditorGUIUtility.singleLineHeight; } string propNameBase = typeInfo.VariableType; propNameBase = Char.ToLowerInvariant(propNameBase[0]) + propNameBase.Substring(1); SerializedProperty referenceProp = property.FindPropertyRelative(propNameBase + "Ref"); if (referenceProp.objectReferenceValue != null) { return EditorGUIUtility.singleLineHeight; } SerializedProperty valueProp = property.FindPropertyRelative(propNameBase + "Val"); return EditorGUI.GetPropertyHeight(valueProp, label); } } [CustomPropertyDrawer (typeof(BooleanData))] public class BooleanDataDrawer : VariableDataDrawer<BooleanVariable> {} [CustomPropertyDrawer (typeof(IntegerData))] public class IntegerDataDrawer : VariableDataDrawer<IntegerVariable> {} [CustomPropertyDrawer (typeof(FloatData))] public class FloatDataDrawer : VariableDataDrawer<FloatVariable> {} [CustomPropertyDrawer (typeof(StringData))] public class StringDataDrawer : VariableDataDrawer<StringVariable> {} [CustomPropertyDrawer (typeof(ColorData))] public class ColorDataDrawer : VariableDataDrawer<ColorVariable> {} [CustomPropertyDrawer (typeof(Vector2Data))] public class Vector2DataDrawer : VariableDataDrawer<Vector2Variable> {} [CustomPropertyDrawer (typeof(Vector3Data))] public class Vector3DataDrawer : VariableDataDrawer<Vector3Variable> {} [CustomPropertyDrawer (typeof(MaterialData))] public class MaterialDataDrawer : VariableDataDrawer<MaterialVariable> {} [CustomPropertyDrawer (typeof(TextureData))] public class TextureDataDrawer : VariableDataDrawer<TextureVariable> {} [CustomPropertyDrawer (typeof(SpriteData))] public class SpriteDataDrawer : VariableDataDrawer<SpriteVariable> {} [CustomPropertyDrawer (typeof(GameObjectData))] public class GameObjectDataDrawer : VariableDataDrawer<GameObjectVariable> {} [CustomPropertyDrawer (typeof(ObjectData))] public class ObjectDataDrawer : VariableDataDrawer<ObjectVariable> {} }
/* * 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 System.Text; using System.Threading; namespace Apache.Geode.Client.FwkLib { using Apache.Geode.Client.Tests; using Apache.Geode.DUnitFramework; public class Security : PerfTests { #region Protected constants protected const string EntryCount = "entryCount"; protected const string WorkTime = "workTime"; protected const string ObjectType = "objectType"; protected const string EntryOps = "entryOps"; protected const string LargeSetQuery = "largeSetQuery"; protected const string UnsupportedPRQuery = "unsupportedPRQuery"; #endregion #region Utility methods private CacheableKey GetKey(int max) { ResetKey(ObjectType); string objectType = GetStringValue(ObjectType); QueryHelper qh = QueryHelper.GetHelper(); int numSet = 0; int setSize = 0; if (objectType != null && objectType == "Portfolio") { setSize = qh.PortfolioSetSize; numSet = max / setSize; return new CacheableString(String.Format("port{0}-{1}", Util.Rand(numSet), Util.Rand(setSize))); } else if (objectType != null && objectType == "Position") { setSize = qh.PositionSetSize; numSet = max / setSize; return new CacheableString(String.Format("pos{0}-{1}", Util.Rand(numSet), Util.Rand(setSize))); } else { return m_keysA[Util.Rand(m_maxKeys)]; } } private IGeodeSerializable GetUserObject(string objType) { IGeodeSerializable usrObj = null; ResetKey(EntryCount); int numOfKeys = GetUIntValue(EntryCount); ResetKey(ValueSizes); int objSize = GetUIntValue(ValueSizes); QueryHelper qh = QueryHelper.GetHelper(); int numSet = 0; int setSize = 0; if (objType != null && objType == "Portfolio") { setSize = qh.PortfolioSetSize; numSet = numOfKeys / setSize; usrObj = new Portfolio(Util.Rand(setSize), objSize); } else if (objType != null && objType == "Position") { setSize = qh.PositionSetSize; numSet = numOfKeys / setSize; int numSecIds = Portfolio.SecIds.Length; usrObj = new Position(Portfolio.SecIds[setSize % numSecIds], setSize * 100); } return usrObj; } private bool AllowQuery(QueryCategory category, bool haveLargeResultset, bool islargeSetQuery, bool isUnsupportedPRQuery) { if (category == QueryCategory.Unsupported) { return false; } else if (haveLargeResultset != islargeSetQuery) { return false; } else if (isUnsupportedPRQuery && ((category == QueryCategory.MultiRegion) || (category == QueryCategory.NestedQueries))) { return false; } else { return true; } } private void RunQuery(ref int queryCnt) { FwkInfo("In Security.RunQuery"); try { ResetKey(EntryCount); int numOfKeys = GetUIntValue(EntryCount); QueryHelper qh = QueryHelper.GetHelper(); int setSize = qh.PortfolioSetSize; if (numOfKeys < setSize) { setSize = numOfKeys; } int index = Util.Rand(QueryStrings.RSsize); DateTime startTime; DateTime endTime; TimeSpan elapsedTime; QueryService qs = CacheHelper<TKey, TVal>.DCache.GetQueryService(); ResetKey(LargeSetQuery); ResetKey(UnsupportedPRQuery); bool isLargeSetQuery = GetBoolValue(LargeSetQuery); bool isUnsupportedPRQuery = GetBoolValue(UnsupportedPRQuery); QueryStrings currentQuery = QueryStatics.ResultSetQueries[index]; if (AllowQuery(currentQuery.Category, currentQuery.IsLargeResultset, isLargeSetQuery, isUnsupportedPRQuery)) { string query = currentQuery.Query; FwkInfo("Security.RunQuery: ResultSet Query Category [{0}], " + "String [{1}].", currentQuery.Category, query); Query qry = qs.NewQuery(query); startTime = DateTime.Now; ISelectResults results = qry.Execute(600); endTime = DateTime.Now; elapsedTime = endTime - startTime; FwkInfo("Security.RunQuery: Time Taken to execute" + " the query [{0}]: {1}ms", query, elapsedTime.TotalMilliseconds); ++queryCnt; } index = Util.Rand(QueryStrings.SSsize); currentQuery = QueryStatics.StructSetQueries[index]; if (AllowQuery(currentQuery.Category, currentQuery.IsLargeResultset, isLargeSetQuery, isUnsupportedPRQuery)) { string query = currentQuery.Query; FwkInfo("Security.RunQuery: StructSet Query Category [{0}], " + "String [{1}].", currentQuery.Category, query); Query qry = qs.NewQuery(query); startTime = DateTime.Now; ISelectResults results = qry.Execute(600); endTime = DateTime.Now; elapsedTime = endTime - startTime; FwkInfo("Security.RunQuery: Time Taken to execute" + " the query [{0}]: {1}ms", query, elapsedTime.TotalMilliseconds); ++queryCnt; } } catch (Exception ex) { FwkException("Security.RunQuery: Caught Exception: {0}", ex); } FwkInfo("Security.RunQuery complete."); } #endregion #region Public methods public new void DoRegisterInterestList() { FwkInfo("In DoRegisterInterestList()"); try { Region region = GetRegion(); int numKeys = GetUIntValue(DistinctKeys); // check distince keys first if (numKeys <= 0) { FwkSevere("DoRegisterInterestList() Failed to initialize keys " + "with numKeys: {0}", numKeys); return; } int low = GetUIntValue(KeyIndexBegin); low = (low > 0) ? low : 0; int numOfRegisterKeys = GetUIntValue(RegisterKeys); int high = numOfRegisterKeys + low; ClearKeys(); m_maxKeys = numOfRegisterKeys; m_keyIndexBegin = low; int keySize = GetUIntValue(KeySize); keySize = (keySize > 0) ? keySize : 10; string keyBase = new string('A', keySize); InitStrKeys(low, high, keyBase); FwkInfo("DoRegisterInterestList() registering interest for {0} to {1}", low, high); CacheableKey[] registerKeyList = new CacheableKey[high - low]; for (int j = low; j < high; j++) { if (m_keysA[j - low] != null) { registerKeyList[j - low] = m_keysA[j - low]; } else { FwkInfo("DoRegisterInterestList() key[{0}] is null.", (j - low)); } } FwkInfo("DoRegisterInterestList() region name is {0}", region.Name); region.RegisterKeys(registerKeyList); } catch (Exception ex) { FwkException("DoRegisterInterestList() Caught Exception: {0}", ex); } FwkInfo("DoRegisterInterestList() complete."); } public void DoEntryOperations() { FwkInfo("DoEntryOperations called."); int opsSec = GetUIntValue(OpsSecond); opsSec = (opsSec < 1) ? 0 : opsSec; int entryCount = GetUIntValue(EntryCount); entryCount = (entryCount < 1) ? 10000 : entryCount; int secondsToRun = GetTimeValue(WorkTime); secondsToRun = (secondsToRun < 1) ? 30 : secondsToRun; int valSize = GetUIntValue(ValueSizes); valSize = ((valSize < 0) ? 32 : valSize); DateTime now = DateTime.Now; DateTime end = now + TimeSpan.FromSeconds(secondsToRun); byte[] valBuf = Encoding.ASCII.GetBytes(new string('A', valSize)); string opcode = null; int creates = 0, puts = 0, gets = 0, dests = 0, invals = 0, queries = 0; Region region = GetRegion(); if (region == null) { FwkSevere("Security.DoEntryOperations: No region to perform operations on."); now = end; // Do not do the loop } FwkInfo("DoEntryOperations will work for {0} secs using {1} byte values.", secondsToRun, valSize); CacheableKey key; IGeodeSerializable value; IGeodeSerializable tmpValue; PaceMeter meter = new PaceMeter(opsSec); string objectType = GetStringValue(ObjectType); while (now < end) { try { opcode = GetStringValue(EntryOps); if (opcode == null || opcode.Length == 0) opcode = "no-op"; if (opcode == "add") { key = GetKey(entryCount); if (objectType != null && objectType.Length > 0) { tmpValue = GetUserObject(objectType); } else { tmpValue = CacheableBytes.Create(valBuf); } region.Create(key, tmpValue); creates++; } else { key = GetKey(entryCount); if (opcode == "update") { if (objectType != null && objectType.Length > 0) { tmpValue = GetUserObject(objectType); } else { int keyVal = int.Parse(key.ToString()); int val = BitConverter.ToInt32(valBuf, 0); val = (val == keyVal) ? keyVal + 1 : keyVal; // alternate the value so that it can be validated later. BitConverter.GetBytes(val).CopyTo(valBuf, 0); BitConverter.GetBytes(DateTime.Now.Ticks).CopyTo(valBuf, 4); tmpValue = CacheableBytes.Create(valBuf); } region.Put(key, tmpValue); puts++; } else if (opcode == "invalidate") { region.Invalidate(key); invals++; } else if (opcode == "destroy") { region.Destroy(key); dests++; } else if (opcode == "read") { value = region.Get(key); gets++; } else if (opcode == "read+localdestroy") { value = region.Get(key); gets++; region.LocalDestroy(key); dests++; } else if (opcode == "query") { RunQuery(ref queries); } else { FwkSevere("Invalid operation specified: {0}", opcode); } } } catch (TimeoutException ex) { FwkSevere("Security: Caught unexpected timeout exception during entry " + "{0} operation; continuing with the test: {1}", opcode, ex); } catch (EntryExistsException) { } catch (EntryNotFoundException) { } catch (EntryDestroyedException) { } catch (Exception ex) { end = DateTime.Now; FwkException("Security: Caught unexpected exception during entry " + "{0} operation; exiting task: {1}", opcode, ex); } meter.CheckPace(); now = DateTime.Now; } FwkInfo("DoEntryOperations did {0} creates, {1} puts, {2} gets, " + "{3} invalidates, {4} destroys, {5} queries.", creates, puts, gets, invals, dests, queries); } public void DoEntryOperationsMU() { FwkInfo("DoEntryOperations called."); int opsSec = GetUIntValue(OpsSecond); opsSec = (opsSec < 1) ? 0 : opsSec; int entryCount = GetUIntValue(EntryCount); entryCount = (entryCount < 1) ? 10000 : entryCount; int secondsToRun = GetTimeValue(WorkTime); secondsToRun = (secondsToRun < 1) ? 30 : secondsToRun; int valSize = GetUIntValue(ValueSizes); valSize = ((valSize < 0) ? 32 : valSize); DateTime now = DateTime.Now; DateTime end = now + TimeSpan.FromSeconds(secondsToRun); byte[] valBuf = Encoding.ASCII.GetBytes(new string('A', valSize)); string opcode = null; int creates = 0, puts = 0, gets = 0, dests = 0, invals = 0, queries = 0; Region region = GetRegion(); if (region == null) { FwkSevere("Security.DoEntryOperations: No region to perform operations on."); now = end; // Do not do the loop } FwkInfo("DoEntryOperations will work for {0} secs using {1} byte values.", secondsToRun, valSize); CacheableKey key; IGeodeSerializable value; IGeodeSerializable tmpValue; PaceMeter meter = new PaceMeter(opsSec); string objectType = GetStringValue(ObjectType); while (now < end) { try { opcode = GetStringValue(EntryOps); if (opcode == null || opcode.Length == 0) opcode = "no-op"; if (opcode == "add") { key = GetKey(entryCount); if (objectType != null && objectType.Length > 0) { tmpValue = GetUserObject(objectType); } else { tmpValue = CacheableBytes.Create(valBuf); } region.Create(key, tmpValue); creates++; } else { key = GetKey(entryCount); if (opcode == "update") { if (objectType != null && objectType.Length > 0) { tmpValue = GetUserObject(objectType); } else { int keyVal = int.Parse(key.ToString()); int val = BitConverter.ToInt32(valBuf, 0); val = (val == keyVal) ? keyVal + 1 : keyVal; // alternate the value so that it can be validated later. BitConverter.GetBytes(val).CopyTo(valBuf, 0); BitConverter.GetBytes(DateTime.Now.Ticks).CopyTo(valBuf, 4); tmpValue = CacheableBytes.Create(valBuf); } region.Put(key, tmpValue); puts++; } else if (opcode == "invalidate") { region.Invalidate(key); invals++; } else if (opcode == "destroy") { region.Destroy(key); dests++; } else if (opcode == "read") { value = region.Get(key); gets++; } else if (opcode == "read+localdestroy") { value = region.Get(key); gets++; region.LocalDestroy(key); dests++; } else if (opcode == "query") { RunQuery(ref queries); } else { FwkSevere("Invalid operation specified: {0}", opcode); } } } catch (TimeoutException ex) { FwkSevere("Security: Caught unexpected timeout exception during entry " + "{0} operation; continuing with the test: {1}", opcode, ex); } catch (EntryExistsException) { } catch (EntryNotFoundException) { } catch (EntryDestroyedException) { } catch (Exception ex) { end = DateTime.Now; FwkException("Security: Caught unexpected exception during entry " + "{0} operation; exiting task: {1}", opcode, ex); } meter.CheckPace(); now = DateTime.Now; } FwkInfo("DoEntryOperations did {0} creates, {1} puts, {2} gets, " + "{3} invalidates, {4} destroys, {5} queries.", creates, puts, gets, invals, dests, queries); } #endregion } }
using System; using Server.Targeting; using Server.Network; using System.Collections; using Server.Misc; using Server.Items; namespace Server.Spells.Druid { public class ShieldOfEarthSpell : DruidicSpell { private static SpellInfo m_Info = new SpellInfo( "Shield Of Earth", "Kes En Sepa Ohm", 227, 9011, false, Reagent.MandrakeRoot, Reagent.SpidersSilk ); public override TimeSpan CastDelayBase { get { return TimeSpan.FromSeconds( 1 ); } } public override SpellCircle Circle { get { return SpellCircle.Sixth; } } public override double RequiredSkill{ get{ return 60.0; } } public override int RequiredMana{ get{ return 45; } } public ShieldOfEarthSpell( Mobile caster, Item scroll ) : base( caster, scroll, m_Info ) { } public override void OnCast() { Caster.Target = new InternalTarget( this ); } public void Target( IPoint3D p ) { if ( !Caster.CanSee( p ) ) { Caster.SendLocalizedMessage( 500237 ); // Target can not be seen. } else if ( /*SpellHelper.CheckTown( p, Caster ) &&*/ CheckSequence() ) { if(this.Scroll!=null) Scroll.Consume(); SpellHelper.Turn( Caster, p ); SpellHelper.GetSurfaceTop( ref p ); int dx = Caster.Location.X - p.X; int dy = Caster.Location.Y - p.Y; int rx = (dx - dy) * 44; int ry = (dx + dy) * 44; bool eastToWest; if ( rx >= 0 && ry >= 0 ) { eastToWest = false; } else if ( rx >= 0 ) { eastToWest = true; } else if ( ry >= 0 ) { eastToWest = true; } else { eastToWest = false; } Effects.PlaySound( p, Caster.Map, 0x20B ); int itemID = eastToWest ? 0x3915 : 0x3922; TimeSpan duration = TimeSpan.FromSeconds( 3.0 + (Caster.Skills[SkillName.Spellweaving].Value * 0.4) ); for ( int i = -2; i <= 2; ++i ) { Point3D loc = new Point3D( eastToWest ? p.X + i : p.X, eastToWest ? p.Y : p.Y + i, p.Z ); new InternalItem( itemID, loc, Caster, Caster.Map, duration, i ); } } FinishSequence(); } [DispellableField] private class InternalItem : Item { private Timer m_Timer; private DateTime m_End; private Mobile m_Caster; private SleepingBody m_Body; public override bool BlocksFit{ get{ return true; } } public InternalItem( int itemID, Point3D loc, Mobile caster, Map map, TimeSpan duration, int val ) : base( itemID ) { bool canFit = SpellHelper.AdjustField( ref loc, map, 12, false ); Visible = false; Movable = false; Light = LightType.Circle300; Hue=1169; Name="sleep field"; MoveToWorld( loc, map ); m_Caster = caster; m_End = DateTime.Now + duration; m_Timer = new InternalTimer( this, TimeSpan.FromSeconds( Math.Abs( val ) * 0.2 ), caster.InLOS( this ), canFit ); m_Timer.Start(); } public override void OnAfterDelete() { base.OnAfterDelete(); if ( m_Timer != null ) m_Timer.Stop(); } public InternalItem( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 1 ); // version writer.Write( m_Caster ); writer.WriteDeltaTime( m_End ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); switch ( version ) { case 1: { m_Caster = reader.ReadMobile(); goto case 0; } case 0: { m_End = reader.ReadDeltaTime(); m_Timer = new InternalTimer( this, TimeSpan.Zero, true, true ); m_Timer.Start(); break; } } } public void ApplySleepTo( Mobile m ) { m.Hidden = true; m.Frozen=true; m.Squelched=true; SleepingBody body = new SleepingBody(m, m.Blessed); body.Map=m.Map; body.Location=m.Location; m_Body=body; m.Z-=100; m.SendMessage("You fall asleep"); RemoveTimer( m ); TimeSpan duration = TimeSpan.FromSeconds( m_Caster.Skills[SkillName.Magery].Value * 1.2 ); // 120% of magery Timer t = new BodyTimer( m, duration, m_Body ); m_Table[m] = t; t.Start(); } private static Hashtable m_Table = new Hashtable(); public static void RemoveTimer( Mobile m ) { Timer t = (Timer)m_Table[m]; if ( t != null ) { t.Stop(); m_Table.Remove( m ); } } private class BodyTimer : Timer { private Mobile m_Mobile; private SleepingBody m_Body; public BodyTimer( Mobile m, TimeSpan duration, SleepingBody body ) : base( duration ) { m_Mobile = m; m_Body=body; } protected override void OnTick() { m_Mobile.RevealingAction(); m_Mobile.Frozen=false; m_Mobile.Squelched=false; m_Mobile.Z=m_Body.Z; if(m_Body!=null) { m_Body.Delete(); m_Mobile.SendMessage("You wake up!"); } RemoveTimer( m_Mobile ); } } public override bool OnMoveOver( Mobile m ) { if ( Visible && m_Caster != null && SpellHelper.ValidIndirectTarget( m_Caster, m ) && m_Caster.CanBeHarmful( m, false ) ) { ApplySleepTo( m ); m.PlaySound( 0x474 ); } m.Hidden=true; return false; } private class InternalTimer : Timer { private InternalItem m_Item; private bool m_InLOS, m_CanFit; private static Queue m_Queue = new Queue(); public InternalTimer( InternalItem item, TimeSpan delay, bool inLOS, bool canFit ) : base( delay, TimeSpan.FromSeconds( 1.5 ) ) { m_Item = item; m_InLOS = inLOS; m_CanFit = canFit; Priority = TimerPriority.FiftyMS; } protected override void OnTick() { if ( m_Item.Deleted ) return; if ( !m_Item.Visible ) { if ( m_InLOS && m_CanFit ) m_Item.Visible = true; else m_Item.Delete(); if ( !m_Item.Deleted ) { m_Item.ProcessDelta(); Effects.SendLocationParticles( EffectItem.Create( m_Item.Location, m_Item.Map, EffectItem.DefaultDuration ), 0x376A, 9, 10, 5040 ); } } else if ( DateTime.Now > m_Item.m_End ) { m_Item.Delete(); Stop(); } else { Map map = m_Item.Map; Mobile caster = m_Item.m_Caster; if ( map != null && caster != null ) { bool eastToWest = ( m_Item.ItemID == 0x3915 ); IPooledEnumerable eable = map.GetMobilesInBounds( new Rectangle2D( m_Item.X - (eastToWest ? 0 : 1), m_Item.Y - (eastToWest ? 1 : 0), (eastToWest ? 1 : 2), (eastToWest ? 2 : 1) ) );; foreach ( Mobile m in eable ) { if ( (m.Z + 16) > m_Item.Z && (m_Item.Z + 12) > m.Z && SpellHelper.ValidIndirectTarget( caster, m ) && caster.CanBeHarmful( m, false ) ) m_Queue.Enqueue( m ); } eable.Free(); while ( m_Queue.Count > 0 ) { Mobile m = (Mobile)m_Queue.Dequeue(); m.PlaySound( 0x3C4 ); m_Item.ApplySleepTo( m ); } } } } } } private class InternalTarget : Target { private ShieldOfEarthSpell m_Owner; public InternalTarget( ShieldOfEarthSpell owner ) : base( 12, true, TargetFlags.None ) { m_Owner = owner; } protected override void OnTarget( Mobile from, object o ) { if ( o is IPoint3D ) m_Owner.Target( (IPoint3D)o ); } protected override void OnTargetFinish( Mobile from ) { m_Owner.FinishSequence(); } } } }
// 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.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Screens; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Database; using osu.Game.Online.Spectator; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Osu.Replays; using osu.Game.Rulesets.UI; using osu.Game.Screens; using osu.Game.Screens.Play; using osu.Game.Tests.Beatmaps.IO; using osu.Game.Tests.Visual.Multiplayer; using osu.Game.Tests.Visual.Spectator; using osu.Game.Users; namespace osu.Game.Tests.Visual.Gameplay { public class TestSceneSpectator : ScreenTestScene { private readonly User streamingUser = new User { Id = MultiplayerTestScene.PLAYER_1_ID, Username = "Test user" }; [Cached(typeof(UserLookupCache))] private UserLookupCache lookupCache = new TestUserLookupCache(); // used just to show beatmap card for the time being. protected override bool UseOnlineAPI => true; [Resolved] private OsuGameBase game { get; set; } private TestSpectatorClient spectatorClient; private SoloSpectator spectatorScreen; private BeatmapSetInfo importedBeatmap; private int importedBeatmapId; [SetUpSteps] public void SetupSteps() { DependenciesScreen dependenciesScreen = null; AddStep("load dependencies", () => { spectatorClient = new TestSpectatorClient(); // The screen gets suspended so it stops receiving updates. Child = spectatorClient; LoadScreen(dependenciesScreen = new DependenciesScreen(spectatorClient)); }); AddUntilStep("wait for dependencies to load", () => dependenciesScreen.IsLoaded); AddStep("import beatmap", () => { importedBeatmap = ImportBeatmapTest.LoadOszIntoOsu(game, virtualTrack: true).Result; importedBeatmapId = importedBeatmap.Beatmaps.First(b => b.RulesetID == 0).OnlineBeatmapID ?? -1; }); } [Test] public void TestFrameStarvationAndResume() { loadSpectatingScreen(); AddAssert("screen hasn't changed", () => Stack.CurrentScreen is SoloSpectator); start(); waitForPlayer(); sendFrames(); AddAssert("ensure frames arrived", () => replayHandler.HasFrames); AddUntilStep("wait for frame starvation", () => replayHandler.WaitingForFrame); checkPaused(true); double? pausedTime = null; AddStep("store time", () => pausedTime = currentFrameStableTime); sendFrames(); AddUntilStep("wait for frame starvation", () => replayHandler.WaitingForFrame); checkPaused(true); AddAssert("time advanced", () => currentFrameStableTime > pausedTime); } [Test] public void TestPlayStartsWithNoFrames() { loadSpectatingScreen(); start(); waitForPlayer(); checkPaused(true); // send enough frames to ensure play won't be paused sendFrames(100); checkPaused(false); } [Test] public void TestSpectatingDuringGameplay() { start(); sendFrames(300); loadSpectatingScreen(); waitForPlayer(); sendFrames(300); AddUntilStep("playing from correct point in time", () => player.ChildrenOfType<DrawableRuleset>().First().FrameStableClock.CurrentTime > 30000); } [Test] public void TestHostRetriesWhileWatching() { loadSpectatingScreen(); start(); sendFrames(); waitForPlayer(); Player lastPlayer = null; AddStep("store first player", () => lastPlayer = player); start(); sendFrames(); waitForPlayer(); AddAssert("player is different", () => lastPlayer != player); } [Test] public void TestHostFails() { loadSpectatingScreen(); start(); waitForPlayer(); checkPaused(true); finish(); checkPaused(false); // TODO: should replay until running out of frames then fail } [Test] public void TestStopWatchingDuringPlay() { loadSpectatingScreen(); start(); sendFrames(); waitForPlayer(); AddStep("stop spectating", () => (Stack.CurrentScreen as Player)?.Exit()); AddUntilStep("spectating stopped", () => spectatorScreen.GetChildScreen() == null); } [Test] public void TestStopWatchingThenHostRetries() { loadSpectatingScreen(); start(); sendFrames(); waitForPlayer(); AddStep("stop spectating", () => (Stack.CurrentScreen as Player)?.Exit()); AddUntilStep("spectating stopped", () => spectatorScreen.GetChildScreen() == null); // host starts playing a new session start(); waitForPlayer(); } [Test] public void TestWatchingBeatmapThatDoesntExistLocally() { loadSpectatingScreen(); start(-1234); sendFrames(); AddAssert("screen didn't change", () => Stack.CurrentScreen is SoloSpectator); } private OsuFramedReplayInputHandler replayHandler => (OsuFramedReplayInputHandler)Stack.ChildrenOfType<OsuInputManager>().First().ReplayInputHandler; private Player player => Stack.CurrentScreen as Player; private double currentFrameStableTime => player.ChildrenOfType<FrameStabilityContainer>().First().FrameStableClock.CurrentTime; private void waitForPlayer() => AddUntilStep("wait for player", () => (Stack.CurrentScreen as Player)?.IsLoaded == true); private void start(int? beatmapId = null) => AddStep("start play", () => spectatorClient.StartPlay(streamingUser.Id, beatmapId ?? importedBeatmapId)); private void finish() => AddStep("end play", () => spectatorClient.EndPlay(streamingUser.Id)); private void checkPaused(bool state) => AddUntilStep($"game is {(state ? "paused" : "playing")}", () => player.ChildrenOfType<DrawableRuleset>().First().IsPaused.Value == state); private void sendFrames(int count = 10) { AddStep("send frames", () => spectatorClient.SendFrames(streamingUser.Id, count)); } private void loadSpectatingScreen() { AddStep("load spectator", () => LoadScreen(spectatorScreen = new SoloSpectator(streamingUser))); AddUntilStep("wait for screen load", () => spectatorScreen.LoadState == LoadState.Loaded); } /// <summary> /// Used for the sole purpose of adding <see cref="TestSpectatorClient"/> as a resolvable dependency. /// </summary> private class DependenciesScreen : OsuScreen { [Cached(typeof(SpectatorClient))] public readonly TestSpectatorClient Client; public DependenciesScreen(TestSpectatorClient client) { Client = client; } } } }
/* PopupNotify - A MSN-style tray popup notification control. Compatible with .NET 1.1. Copyright (c) 2005 Benjamin Hollis (The 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. */ using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Runtime.InteropServices; using System.Diagnostics; namespace Brh.Forms { /// <summary> /// Summary description for PopupNotify. /// Note: No properties may be changed after Show - don't do it! It won't cause an error but it'll mess you up. /// </summary> public class PopupNotify : System.Windows.Forms.Form { #region Public Variables /// <summary> /// Gets or sets the title text to be displayed in the NotifyWindow. /// </summary> public string Title { get { return NotifyTitle.Text; } set { NotifyTitle.Text = value; } } /// <summary> /// Gets or sets the message text to be displayed in the NotifyWindow. /// </summary> public string Message { get { return NotifyMessage.Text; } set { NotifyMessage.Text = value; } } /// <summary> /// Gets or sets a value specifiying whether or not the window should continue to be displayed if the mouse cursor is inside the bounds /// of the NotifyWindow. /// </summary> public bool WaitOnMouseOver; /// <summary> /// Gets or sets the gradient color which will be blended in drawing the background. Use BackgroundColor for the other gradient color. /// </summary> public System.Drawing.Color GradientColor; /// <summary> /// Gets or sets the amount of milliseconds to display the NotifyWindow for. /// </summary> public int WaitTime; /// <summary> /// Gets or sets the amount of time the slide in/out animations take, in ms. /// </summary> public int AnimateTime; /// <summary> /// Gets or sets the image shown on the left of the popup. /// </summary> public Image IconImage { get { return iconBox.Image; } set { iconBox.Image = value; } } /// <summary> /// Gets or sets the width of the image on the left of the popup. /// </summary> public int IconWidth = 48; /// <summary> /// Gets or sets the width of the image on the right of the popup. /// </summary> public int IconHeight = 48; #endregion #region Private Members private System.ComponentModel.IContainer components; private System.Windows.Forms.PictureBox iconBox; private System.Windows.Forms.Label NotifyTitle; private System.Windows.Forms.Label NotifyMessage; private System.Windows.Forms.Timer displayTimer; private System.Windows.Forms.PictureBox closeButton; private enum SystemTrayLocation { BottomLeft, BottomRight, TopRight }; private System.Drawing.Drawing2D.LinearGradientBrush bBackground = null; private static Bitmap closeCold = null; private static Bitmap closeHot = null; private static Bitmap closeDown = null; private SystemTrayLocation sysLoc; private static ArrayList openPopups = new ArrayList(); #endregion public PopupNotify() : this("", "") { } public PopupNotify(string titleText, string messageText) { // // Required for Windows Form Designer support // InitializeComponent(); Title = titleText; Message = messageText; if(closeCold == null) { closeCold = drawCloseButton(CBS_NORMAL); } if(closeHot == null) { closeHot = drawCloseButton(CBS_HOT); } if(closeDown == null) { closeDown = drawCloseButton(CBS_PUSHED); } closeButton.Image = closeCold; // Default values BackColor = Color.SkyBlue; GradientColor = Color.WhiteSmoke; WaitOnMouseOver = true; WaitTime = 4000; AnimateTime = 250; } private void SetLayout() { int padding = 8; int padding2 = 8; int border = 4; closeButton.Left = Width - padding - border - closeButton.Width + 4; closeButton.Top = padding + border - 3; iconBox.Left = padding + border; iconBox.Top = padding + border; iconBox.Width = IconWidth; iconBox.Height = IconHeight; NotifyTitle.Top = padding + border - 3; NotifyTitle.Left = iconBox.Right + padding2; NotifyTitle.Width = closeButton.Left - NotifyTitle.Left - padding2; NotifyTitle.Height = 16; NotifyMessage.Left = iconBox.Right + padding2; NotifyMessage.Width = closeButton.Left - NotifyMessage.Left - padding2; NotifyMessage.Top = NotifyTitle.Bottom + padding2; NotifyMessage.Height = Height - NotifyMessage.Top - padding - border; } #region Animation and Notification private void Notify() { if(IconImage == null) iconBox.Visible = false; SetLayout(); Rectangle rScreen = Screen.PrimaryScreen.WorkingArea; sysLoc = FindSystemTray(rScreen); if(sysLoc == SystemTrayLocation.BottomRight) { Top = rScreen.Bottom - Height; Left = rScreen.Right - Width; MakeRoom(); SetWindowPos (Handle, HWND_TOPMOST, Left, Top, Width, Height, SWP_NOACTIVATE); AnimateWindow(false, false); } else if(sysLoc == SystemTrayLocation.TopRight) { Top = rScreen.Top; Left = rScreen.Right - Width; MakeRoom(); SetWindowPos (Handle, HWND_TOPMOST, Left, Top, Width, Height, SWP_NOACTIVATE); AnimateWindow(true, false); } else if(sysLoc == SystemTrayLocation.BottomLeft) { Top = rScreen.Bottom - Height; Left = rScreen.Left; MakeRoom(); SetWindowPos (Handle, HWND_TOPMOST, Left, Top, Width, Height, SWP_NOACTIVATE); AnimateWindow(false, false); } lock(openPopups) { openPopups.Add(this); } displayTimer.Interval = WaitTime; displayTimer.Start(); } private void UnNotify() { Rectangle rScreen = Screen.PrimaryScreen.WorkingArea; if(sysLoc == SystemTrayLocation.BottomRight || sysLoc == SystemTrayLocation.BottomLeft) { AnimateWindow(true, true); } else if(sysLoc == SystemTrayLocation.TopRight) { AnimateWindow(false, true); } this.Close(); } private void AnimateWindow(bool positive, bool hide) { AnimateWindowFlags flags = AnimateWindowFlags.AW_SLIDE; if(positive) { flags |= AnimateWindowFlags.AW_VER_POSITIVE; } else { flags |= AnimateWindowFlags.AW_VER_NEGATIVE; } if(hide) { flags |= AnimateWindowFlags.AW_HIDE; } Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); lock(iconBox.Image) { AnimateWindow(Handle, AnimateTime, flags); } Application.ThreadException -= new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); } private void MakeRoom() { lock(openPopups) { foreach(PopupNotify popup in openPopups) { if(sysLoc == SystemTrayLocation.BottomLeft || sysLoc == SystemTrayLocation.BottomRight) { popup.Top -= Height; } else { popup.Top += Height; } } } } private void Collapse() { lock(openPopups) { int thisIndex = openPopups.IndexOf(this); for(int i=thisIndex-1;i >= 0;i--) { PopupNotify popup = (PopupNotify)openPopups[i]; if(sysLoc == SystemTrayLocation.BottomLeft || sysLoc == SystemTrayLocation.BottomLeft) { popup.Top += Height; } else { popup.Top -= Height; } } openPopups.RemoveAt(thisIndex); } } #endregion private SystemTrayLocation FindSystemTray(System.Drawing.Rectangle rcWorkArea) { APPBARDATA appBarData = APPBARDATA.Create(); if(SHAppBarMessage(ABM_GETTASKBARPOS, ref appBarData) != IntPtr.Zero) { RECT taskBarLocation = appBarData.rc; int TaskBarHeight = taskBarLocation.Bottom - taskBarLocation.Top; int TaskBarWidth = taskBarLocation.Right - taskBarLocation.Left; if( TaskBarHeight > TaskBarWidth ) { // Taskbar is vertical if( taskBarLocation.Right > rcWorkArea.Right ) return SystemTrayLocation.BottomRight; else return SystemTrayLocation.BottomLeft; } else { // Taskbar is horizontal if( taskBarLocation.Bottom > rcWorkArea.Bottom ) return SystemTrayLocation.BottomRight; else return SystemTrayLocation.TopRight; } } else { return SystemTrayLocation.BottomRight; //oh well, let's just go default } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form 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(); this.closeButton = new System.Windows.Forms.PictureBox(); this.iconBox = new System.Windows.Forms.PictureBox(); this.NotifyTitle = new System.Windows.Forms.Label(); this.NotifyMessage = new System.Windows.Forms.Label(); this.displayTimer = new System.Windows.Forms.Timer(this.components); this.SuspendLayout(); // // closeButton // this.closeButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.closeButton.BackColor = System.Drawing.Color.Transparent; this.closeButton.Location = new System.Drawing.Point(280, 8); this.closeButton.Name = "closeButton"; this.closeButton.Size = new System.Drawing.Size(16, 16); this.closeButton.TabIndex = 0; this.closeButton.TabStop = false; this.closeButton.Click += new System.EventHandler(this.closeButton_Click); this.closeButton.MouseEnter += new System.EventHandler(this.closeButton_MouseEnter); this.closeButton.MouseLeave += new System.EventHandler(this.closeButton_MouseLeave); this.closeButton.MouseDown += new System.Windows.Forms.MouseEventHandler(this.closeButton_MouseDown); // // iconBox // this.iconBox.BackColor = System.Drawing.Color.Transparent; this.iconBox.Location = new System.Drawing.Point(8, 8); this.iconBox.Name = "iconBox"; this.iconBox.Size = new System.Drawing.Size(50, 50); this.iconBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.iconBox.TabIndex = 1; this.iconBox.TabStop = false; // // NotifyTitle // this.NotifyTitle.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.NotifyTitle.BackColor = System.Drawing.Color.Transparent; this.NotifyTitle.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.NotifyTitle.Location = new System.Drawing.Point(72, 8); this.NotifyTitle.Name = "NotifyTitle"; this.NotifyTitle.Size = new System.Drawing.Size(192, 16); this.NotifyTitle.TabIndex = 2; // // NotifyMessage // this.NotifyMessage.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.NotifyMessage.BackColor = System.Drawing.Color.Transparent; this.NotifyMessage.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.NotifyMessage.Location = new System.Drawing.Point(72, 32); this.NotifyMessage.Name = "NotifyMessage"; this.NotifyMessage.Size = new System.Drawing.Size(224, 70); this.NotifyMessage.TabIndex = 3; // // displayTimer // this.displayTimer.Tick += new System.EventHandler(this.displayTimer_Tick); // // PopupNotify // this.AutoScaleBaseSize = new System.Drawing.Size(5, 14); this.ClientSize = new System.Drawing.Size(304, 112); this.ControlBox = false; this.Controls.Add(this.NotifyMessage); this.Controls.Add(this.NotifyTitle); this.Controls.Add(this.iconBox); this.Controls.Add(this.closeButton); this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "PopupNotify"; this.ShowInTaskbar = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "PopupNotify"; this.TopMost = true; this.Closing += new System.ComponentModel.CancelEventHandler(this.PopupNotify_Closing); this.Load += new System.EventHandler(this.PopupNotify_Load); this.ResumeLayout(false); } #endregion #region Drawing protected override void OnPaintBackground(PaintEventArgs e) { if(bBackground == null) { Rectangle rBackground = new Rectangle(0, 0, this.Width, this.Height); bBackground = new System.Drawing.Drawing2D.LinearGradientBrush(rBackground, BackColor, GradientColor, 90f); } // Getting the graphics object Graphics g = e.Graphics; Rectangle windowRect = new Rectangle(0,0,Width,Height); windowRect.Inflate(-4,-4); // Draw the gradient onto the form g.FillRectangle(bBackground, windowRect); if(BackgroundImage != null) { Rectangle DestRect = new Rectangle(windowRect.Right - BackgroundImage.Width, windowRect.Bottom - BackgroundImage.Height, BackgroundImage.Width, BackgroundImage.Height); e.Graphics.DrawImage(BackgroundImage, DestRect); } // Next draw borders... drawBorder (e.Graphics); } protected virtual void drawBorder (Graphics fx) { fx.DrawRectangle (Pens.Silver, 2, 2, Width - 4, Height - 4); // Top border fx.DrawLine (Pens.Silver, 0, 0, Width, 0); fx.DrawLine (Pens.White, 0, 1, Width, 1); fx.DrawLine (Pens.DarkGray, 3, 3, Width - 4, 3); fx.DrawLine (Pens.DimGray, 4, 4, Width - 5, 4); // Left border fx.DrawLine (Pens.Silver, 0, 0, 0, Height); fx.DrawLine (Pens.White, 1, 1, 1, Height); fx.DrawLine (Pens.DarkGray, 3, 3, 3, Height - 4); fx.DrawLine (Pens.DimGray, 4, 4, 4, Height - 5); // Bottom border fx.DrawLine (Pens.DarkGray, 1, Height - 1, Width - 1, Height - 1); fx.DrawLine (Pens.White, 3, Height - 3, Width - 3, Height - 3); fx.DrawLine (Pens.Silver, 4, Height - 4, Width - 4, Height - 4); // Right border fx.DrawLine (Pens.DarkGray, Width - 1, 1, Width - 1, Height - 1); fx.DrawLine (Pens.White, Width - 3, 3, Width - 3, Height - 3); fx.DrawLine (Pens.Silver, Width - 4, 4, Width - 4, Height - 4); } protected Bitmap drawCloseButton (Int32 state) { if (visualStylesEnabled()) return drawThemeCloseButton (state); else return drawLegacyCloseButton (state); } /// <summary> /// Draw a Windows XP style close button. /// </summary> protected Bitmap drawThemeCloseButton (Int32 state) { Bitmap output = new Bitmap(closeButton.Width, closeButton.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics fx = Graphics.FromImage(output); IntPtr hTheme = OpenThemeData (Handle, "Window"); if (hTheme == IntPtr.Zero) { fx.Dispose(); return drawLegacyCloseButton (state); } Rectangle rClose = new Rectangle(0, 0, closeButton.Width, closeButton.Height); RECT reClose = rClose; RECT reClip = reClose; // should fx.VisibleClipBounds be used here? IntPtr hDC = fx.GetHdc(); DrawThemeBackground (hTheme, hDC, WP_CLOSEBUTTON, state, ref reClose, ref reClip); fx.ReleaseHdc (hDC); fx.DrawImage(output,rClose); CloseThemeData (hTheme); fx.Dispose(); return output; } /// <summary> /// Draw a Windows 95 style close button. /// </summary> protected Bitmap drawLegacyCloseButton (Int32 state) { Bitmap output = new Bitmap(closeButton.Width, closeButton.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics fx = Graphics.FromImage(output); Rectangle rClose = new Rectangle(0, 0, closeButton.Width, closeButton.Height); ButtonState bState; if (state == CBS_PUSHED) bState = ButtonState.Pushed; else // the Windows 95 theme doesn't have a "hot" button bState = ButtonState.Normal; ControlPaint.DrawCaptionButton (fx, rClose, CaptionButton.Close, bState); fx.DrawImage(output, rClose); fx.Dispose(); return output; } /// <summary> /// Determine whether or not XP Visual Styles are active. Compatible with pre-UxTheme.dll versions of Windows. /// </summary> protected bool visualStylesEnabled() { try { if (IsThemeActive() == 1) return true; else return false; } catch (System.DllNotFoundException) // pre-XP systems which don't have UxTheme.dll { return false; } } #endregion #region P/Invoke // DrawThemeBackground() protected const Int32 WP_CLOSEBUTTON = 18; protected const Int32 CBS_NORMAL = 1; protected const Int32 CBS_HOT = 2; protected const Int32 CBS_PUSHED = 3; [StructLayout (LayoutKind.Explicit)] public struct RECT { [FieldOffset (0)] public Int32 Left; [FieldOffset (4)] public Int32 Top; [FieldOffset (8)] public Int32 Right; [FieldOffset (12)] public Int32 Bottom; public RECT (System.Drawing.Rectangle bounds) { Left = bounds.Left; Top = bounds.Top; Right = bounds.Right; Bottom = bounds.Bottom; } public static implicit operator Rectangle( RECT rect ) { return Rectangle.FromLTRB(rect.Left, rect.Top, rect.Right, rect.Bottom); } public static implicit operator RECT( Rectangle rect ) { return new RECT(rect.Left, rect.Top, rect.Right, rect.Bottom); } public RECT(int left_, int top_, int right_, int bottom_) { Left = left_; Top = top_; Right = right_; Bottom = bottom_; } public int Height { get { return Bottom - Top + 1; } } public int Width { get { return Right - Left + 1; } } public Size Size { get { return new Size(Width, Height); } } public Point Location { get { return new Point(Left, Top); } } // Handy method for converting to a System.Drawing.Rectangle public Rectangle ToRectangle() { return Rectangle.FromLTRB(Left, Top, Right, Bottom); } public static RECT FromRectangle(Rectangle rectangle) { return new RECT(rectangle.Left, rectangle.Top, rectangle.Right, rectangle.Bottom); } public override int GetHashCode() { return Left ^ ((Top << 13) | (Top >> 0x13)) ^ ((Width << 0x1a) | (Width >> 6)) ^ ((Height << 7) | (Height >> 0x19)); } } // SetWindowPos() protected const Int32 HWND_TOPMOST = -1; protected const Int32 SWP_NOACTIVATE = 0x0010; // ShowWindow() protected const Int32 SW_SHOWNOACTIVATE = 4; // UxTheme.dll [DllImport ("UxTheme.dll")] protected static extern Int32 IsThemeActive(); [DllImport ("UxTheme.dll")] protected static extern IntPtr OpenThemeData (IntPtr hWnd, [MarshalAs (UnmanagedType.LPTStr)] string classList); [DllImport ("UxTheme.dll")] protected static extern void CloseThemeData (IntPtr hTheme); [DllImport ("UxTheme.dll")] protected static extern void DrawThemeBackground (IntPtr hTheme, IntPtr hDC, Int32 partId, Int32 stateId, ref RECT rect, ref RECT clipRect); // user32.dll [DllImport ("user32.dll")] protected static extern bool ShowWindow (IntPtr hWnd, Int32 flags); [DllImport ("user32.dll")] protected static extern bool SetWindowPos (IntPtr hWnd, Int32 hWndInsertAfter, Int32 X, Int32 Y, Int32 cx, Int32 cy, uint uFlags); [DllImport("user32.dll")] protected static extern bool AnimateWindow(IntPtr hwnd, int time, AnimateWindowFlags flags); // Shell32.dll [DllImport("shell32.dll")] protected static extern IntPtr SHAppBarMessage(uint dwMessage, ref APPBARDATA pData); [StructLayout(LayoutKind.Sequential)] public struct APPBARDATA { public static APPBARDATA Create() { APPBARDATA appBarData = new APPBARDATA(); appBarData.cbSize = Marshal.SizeOf(typeof(APPBARDATA)); return appBarData; } public int cbSize; public IntPtr hWnd; public uint uCallbackMessage; public uint uEdge; public RECT rc; public int lParam; } [Flags] public enum AnimateWindowFlags { AW_HOR_POSITIVE = 0x00000001, AW_HOR_NEGATIVE = 0x00000002, AW_VER_POSITIVE = 0x00000004, AW_VER_NEGATIVE = 0x00000008, AW_CENTER = 0x00000010, AW_HIDE = 0x00010000, AW_ACTIVATE = 0x00020000, AW_SLIDE = 0x00040000, AW_BLEND = 0x00080000 } public const int ABM_QUERYPOS = 0x00000002, ABM_GETTASKBARPOS=5; public const int ABE_LEFT = 0; public const int ABE_TOP = 1; public const int ABE_RIGHT = 2; public const int ABE_BOTTOM = 3; #endregion #region Event Handlers private void closeButton_MouseEnter(object sender, System.EventArgs e) { closeButton.Image = closeHot; } private void closeButton_MouseLeave(object sender, System.EventArgs e) { closeButton.Image = closeCold; } private void closeButton_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { closeButton.Image = closeDown; } private void PopupNotify_Load(object sender, System.EventArgs e) { Notify(); } private void displayTimer_Tick(object sender, System.EventArgs e) { if(this.WaitOnMouseOver && this.Bounds.Contains(Cursor.Position)) { displayTimer.Interval = 1000; //try every second, now } else { displayTimer.Stop(); UnNotify(); } } private void PopupNotify_Closing(object sender, System.ComponentModel.CancelEventArgs e) { Collapse(); bBackground.Dispose(); } private void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) { //do nothing } private void closeButton_Click(object sender, System.EventArgs e) { this.Close(); } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="_ProxyRegBlob.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net { using System; using System.Security.Permissions; using System.Globalization; using System.Text; using System.Collections; using System.Collections.Specialized; using System.Net.Sockets; using System.Threading; using System.Runtime.InteropServices; #if USE_WINIET_AUTODETECT_CACHE #if !FEATURE_PAL using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; #endif // !FEATURE_PAL #endif using Microsoft.Win32; using System.Runtime.Versioning; using System.Diagnostics; internal class RegBlobWebProxyDataBuilder : WebProxyDataBuilder { #if !FEATURE_PAL // // Allows us to grob through the registry and read the // IE binary format, note that this should be replaced, // by code that calls Wininet directly, but it can be // expensive to load wininet, in order to do this. // [Flags] private enum ProxyTypeFlags { PROXY_TYPE_DIRECT = 0x00000001, // direct to net PROXY_TYPE_PROXY = 0x00000002, // via named proxy PROXY_TYPE_AUTO_PROXY_URL = 0x00000004, // autoproxy URL PROXY_TYPE_AUTO_DETECT = 0x00000008, // use autoproxy detection } internal const string PolicyKey = @"SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings"; internal const string ProxyKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Connections"; private const string DefaultConnectionSettings = "DefaultConnectionSettings"; private const string ProxySettingsPerUser = "ProxySettingsPerUser"; #if USE_WINIET_AUTODETECT_CACHE // Get the number of MilliSeconds in 7 days and then multiply by 10 because // FILETIME stores data stores time in 100-nanosecond intervals. // internal static UInt64 s_lkgScriptValidTime = (UInt64)(new TimeSpan(7, 0, 0, 0).Ticks); // 7 days #endif const int IE50StrucSize = 60; private byte[] m_RegistryBytes; private int m_ByteOffset; private string m_Connectoid; private SafeRegistryHandle m_Registry; public RegBlobWebProxyDataBuilder(string connectoid, SafeRegistryHandle registry) { Debug.Assert(registry != null); m_Registry = registry; m_Connectoid = connectoid; } // returns true - on successful read of proxy registry settings [RegistryPermission(SecurityAction.Assert, Read=@"HKEY_LOCAL_MACHINE\" + PolicyKey)] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] private bool ReadRegSettings() { SafeRegistryHandle key = null; RegistryKey lmKey = null; try { bool isPerUser = true; lmKey = Registry.LocalMachine.OpenSubKey(PolicyKey); if (lmKey != null) { object perUser = lmKey.GetValue(ProxySettingsPerUser); if (perUser != null && perUser.GetType() == typeof(int) && 0 == (int) perUser) { isPerUser = false; } } uint errorCode; if (isPerUser) { if (m_Registry != null) { errorCode = m_Registry.RegOpenKeyEx(ProxyKey, 0, UnsafeNclNativeMethods.RegistryHelper.KEY_READ, out key); } else { errorCode = UnsafeNclNativeMethods.ErrorCodes.ERROR_NOT_FOUND; } } else { errorCode = SafeRegistryHandle.RegOpenKeyEx(UnsafeNclNativeMethods.RegistryHelper.HKEY_LOCAL_MACHINE, ProxyKey, 0, UnsafeNclNativeMethods.RegistryHelper.KEY_READ, out key); } if (errorCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS) { key = null; } if (key != null) { // When reading settings from the registry, if connectoid key is missing, the connectoid // was never configured. In this case we have no settings (this is equivalent to always go direct). object data; errorCode = key.QueryValue(m_Connectoid != null ? m_Connectoid : DefaultConnectionSettings, out data); if (errorCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS) { m_RegistryBytes = (byte[]) data; } } } catch (Exception exception) { if (NclUtilities.IsFatal(exception)) throw; } finally { if (lmKey != null) lmKey.Close(); if(key != null) key.RegCloseKey(); } return m_RegistryBytes != null; } #if USE_WINIET_AUTODETECT_CACHE public FILETIME ReadFileTime() { FILETIME ft = new FILETIME(); ft.dwLowDateTime = ReadInt32(); ft.dwHighDateTime = ReadInt32(); return ft; } #endif // // Reads a string from the byte buffer, cached // inside this object, and then updates the // offset, NOTE: Must be in the correct offset // before reading, or will error // public string ReadString() { string stringOut = null; int stringSize = ReadInt32(); if (stringSize>0) { // prevent reading too much int actualSize = m_RegistryBytes.Length - m_ByteOffset; if (stringSize >= actualSize) { stringSize = actualSize; } stringOut = Encoding.UTF8.GetString(m_RegistryBytes, m_ByteOffset, stringSize); m_ByteOffset += stringSize; } return stringOut; } // // Reads a DWORD into a Int32, used to read // a int from the byte buffer. // internal unsafe int ReadInt32() { int intValue = 0; int actualSize = m_RegistryBytes.Length - m_ByteOffset; // copy bytes and increment offset if (actualSize>=sizeof(int)) { fixed (byte* pBuffer = m_RegistryBytes) { if (sizeof(IntPtr)==4) { intValue = *((int*)(pBuffer + m_ByteOffset)); } else { intValue = Marshal.ReadInt32((IntPtr)pBuffer, m_ByteOffset); } } m_ByteOffset += sizeof(int); } // tell caller what we actually read return intValue; } #else // !FEATURE_PAL private static string ReadConfigString(string ConfigName) { const int parameterValueLength = 255; StringBuilder parameterValue = new StringBuilder(parameterValueLength); bool rc = UnsafeNclNativeMethods.FetchConfigurationString(true, ConfigName, parameterValue, parameterValueLength); if (rc) { return parameterValue.ToString(); } return ""; } #endif // !FEATURE_PAL // // Updates an instance of WbeProxy with the proxy settings from IE for: // the current user and a given connectoid. // [ResourceExposure(ResourceScope.Machine)] // Check scoping on this SafeRegistryHandle [ResourceConsumption(ResourceScope.Machine)] protected override void BuildInternal() { GlobalLog.Enter("RegBlobWebProxyDataBuilder#" + ValidationHelper.HashString(this) + "::BuildInternal() m_Connectoid:" + ValidationHelper.ToString(m_Connectoid)); // DON'T TOUCH THE ORDERING OF THE CALLS TO THE INSTANCE OF ProxyRegBlob bool success = ReadRegSettings(); if (success) { success = ReadInt32() >= IE50StrucSize; } if (!success) { // if registry access fails rely on automatic detection SetAutoDetectSettings(true); return; } // read the rest of the items out ReadInt32(); // incremental version# of current settings (ignored) ProxyTypeFlags proxyFlags = (ProxyTypeFlags)ReadInt32(); // flags GlobalLog.Print("RegBlobWebProxyDataBuilder::BuildInternal() proxyFlags:" + ValidationHelper.ToString(proxyFlags)); string addressString = ReadString(); // proxy name string proxyBypassString = ReadString(); // proxy bypass GlobalLog.Print("RegBlobWebProxyDataBuilder::BuildInternal() proxyAddressString:" + ValidationHelper.ToString(addressString) + " proxyBypassString:" + ValidationHelper.ToString(proxyBypassString)); // // Once we verify that the flag for proxy is enabled, // Parse UriString that is stored, may be in the form, // of "http=http://http-proxy;ftp="ftp=http://..." must // handle this case along with just a URI. // if ((proxyFlags & ProxyTypeFlags.PROXY_TYPE_PROXY) != 0) { SetProxyAndBypassList(addressString, proxyBypassString); } #if !FEATURE_PAL SetAutoDetectSettings((proxyFlags & ProxyTypeFlags.PROXY_TYPE_AUTO_DETECT) != 0); string autoConfigUrlString = ReadString(); // autoconfig url GlobalLog.Print("RegBlobWebProxyDataBuilder::BuildInternal() scriptLocation:" + ValidationHelper.ToString(addressString)); if ((proxyFlags & ProxyTypeFlags.PROXY_TYPE_AUTO_PROXY_URL) != 0) { SetAutoProxyUrl(autoConfigUrlString); } // The final straw against attempting to use the WinInet LKG script location was, it's invalid when IPs have changed even if the // connectoid hadn't. Doing that validation didn't seem worth it (error-prone, expensive, unsupported). #if USE_WINIET_AUTODETECT_CACHE proxyIE5Settings.ReadInt32(); // autodetect flags (ignored) // reuse addressString for lkgScriptLocationString addressString = proxyIE5Settings.ReadString(); // last known good auto-proxy url // read ftLastKnownDetectTime FILETIME ftLastKnownDetectTime = proxyIE5Settings.ReadFileTime(); // Verify if this lkgScriptLocationString has timed out // if (IsValidTimeForLkgScriptLocation(ftLastKnownDetectTime)) { // reuse address for lkgScriptLocation GlobalLog.Print("RegBlobWebProxyDataBuilder::BuildInternal() lkgScriptLocation:" + ValidationHelper.ToString(addressString)); if (Uri.TryCreate(addressString, UriKind.Absolute, out address)) { webProxyData.lkgScriptLocation = address; } } else { #if TRAVE SYSTEMTIME st = new SYSTEMTIME(); bool f = SafeNclNativeMethods.FileTimeToSystemTime(ref ftLastKnownDetectTime, ref st); if (f) GlobalLog.Print("RegBlobWebProxyDataBuilder::BuildInternal() ftLastKnownDetectTime:" + ValidationHelper.ToString(st)); #endif // TRAVE GlobalLog.Print("RegBlobWebProxyDataBuilder::BuildInternal() Ignoring Timed out lkgScriptLocation:" + ValidationHelper.ToString(addressString)); // Now rely on automatic detection settings set above // based on the proxy flags (webProxyData.automaticallyDetectSettings). // } #endif /* // This is some of the rest of the proxy reg key blob parsing. // // Read Inte---- IPs int iftCount = proxyIE5Settings.ReadInt32(); for (int ift = 0; ift < iftCount; ++ift) { proxyIE5Settings.ReadInt32(); } // Read lpszAutoconfigSecondaryUrl string autoconfigSecondaryUrl = proxyIE5Settings.ReadString(); // Read dwAutoconfigReloadDelayMins int autoconfigReloadDelayMins = proxyIE5Settings.ReadInt32(); */ #endif GlobalLog.Leave("RegBlobWebProxyDataBuilder#" + ValidationHelper.HashString(this) + "::BuildInternal()"); } #if USE_WINIET_AUTODETECT_CACHE #if !FEATURE_PAL internal unsafe static bool IsValidTimeForLkgScriptLocation(FILETIME ftLastKnownDetectTime) { // Get Current System Time. FILETIME ftCurrentTime = new FILETIME(); SafeNclNativeMethods.GetSystemTimeAsFileTime(ref ftCurrentTime); UInt64 ftDetect = (UInt64)ftLastKnownDetectTime.dwHighDateTime; ftDetect <<= (sizeof(int) * 8); ftDetect |= (UInt64)(uint)ftLastKnownDetectTime.dwLowDateTime; UInt64 ftCurrent = (UInt64)ftCurrentTime.dwHighDateTime; ftCurrent <<= (sizeof(int) * 8); ftCurrent |= (UInt64)(uint)ftCurrentTime.dwLowDateTime; GlobalLog.Print("RegBlobWebProxyDataBuilder::BuildInternal() Detect Time:" + ValidationHelper.ToString(ftDetect)); GlobalLog.Print("RegBlobWebProxyDataBuilder::BuildInternal() Current Time:" + ValidationHelper.ToString(ftCurrent)); GlobalLog.Print("RegBlobWebProxyDataBuilder::BuildInternal() 7 days:" + ValidationHelper.ToString(s_lkgScriptValidTime)); GlobalLog.Print("RegBlobWebProxyDataBuilder::BuildInternal() Delta Time:" + ValidationHelper.ToString((UInt64)(ftCurrent - ftDetect))); return (ftCurrent - ftDetect) < s_lkgScriptValidTime; } #endif // !FEATURE_PAL #endif } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Configuration; using Apache.Ignite.Core.Datastream; using Apache.Ignite.Core.DataStructures; using Apache.Ignite.Core.Events; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Cache; using Apache.Ignite.Core.Impl.Cache.Platform; using Apache.Ignite.Core.Impl.Cluster; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Datastream; using Apache.Ignite.Core.Impl.DataStructures; using Apache.Ignite.Core.Impl.Handle; using Apache.Ignite.Core.Impl.Plugin; using Apache.Ignite.Core.Impl.Transactions; using Apache.Ignite.Core.Impl.Unmanaged; using Apache.Ignite.Core.Interop; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.Messaging; using Apache.Ignite.Core.PersistentStore; using Apache.Ignite.Core.Services; using Apache.Ignite.Core.Transactions; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// Native Ignite wrapper. /// </summary> internal sealed class Ignite : PlatformTargetAdapter, ICluster, IIgniteInternal, IIgnite { /// <summary> /// Operation codes for PlatformProcessorImpl calls. /// </summary> private enum Op { GetCache = 1, CreateCache = 2, GetOrCreateCache = 3, CreateCacheFromConfig = 4, GetOrCreateCacheFromConfig = 5, DestroyCache = 6, GetAffinity = 7, GetDataStreamer = 8, GetTransactions = 9, GetClusterGroup = 10, GetExtension = 11, GetAtomicLong = 12, GetAtomicReference = 13, GetAtomicSequence = 14, GetIgniteConfiguration = 15, GetCacheNames = 16, CreateNearCache = 17, GetOrCreateNearCache = 18, LoggerIsLevelEnabled = 19, LoggerLog = 20, GetBinaryProcessor = 21, ReleaseStart = 22, AddCacheConfiguration = 23, SetBaselineTopologyVersion = 24, SetBaselineTopologyNodes = 25, GetBaselineTopology = 26, DisableWal = 27, EnableWal = 28, IsWalEnabled = 29, SetTxTimeoutOnPartitionMapExchange = 30, GetNodeVersion = 31, IsBaselineAutoAdjustmentEnabled = 32, SetBaselineAutoAdjustmentEnabled = 33, GetBaselineAutoAdjustTimeout = 34, SetBaselineAutoAdjustTimeout = 35, GetCacheConfig = 36, GetThreadLocal = 37, GetOrCreateLock = 38 } /** */ private readonly IgniteConfiguration _cfg; /** Grid name. */ private readonly string _name; /** Unmanaged node. */ private readonly IPlatformTargetInternal _proc; /** Marshaller. */ private readonly Marshaller _marsh; /** Initial projection. */ private readonly ClusterGroupImpl _prj; /** Binary. */ private readonly Binary.Binary _binary; /** Binary processor. */ private readonly BinaryProcessor _binaryProc; /** Lifecycle handlers. */ private readonly IList<LifecycleHandlerHolder> _lifecycleHandlers; /** Local node. */ private volatile IClusterNode _locNode; /** Callbacks */ private readonly UnmanagedCallbacks _cbs; /** Node info cache. */ private readonly ConcurrentDictionary<Guid, ClusterNodeImpl> _nodes = new ConcurrentDictionary<Guid, ClusterNodeImpl>(); /** Client reconnect task completion source. */ private volatile TaskCompletionSource<bool> _clientReconnectTaskCompletionSource = new TaskCompletionSource<bool>(); /** Plugin processor. */ private readonly PluginProcessor _pluginProcessor; /** Platform cache manager. */ private readonly PlatformCacheManager _platformCacheManager; /// <summary> /// Constructor. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="name">Grid name.</param> /// <param name="proc">Interop processor.</param> /// <param name="marsh">Marshaller.</param> /// <param name="lifecycleHandlers">Lifecycle beans.</param> /// <param name="cbs">Callbacks.</param> public Ignite(IgniteConfiguration cfg, string name, IPlatformTargetInternal proc, Marshaller marsh, IList<LifecycleHandlerHolder> lifecycleHandlers, UnmanagedCallbacks cbs) : base(proc) { Debug.Assert(cfg != null); Debug.Assert(proc != null); Debug.Assert(marsh != null); Debug.Assert(lifecycleHandlers != null); Debug.Assert(cbs != null); _cfg = cfg; _name = name; _proc = proc; _marsh = marsh; _lifecycleHandlers = lifecycleHandlers; _cbs = cbs; marsh.Ignite = this; _prj = new ClusterGroupImpl(Target.OutObjectInternal((int) Op.GetClusterGroup), null); _binary = new Binary.Binary(marsh); _binaryProc = new BinaryProcessor(DoOutOpObject((int) Op.GetBinaryProcessor)); cbs.Initialize(this); // Set reconnected task to completed state for convenience. _clientReconnectTaskCompletionSource.SetResult(false); SetCompactFooter(); _pluginProcessor = new PluginProcessor(this); _platformCacheManager = new PlatformCacheManager(this); } /// <summary> /// Sets the compact footer setting. /// </summary> private void SetCompactFooter() { if (!string.IsNullOrEmpty(_cfg.SpringConfigUrl)) { // If there is a Spring config, use setting from Spring, // since we ignore .NET config in legacy mode. var cfg0 = GetConfiguration().BinaryConfiguration; if (cfg0 != null) _marsh.CompactFooter = cfg0.CompactFooter; } } /// <summary> /// On-start routine. /// </summary> internal void OnStart() { PluginProcessor.OnIgniteStart(); foreach (var lifecycleBean in _lifecycleHandlers) lifecycleBean.OnStart(this); } /** <inheritdoc /> */ public string Name { get { return _name; } } /** <inheritdoc /> */ public ICluster GetCluster() { return this; } /** <inheritdoc /> */ IIgnite IClusterGroup.Ignite { get { return this; } } /** <inheritdoc /> */ public IClusterGroup ForLocal() { return _prj.ForNodes(GetLocalNode()); } /** <inheritdoc cref="IIgnite" /> */ public ICompute GetCompute() { return _prj.ForServers().GetCompute(); } /** <inheritdoc /> */ public IgniteProductVersion GetVersion() { return Target.OutStream((int) Op.GetNodeVersion, r => new IgniteProductVersion(r)); } /** <inheritdoc /> */ public IClusterGroup ForNodes(IEnumerable<IClusterNode> nodes) { return _prj.ForNodes(nodes); } /** <inheritdoc /> */ public IClusterGroup ForNodes(params IClusterNode[] nodes) { return _prj.ForNodes(nodes); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(IEnumerable<Guid> ids) { return _prj.ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(params Guid[] ids) { return _prj.ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForPredicate(Func<IClusterNode, bool> p) { IgniteArgumentCheck.NotNull(p, "p"); return _prj.ForPredicate(p); } /** <inheritdoc /> */ public IClusterGroup ForAttribute(string name, string val) { return _prj.ForAttribute(name, val); } /** <inheritdoc /> */ public IClusterGroup ForCacheNodes(string name) { return _prj.ForCacheNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForDataNodes(string name) { return _prj.ForDataNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForClientNodes(string name) { return _prj.ForClientNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForRemotes() { return _prj.ForRemotes(); } /** <inheritdoc /> */ public IClusterGroup ForDaemons() { return _prj.ForDaemons(); } /** <inheritdoc /> */ public IClusterGroup ForHost(IClusterNode node) { IgniteArgumentCheck.NotNull(node, "node"); return _prj.ForHost(node); } /** <inheritdoc /> */ public IClusterGroup ForRandom() { return _prj.ForRandom(); } /** <inheritdoc /> */ public IClusterGroup ForOldest() { return _prj.ForOldest(); } /** <inheritdoc /> */ public IClusterGroup ForYoungest() { return _prj.ForYoungest(); } /** <inheritdoc /> */ public IClusterGroup ForDotNet() { return _prj.ForDotNet(); } /** <inheritdoc /> */ public IClusterGroup ForServers() { return _prj.ForServers(); } /** <inheritdoc /> */ public ICollection<IClusterNode> GetNodes() { return _prj.GetNodes(); } /** <inheritdoc /> */ public IClusterNode GetNode(Guid id) { return _prj.GetNode(id); } /** <inheritdoc /> */ public IClusterNode GetNode() { return _prj.GetNode(); } /** <inheritdoc /> */ public IClusterMetrics GetMetrics() { return _prj.GetMetrics(); } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly", Justification = "There is no finalizer.")] [SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "_proxy", Justification = "Proxy does not need to be disposed.")] public void Dispose() { Ignition.Stop(Name, true); } /// <summary> /// Internal stop routine. /// </summary> /// <param name="cancel">Cancel flag.</param> internal void Stop(bool cancel) { var jniTarget = _proc as PlatformJniTarget; if (jniTarget == null) { throw new IgniteException("Ignition.Stop is not supported in thin client."); } UU.IgnitionStop(Name, cancel); _cbs.Cleanup(); } /// <summary> /// Called before node has stopped. /// </summary> internal void BeforeNodeStop() { var handler = Stopping; if (handler != null) handler.Invoke(this, EventArgs.Empty); } /// <summary> /// Called after node has stopped. /// </summary> internal void AfterNodeStop() { foreach (var bean in _lifecycleHandlers) bean.OnLifecycleEvent(LifecycleEventType.AfterNodeStop); var handler = Stopped; if (handler != null) handler.Invoke(this, EventArgs.Empty); } /** <inheritdoc /> */ public ICache<TK, TV> GetCache<TK, TV>(string name) { IgniteArgumentCheck.NotNull(name, "name"); return GetCache<TK, TV>(DoOutOpObject((int) Op.GetCache, w => w.WriteString(name))); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(string name) { IgniteArgumentCheck.NotNull(name, "name"); return GetCache<TK, TV>(DoOutOpObject((int) Op.GetOrCreateCache, w => w.WriteString(name))); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration) { return GetOrCreateCache<TK, TV>(configuration, null); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration) { return GetOrCreateCache<TK, TV>(configuration, nearConfiguration, null); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration, PlatformCacheConfiguration platformCacheConfiguration) { return GetOrCreateCache<TK, TV>(configuration, nearConfiguration, platformCacheConfiguration, Op.GetOrCreateCacheFromConfig); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(string name) { IgniteArgumentCheck.NotNull(name, "name"); var cacheTarget = DoOutOpObject((int) Op.CreateCache, w => w.WriteString(name)); return GetCache<TK, TV>(cacheTarget); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration) { return CreateCache<TK, TV>(configuration, null); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration) { return CreateCache<TK, TV>(configuration, nearConfiguration, null); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration, PlatformCacheConfiguration platformCacheConfiguration) { return GetOrCreateCache<TK, TV>(configuration, nearConfiguration, platformCacheConfiguration, Op.CreateCacheFromConfig); } /// <summary> /// Gets or creates the cache. /// </summary> private ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration, PlatformCacheConfiguration platformCacheConfiguration, Op op) { IgniteArgumentCheck.NotNull(configuration, "configuration"); IgniteArgumentCheck.NotNull(configuration.Name, "CacheConfiguration.Name"); configuration.Validate(Logger); var cacheTarget = DoOutOpObject((int) op, s => { var w = BinaryUtils.Marshaller.StartMarshal(s); configuration.Write(w); if (nearConfiguration != null) { w.WriteBoolean(true); nearConfiguration.Write(w); } else { w.WriteBoolean(false); } if (platformCacheConfiguration != null) { w.WriteBoolean(true); platformCacheConfiguration.Write(w); } else { w.WriteBoolean(false); } }); return GetCache<TK, TV>(cacheTarget); } /** <inheritdoc /> */ public void DestroyCache(string name) { IgniteArgumentCheck.NotNull(name, "name"); DoOutOp((int) Op.DestroyCache, w => w.WriteString(name)); } /// <summary> /// Gets cache from specified native cache object. /// </summary> /// <param name="nativeCache">Native cache.</param> /// <param name="keepBinary">Keep binary flag.</param> /// <returns> /// New instance of cache wrapping specified native cache. /// </returns> public static ICache<TK, TV> GetCache<TK, TV>(IPlatformTargetInternal nativeCache, bool keepBinary = false) { return new CacheImpl<TK, TV>(nativeCache, false, keepBinary, false, false); } /** <inheritdoc /> */ public IClusterNode GetLocalNode() { return _locNode ?? (_locNode = GetNodes().FirstOrDefault(x => x.IsLocal) ?? ForDaemons().GetNodes().FirstOrDefault(x => x.IsLocal)); } /** <inheritdoc /> */ public bool PingNode(Guid nodeId) { return _prj.PingNode(nodeId); } /** <inheritdoc /> */ public long TopologyVersion { get { return _prj.TopologyVersion; } } /** <inheritdoc /> */ public ICollection<IClusterNode> GetTopology(long ver) { return _prj.Topology(ver); } /** <inheritdoc /> */ public void ResetMetrics() { _prj.ResetMetrics(); } /** <inheritdoc /> */ public Task<bool> ClientReconnectTask { get { return _clientReconnectTaskCompletionSource.Task; } } /** <inheritdoc /> */ public IDataStreamer<TK, TV> GetDataStreamer<TK, TV>(string cacheName) { IgniteArgumentCheck.NotNull(cacheName, "cacheName"); return GetDataStreamer<TK, TV>(cacheName, false); } /// <summary> /// Gets the data streamer. /// </summary> public IDataStreamer<TK, TV> GetDataStreamer<TK, TV>(string cacheName, bool keepBinary) { var streamerTarget = DoOutOpObject((int) Op.GetDataStreamer, w => { w.WriteString(cacheName); w.WriteBoolean(keepBinary); }); return new DataStreamerImpl<TK, TV>(streamerTarget, _marsh, cacheName, keepBinary); } /// <summary> /// Gets the public Ignite interface. /// </summary> public IIgnite GetIgnite() { return this; } /** <inheritdoc cref="IIgnite" /> */ public IBinary GetBinary() { return _binary; } /** <inheritdoc /> */ CacheAffinityImpl IIgniteInternal.GetAffinity(string cacheName) { IgniteArgumentCheck.NotNull(cacheName, "cacheName"); var aff = DoOutOpObject((int) Op.GetAffinity, w => w.WriteString(cacheName)); return new CacheAffinityImpl(aff, false); } /** <inheritdoc /> */ public ICacheAffinity GetAffinity(string cacheName) { return ((IIgniteInternal) this).GetAffinity(cacheName); } /** <inheritdoc /> */ public ITransactions GetTransactions() { return new TransactionsImpl(this, DoOutOpObject((int) Op.GetTransactions), GetLocalNode().Id); } /** <inheritdoc cref="IIgnite" /> */ public IMessaging GetMessaging() { return _prj.GetMessaging(); } /** <inheritdoc cref="IIgnite" /> */ public IEvents GetEvents() { return _prj.GetEvents(); } /** <inheritdoc cref="IIgnite" /> */ public IServices GetServices() { return _prj.ForServers().GetServices(); } /** <inheritdoc /> */ public void EnableStatistics(IEnumerable<string> cacheNames, bool enabled) { _prj.EnableStatistics(cacheNames, enabled); } /** <inheritdoc /> */ public void ClearStatistics(IEnumerable<string> caches) { _prj.ClearStatistics(caches); } /** <inheritdoc /> */ public IAtomicLong GetAtomicLong(string name, long initialValue, bool create) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); var nativeLong = DoOutOpObject((int) Op.GetAtomicLong, w => { w.WriteString(name); w.WriteLong(initialValue); w.WriteBoolean(create); }); if (nativeLong == null) return null; return new AtomicLong(nativeLong, name); } /** <inheritdoc /> */ public IAtomicSequence GetAtomicSequence(string name, long initialValue, bool create) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); var nativeSeq = DoOutOpObject((int) Op.GetAtomicSequence, w => { w.WriteString(name); w.WriteLong(initialValue); w.WriteBoolean(create); }); if (nativeSeq == null) return null; return new AtomicSequence(nativeSeq, name); } /** <inheritdoc /> */ public IAtomicReference<T> GetAtomicReference<T>(string name, T initialValue, bool create) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); var refTarget = DoOutOpObject((int) Op.GetAtomicReference, w => { w.WriteString(name); w.WriteObject(initialValue); w.WriteBoolean(create); }); return refTarget == null ? null : new AtomicReference<T>(refTarget, name); } /** <inheritdoc /> */ public IgniteConfiguration GetConfiguration() { return DoInOp((int) Op.GetIgniteConfiguration, s => new IgniteConfiguration(BinaryUtils.Marshaller.StartUnmarshal(s), _cfg)); } /** <inheritdoc /> */ public ICache<TK, TV> CreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration) { return GetOrCreateNearCache0<TK, TV>(name, configuration, null, Op.CreateNearCache); } /** <inheritdoc /> */ public ICache<TK, TV> CreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration, PlatformCacheConfiguration platformConfiguration) { return GetOrCreateNearCache0<TK, TV>(name, configuration, platformConfiguration, Op.CreateNearCache); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration) { return GetOrCreateNearCache0<TK, TV>(name, configuration, null, Op.GetOrCreateNearCache); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration, PlatformCacheConfiguration platformConfiguration) { return GetOrCreateNearCache0<TK, TV>(name, configuration, platformConfiguration, Op.GetOrCreateNearCache); } /** <inheritdoc /> */ public ICollection<string> GetCacheNames() { return Target.OutStream((int) Op.GetCacheNames, r => { var res = new string[r.ReadInt()]; for (var i = 0; i < res.Length; i++) res[i] = r.ReadString(); return (ICollection<string>) res; }); } /** <inheritdoc /> */ public CacheConfiguration GetCacheConfiguration(int cacheId) { return Target.InStreamOutStream((int) Op.GetCacheConfig, w => w.WriteInt(cacheId), s => new CacheConfiguration(BinaryUtils.Marshaller.StartUnmarshal(s))); } /** <inheritdoc /> */ public object GetJavaThreadLocal() { return Target.OutStream((int) Op.GetThreadLocal, r => r.ReadObject<object>()); } /** <inheritdoc /> */ public ILogger Logger { get { return _cbs.Log; } } /** <inheritdoc /> */ public event EventHandler Stopping; /** <inheritdoc /> */ public event EventHandler Stopped; /** <inheritdoc /> */ public event EventHandler ClientDisconnected; /** <inheritdoc /> */ public event EventHandler<ClientReconnectEventArgs> ClientReconnected; /** <inheritdoc /> */ public T GetPlugin<T>(string name) where T : class { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); return PluginProcessor.GetProvider(name).GetPlugin<T>(); } /** <inheritdoc /> */ public void ResetLostPartitions(IEnumerable<string> cacheNames) { IgniteArgumentCheck.NotNull(cacheNames, "cacheNames"); _prj.ResetLostPartitions(cacheNames); } /** <inheritdoc /> */ public void ResetLostPartitions(params string[] cacheNames) { ResetLostPartitions((IEnumerable<string>) cacheNames); } /** <inheritdoc /> */ #pragma warning disable 618 public ICollection<IMemoryMetrics> GetMemoryMetrics() { return _prj.GetMemoryMetrics(); } /** <inheritdoc /> */ public IMemoryMetrics GetMemoryMetrics(string memoryPolicyName) { IgniteArgumentCheck.NotNullOrEmpty(memoryPolicyName, "memoryPolicyName"); return _prj.GetMemoryMetrics(memoryPolicyName); } #pragma warning restore 618 /** <inheritdoc cref="IIgnite" /> */ public void SetActive(bool isActive) { _prj.SetActive(isActive); } /** <inheritdoc cref="IIgnite" /> */ public bool IsActive() { return _prj.IsActive(); } /** <inheritdoc /> */ public void SetBaselineTopology(long topologyVersion) { DoOutInOp((int) Op.SetBaselineTopologyVersion, topologyVersion); } /** <inheritdoc /> */ public void SetBaselineTopology(IEnumerable<IBaselineNode> nodes) { IgniteArgumentCheck.NotNull(nodes, "nodes"); DoOutOp((int) Op.SetBaselineTopologyNodes, w => { var pos = w.Stream.Position; w.WriteInt(0); var cnt = 0; foreach (var node in nodes) { cnt++; BaselineNode.Write(w, node); } w.Stream.WriteInt(pos, cnt); }); } /** <inheritdoc /> */ public ICollection<IBaselineNode> GetBaselineTopology() { return DoInOp((int) Op.GetBaselineTopology, s => Marshaller.StartUnmarshal(s).ReadCollectionRaw(r => (IBaselineNode) new BaselineNode(r))); } /** <inheritdoc /> */ public void DisableWal(string cacheName) { IgniteArgumentCheck.NotNull(cacheName, "cacheName"); DoOutOp((int) Op.DisableWal, w => w.WriteString(cacheName)); } /** <inheritdoc /> */ public void EnableWal(string cacheName) { IgniteArgumentCheck.NotNull(cacheName, "cacheName"); DoOutOp((int) Op.EnableWal, w => w.WriteString(cacheName)); } /** <inheritdoc /> */ public bool IsWalEnabled(string cacheName) { IgniteArgumentCheck.NotNull(cacheName, "cacheName"); return DoOutOp((int) Op.IsWalEnabled, w => w.WriteString(cacheName)) == True; } /** <inheritdoc /> */ public void SetTxTimeoutOnPartitionMapExchange(TimeSpan timeout) { DoOutOp((int) Op.SetTxTimeoutOnPartitionMapExchange, (BinaryWriter w) => w.WriteLong((long) timeout.TotalMilliseconds)); } /** <inheritdoc /> */ public bool IsBaselineAutoAdjustEnabled() { return DoOutOp((int) Op.IsBaselineAutoAdjustmentEnabled, s => s.ReadBool()) == True; } /** <inheritdoc /> */ public void SetBaselineAutoAdjustEnabledFlag(bool isBaselineAutoAdjustEnabled) { DoOutOp((int) Op.SetBaselineAutoAdjustmentEnabled, w => w.WriteBoolean(isBaselineAutoAdjustEnabled)); } /** <inheritdoc /> */ public long GetBaselineAutoAdjustTimeout() { return DoOutOp((int) Op.GetBaselineAutoAdjustTimeout, s => s.ReadLong()); } /** <inheritdoc /> */ public void SetBaselineAutoAdjustTimeout(long baselineAutoAdjustTimeout) { DoOutInOp((int) Op.SetBaselineAutoAdjustTimeout, baselineAutoAdjustTimeout); } /** <inheritdoc /> */ #pragma warning disable 618 public IPersistentStoreMetrics GetPersistentStoreMetrics() { return _prj.GetPersistentStoreMetrics(); } #pragma warning restore 618 /** <inheritdoc /> */ public ICollection<IDataRegionMetrics> GetDataRegionMetrics() { return _prj.GetDataRegionMetrics(); } /** <inheritdoc /> */ public IDataRegionMetrics GetDataRegionMetrics(string memoryPolicyName) { return _prj.GetDataRegionMetrics(memoryPolicyName); } /** <inheritdoc /> */ public IDataStorageMetrics GetDataStorageMetrics() { return _prj.GetDataStorageMetrics(); } /** <inheritdoc /> */ public void AddCacheConfiguration(CacheConfiguration configuration) { IgniteArgumentCheck.NotNull(configuration, "configuration"); DoOutOp((int) Op.AddCacheConfiguration, s => configuration.Write(BinaryUtils.Marshaller.StartMarshal(s))); } /** <inheritdoc /> */ public IIgniteLock GetOrCreateLock(string name) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); var configuration = new LockConfiguration { Name = name }; return GetOrCreateLock(configuration, true); } /** <inheritdoc /> */ public IIgniteLock GetOrCreateLock(LockConfiguration configuration, bool create) { IgniteArgumentCheck.NotNull(configuration, "configuration"); IgniteArgumentCheck.NotNullOrEmpty(configuration.Name, "configuration.Name"); // Create a copy to ignore modifications from outside. var cfg = new LockConfiguration(configuration); var target = DoOutOpObject((int) Op.GetOrCreateLock, w => { w.WriteString(configuration.Name); w.WriteBoolean(configuration.IsFailoverSafe); w.WriteBoolean(configuration.IsFair); w.WriteBoolean(create); }); return target == null ? null : new IgniteLock(target, cfg); } /// <summary> /// Gets or creates near cache. /// </summary> private ICache<TK, TV> GetOrCreateNearCache0<TK, TV>(string name, NearCacheConfiguration configuration, PlatformCacheConfiguration platformConfiguration, Op op) { IgniteArgumentCheck.NotNull(configuration, "configuration"); var cacheTarget = DoOutOpObject((int) op, w => { w.WriteString(name); configuration.Write(w); if (platformConfiguration != null) { w.WriteBoolean(true); platformConfiguration.Write(w); } else { w.WriteBoolean(false); } }); return GetCache<TK, TV>(cacheTarget); } /// <summary> /// Gets internal projection. /// </summary> /// <returns>Projection.</returns> public ClusterGroupImpl ClusterGroup { get { return _prj; } } /// <summary> /// Gets the binary processor. /// </summary> public IBinaryProcessor BinaryProcessor { get { return _binaryProc; } } /// <summary> /// Configuration. /// </summary> public IgniteConfiguration Configuration { get { return _cfg; } } /// <summary> /// Handle registry. /// </summary> public HandleRegistry HandleRegistry { get { return _cbs.HandleRegistry; } } /// <summary> /// Gets the platform cache manager. /// </summary> public PlatformCacheManager PlatformCacheManager { get { return _platformCacheManager; } } /// <summary> /// Updates the node information from stream. /// </summary> /// <param name="memPtr">Stream ptr.</param> public void UpdateNodeInfo(long memPtr) { var stream = IgniteManager.Memory.Get(memPtr).GetStream(); IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); var node = new ClusterNodeImpl(reader); node.Init(this); _nodes[node.Id] = node; } /// <summary> /// Returns instance of Ignite Transactions to mark a transaction with a special label. /// </summary> /// <param name="label"></param> /// <returns><see cref="ITransactions"/></returns> internal ITransactions GetTransactionsWithLabel(string label) { Debug.Assert(label != null); var platformTargetInternal = DoOutOpObject((int) Op.GetTransactions, s => { var w = BinaryUtils.Marshaller.StartMarshal(s); w.WriteString(label); }); return new TransactionsImpl(this, platformTargetInternal, GetLocalNode().Id, label); } /// <summary> /// Gets the node from cache. /// </summary> /// <param name="id">Node id.</param> /// <returns>Cached node.</returns> public ClusterNodeImpl GetNode(Guid? id) { return id == null ? null : _nodes[id.Value]; } /// <summary> /// Gets the interop processor. /// </summary> internal IPlatformTargetInternal InteropProcessor { get { return _proc; } } /// <summary> /// Called when local client node has been disconnected from the cluster. /// </summary> internal void OnClientDisconnected() { // Clear cached node data. // Do not clear _nodes - it is in sync with PlatformContextImpl.sentNodes. _locNode = null; _prj.ClearCachedNodeData(); // Raise events. _clientReconnectTaskCompletionSource = new TaskCompletionSource<bool>(); var handler = ClientDisconnected; if (handler != null) handler.Invoke(this, EventArgs.Empty); } /// <summary> /// Called when local client node has been reconnected to the cluster. /// </summary> /// <param name="clusterRestarted">Cluster restarted flag.</param> internal void OnClientReconnected(bool clusterRestarted) { _marsh.OnClientReconnected(clusterRestarted); _clientReconnectTaskCompletionSource.TrySetResult(clusterRestarted); var handler = ClientReconnected; if (handler != null) handler.Invoke(this, new ClientReconnectEventArgs(clusterRestarted)); } /// <summary> /// Gets the plugin processor. /// </summary> public PluginProcessor PluginProcessor { get { return _pluginProcessor; } } /// <summary> /// Notify processor that it is safe to use. /// </summary> internal void ProcessorReleaseStart() { Target.InLongOutLong((int) Op.ReleaseStart, 0); } /// <summary> /// Checks whether log level is enabled in Java logger. /// </summary> internal bool LoggerIsLevelEnabled(LogLevel logLevel) { return Target.InLongOutLong((int) Op.LoggerIsLevelEnabled, (long) logLevel) == True; } /// <summary> /// Logs to the Java logger. /// </summary> internal void LoggerLog(LogLevel level, string msg, string category, string err) { Target.InStreamOutLong((int) Op.LoggerLog, w => { w.WriteInt((int) level); w.WriteString(msg); w.WriteString(category); w.WriteString(err); }); } /// <summary> /// Gets the platform plugin extension. /// </summary> internal IPlatformTarget GetExtension(int id) { return ((IPlatformTarget) Target).InStreamOutObject((int) Op.GetExtension, w => w.WriteInt(id)); } /** <inheritdoc /> */ public override string ToString() { return string.Format("Ignite [Name={0}]", _name); } } }
// 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.Linq; using System.Xml.Linq; using Microsoft.Test.ModuleCore; namespace CoreXml.Test.XLinq { public partial class FunctionalTests : TestModule { public partial class EventsTests : XLinqTestCase { public partial class EventsXObjectValue : EventsBase { //[Variation(Priority = 0, Desc = "XText - change value")] public void XTextValue() { XText toChange = new XText("Original Value"); String newValue = "New Value"; XElement xElem = new XElement("root", toChange); XElement xElemOriginal = new XElement(xElem); using (UndoManager undo = new UndoManager(xElem)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(xElem)) { using (EventsHelper textHelper = new EventsHelper(toChange)) { toChange.Value = newValue; TestLog.Compare(toChange.Value.Equals(newValue), "Value did not change"); xElem.Verify(); textHelper.Verify(XObjectChange.Value, toChange); } eHelper.Verify(XObjectChange.Value, toChange); } undo.Undo(); TestLog.Compare(XNode.DeepEquals(xElem, xElemOriginal), "Undo did not work!"); } } //[Variation(Priority = 0, Desc = "XCData - change value")] public void XCDataValue() { XCData toChange = new XCData("Original Value"); String newValue = "New Value"; XElement xElem = new XElement("root", toChange); XElement xElemOriginal = new XElement(xElem); using (UndoManager undo = new UndoManager(xElem)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(xElem)) { using (EventsHelper dataHelper = new EventsHelper(toChange)) { toChange.Value = newValue; TestLog.Compare(toChange.Value.Equals(newValue), "Value did not change"); xElem.Verify(); dataHelper.Verify(XObjectChange.Value, toChange); } eHelper.Verify(XObjectChange.Value, toChange); } undo.Undo(); TestLog.Compare(XNode.DeepEquals(xElem, xElemOriginal), "Undo did not work!"); } } //[Variation(Priority = 0, Desc = "XComment - change value")] public void XCommentValue() { XComment toChange = new XComment("Original Value"); String newValue = "New Value"; XElement xElem = new XElement("root", toChange); XElement xElemOriginal = new XElement(xElem); using (UndoManager undo = new UndoManager(xElem)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(xElem)) { using (EventsHelper comHelper = new EventsHelper(toChange)) { toChange.Value = newValue; TestLog.Compare(toChange.Value.Equals(newValue), "Value did not change"); xElem.Verify(); comHelper.Verify(XObjectChange.Value, toChange); } eHelper.Verify(XObjectChange.Value, toChange); } undo.Undo(); TestLog.Compare(XNode.DeepEquals(xElem, xElemOriginal), "Undo did not work!"); } } //[Variation(Priority = 0, Desc = "XProcessingInstruction - change value")] public void XPIValue() { XProcessingInstruction toChange = new XProcessingInstruction("target", "Original Value"); String newValue = "New Value"; XElement xElem = new XElement("root", toChange); XElement xElemOriginal = new XElement(xElem); using (UndoManager undo = new UndoManager(xElem)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(xElem)) { using (EventsHelper piHelper = new EventsHelper(toChange)) { toChange.Data = newValue; TestLog.Compare(toChange.Data.Equals(newValue), "Value did not change"); xElem.Verify(); piHelper.Verify(XObjectChange.Value, toChange); } eHelper.Verify(XObjectChange.Value, toChange); } undo.Undo(); TestLog.Compare(XNode.DeepEquals(xElem, xElemOriginal), "Undo did not work!"); } } //[Variation(Priority = 0, Desc = "XDocumentType - change public Id")] public void XDocTypePublicID() { XDocumentType toChange = new XDocumentType("root", "", "", ""); XDocument xDoc = new XDocument(toChange); XDocument xDocOriginal = new XDocument(xDoc); using (EventsHelper docHelper = new EventsHelper(xDoc)) { using (EventsHelper typeHelper = new EventsHelper(toChange)) { toChange.PublicId = "newValue"; TestLog.Compare(toChange.PublicId.Equals("newValue"), "PublicID did not change"); typeHelper.Verify(XObjectChange.Value, toChange); } docHelper.Verify(XObjectChange.Value, toChange); } } //[Variation(Priority = 0, Desc = "XDocumentType - change system Id")] public void XDocTypeSystemID() { XDocumentType toChange = new XDocumentType("root", "", "", ""); XDocument xDoc = new XDocument(toChange); XDocument xDocOriginal = new XDocument(xDoc); using (EventsHelper docHelper = new EventsHelper(xDoc)) { using (EventsHelper typeHelper = new EventsHelper(toChange)) { toChange.SystemId = "newValue"; TestLog.Compare(toChange.SystemId.Equals("newValue"), "SystemID did not change"); typeHelper.Verify(XObjectChange.Value, toChange); } docHelper.Verify(XObjectChange.Value, toChange); } } //[Variation(Priority = 0, Desc = "XDocumentType - change internal subset")] public void XDocTypeInternalSubset() { XDocumentType toChange = new XDocumentType("root", "", "", ""); XDocument xDoc = new XDocument(toChange); XDocument xDocOriginal = new XDocument(xDoc); using (EventsHelper docHelper = new EventsHelper(xDoc)) { using (EventsHelper typeHelper = new EventsHelper(toChange)) { toChange.InternalSubset = "newValue"; TestLog.Compare(toChange.InternalSubset.Equals("newValue"), "Internal Subset did not change"); typeHelper.Verify(XObjectChange.Value, toChange); } docHelper.Verify(XObjectChange.Value, toChange); } } } public partial class EventsXElementValue : EventsBase { protected override void DetermineChildren() { VariationsForXElement(ExecuteXElementVariation); base.DetermineChildren(); } void VariationsForXElement(TestFunc func) { AddChild(func, 0, "Empty element", new XElement("element"), "newValue"); AddChild(func, 0, "Element with string", new XElement("element", "value"), "newValue"); AddChild(func, 0, "Element with attributes", new XElement("element", new XAttribute("a", "aa")), "newValue"); AddChild(func, 0, "Element with nodes", new XElement("parent", new XElement("child", "child text")), "newValue"); AddChild(func, 1, "Element with IEnumerable of XNodes", new XElement("root", InputSpace.GetElement(100, 10).DescendantNodes()), "newValue"); } public void ExecuteXElementVariation() { XElement toChange = Variation.Params[0] as XElement; int count = toChange.Nodes().Count(); String newValue = Variation.Params[1] as String; XElement xElem = new XElement("root", toChange); XElement xElemOriginal = new XElement(xElem); using (UndoManager undo = new UndoManager(xElem)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(toChange)) { toChange.Value = newValue; TestLog.Compare(toChange.Value == newValue, "Value change was not correct"); toChange.Verify(); eHelper.Verify(count + 1); } undo.Undo(); TestLog.Compare(xElem.Nodes().SequenceEqual(xElemOriginal.Nodes(), XNode.EqualityComparer), "Undo did not work!"); TestLog.Compare(xElem.Attributes().EqualsAllAttributes(xElemOriginal.Attributes(), Helpers.MyAttributeComparer), "Undo did not work!"); } } } public partial class EventsXAttributeValue : EventsBase { protected override void DetermineChildren() { VariationsForXAttribute(ExecuteXAttributeVariation); base.DetermineChildren(); } void VariationsForXAttribute(TestFunc func) { AddChild(func, 0, "Attribute with empty string as value", new XAttribute("xxx", ""), "newValue"); AddChild(func, 0, "Attribute with value", new XAttribute("xxx", "yyy"), "newValue"); AddChild(func, 0, "Attribute with namespace and value", new XAttribute("{a}xxx", "a_yyy"), "newValue"); } public void ExecuteXAttributeVariation() { XAttribute toChange = Variation.Params[0] as XAttribute; String newValue = Variation.Params[1] as String; XElement xElem = new XElement("root", toChange); XElement xElemOriginal = new XElement(xElem); using (UndoManager undo = new UndoManager(xElem)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(toChange)) { toChange.Value = newValue; TestLog.Compare(toChange.Value.Equals(newValue), "Value did not change"); xElem.Verify(); eHelper.Verify(XObjectChange.Value, toChange); } undo.Undo(); TestLog.Compare(xElem.Nodes().SequenceEqual(xElemOriginal.Nodes(), XNode.EqualityComparer), "Undo did not work!"); TestLog.Compare(xElem.Attributes().EqualsAllAttributes(xElemOriginal.Attributes(), Helpers.MyAttributeComparer), "Undo did not work!"); } } } public partial class EventsXAttributeSetValue : EventsBase { protected override void DetermineChildren() { VariationsForXAttribute(ExecuteXAttributeVariation); base.DetermineChildren(); } void VariationsForXAttribute(TestFunc func) { AddChild(func, 0, "Empty value, string", new XAttribute("xxx", ""), "newValue"); AddChild(func, 0, "String, String", new XAttribute("xxx", "yyy"), "newValue"); AddChild(func, 0, "Attribute with namespace, String", new XAttribute("{a}xxx", "a_yyy"), "newValue"); } public void ExecuteXAttributeVariation() { XAttribute toChange = Variation.Params[0] as XAttribute; Object newValue = Variation.Params[1]; XElement xElem = new XElement("root", toChange); XElement xElemOriginal = new XElement(xElem); using (UndoManager undo = new UndoManager(xElem)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(toChange)) { toChange.SetValue(newValue); TestLog.Compare(newValue.Equals(toChange.Value), "Value did not change"); xElem.Verify(); eHelper.Verify(XObjectChange.Value, toChange); } undo.Undo(); TestLog.Compare(xElem.Nodes().SequenceEqual(xElemOriginal.Nodes(), XNode.EqualityComparer), "Undo did not work!"); TestLog.Compare(xElem.Attributes().EqualsAllAttributes(xElemOriginal.Attributes(), Helpers.MyAttributeComparer), "Undo did not work!"); } } } public partial class EventsXElementSetValue : EventsBase { protected override void DetermineChildren() { VariationsForXElement(ExecuteXElementVariation); base.DetermineChildren(); } void VariationsForXElement(TestFunc func) { AddChild(func, 0, "Empty element, String", new XElement("element"), "newValue"); AddChild(func, 0, "String, String", new XElement("element", "value"), "newValue"); AddChild(func, 0, "Element with attributes, String", new XElement("element", new XAttribute("a", "aa")), "newValue"); AddChild(func, 0, "Element with child, String", new XElement("parent", new XElement("child", "child text")), "newValue"); AddChild(func, 1, "Element with nodes", new XElement("root", InputSpace.GetElement(100, 10).DescendantNodes()), "newValue"); } public void ExecuteXElementVariation() { XElement toChange = Variation.Params[0] as XElement; int count = toChange.Nodes().Count(); Object newValue = Variation.Params[1]; XElement xElemOriginal = new XElement(toChange); using (UndoManager undo = new UndoManager(toChange)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(toChange)) { toChange.SetValue(newValue); TestLog.Compare(newValue.Equals(toChange.Value), "Value change was not correct"); toChange.Verify(); eHelper.Verify(count + 1); } undo.Undo(); TestLog.Compare(toChange.Nodes().SequenceEqual(xElemOriginal.Nodes(), XNode.EqualityComparer), "Undo did not work!"); TestLog.Compare(toChange.Attributes().EqualsAllAttributes(xElemOriginal.Attributes(), Helpers.MyAttributeComparer), "Undo did not work!"); } } } public partial class EventsXElementSetAttributeValue : EventsBase { protected override void DetermineChildren() { VariationsForXAttribute(ExecuteXAttributeVariation); base.DetermineChildren(); } void VariationsForXAttribute(TestFunc func) { AddChild(func, 0, "Empty value, string", new XAttribute("xxx", ""), "newValue"); AddChild(func, 0, "String, String", new XAttribute("xxx", "yyy"), "newValue"); AddChild(func, 0, "Attribute with namespace, String", new XAttribute("{a}xxx", "a_yyy"), "newValue"); } public void ExecuteXAttributeVariation() { XAttribute toChange = Variation.Params[0] as XAttribute; Object newValue = Variation.Params[1]; XElement xElem = new XElement("root", toChange); XElement xElemOriginal = new XElement(xElem); using (UndoManager undo = new UndoManager(xElem)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(toChange)) { xElem.SetAttributeValue(toChange.Name, newValue); TestLog.Compare(newValue.Equals(toChange.Value), "Value did not change"); xElem.Verify(); eHelper.Verify(XObjectChange.Value, toChange); } undo.Undo(); TestLog.Compare(xElem.Nodes().SequenceEqual(xElemOriginal.Nodes(), XNode.EqualityComparer), "Undo did not work!"); TestLog.Compare(xElem.Attributes().EqualsAllAttributes(xElemOriginal.Attributes(), Helpers.MyAttributeComparer), "Undo did not work!"); } } } public partial class EventsXElementSetElementValue : EventsBase { protected override void DetermineChildren() { VariationsForAdd(ExecuteAddVariation); VariationsForRemove(ExecuteRemoveVariation); VariationsForValue(ExecuteValueVariation); base.DetermineChildren(); } void VariationsForAdd(TestFunc func) { AddChild(func, 1, "Add - Empty element", null, new XElement("element")); AddChild(func, 0, "Add - Element with value", new XComment("comment"), new XElement("element", "value")); AddChild(func, 0, "Add - Element with attribute", new XCData("cdata"), new XElement("element", new XAttribute("a", "aa"))); AddChild(func, 0, "Add - Element with child", new XAttribute("a", "aa"), new XElement("parent", new XElement("child", "child text"))); AddChild(func, 1, "Add - Element with nodes", new XElement("element"), new XElement("nodes", InputSpace.GetElement(100, 10).DescendantNodes())); } void VariationsForRemove(TestFunc func) { AddChild(func, 1, "Remove - Empty element", new XElement("element")); AddChild(func, 0, "Remove - Element with value", new XElement("element", "value")); AddChild(func, 0, "Remove - Element with attribute", new XElement("element", new XAttribute("a", "aa"))); AddChild(func, 0, "Remove - Element with child", new XElement("parent", new XElement("child", "child text"))); AddChild(func, 1, "Remove - Element with nodes", new XElement("nodes", InputSpace.GetElement(100, 10).DescendantNodes())); } void VariationsForValue(TestFunc func) { AddChild(func, 1, "Value - Empty element", new XElement("element"), (double)10); AddChild(func, 0, "Value - Element with value", new XElement("element", "value"), "newValue"); AddChild(func, 0, "Value - Element with attribute", new XElement("element", new XAttribute("a", "aa")), System.DateTime.Now); AddChild(func, 0, "Value - Element with child", new XElement("parent", new XElement("child", "child text")), "Windows 8"); AddChild(func, 1, "Value - Element with nodes", new XElement("nodes", InputSpace.GetElement(100, 10).DescendantNodes()), "StackTrace");//Environment.StackTrace); } public void ExecuteAddVariation() { XObject content = Variation.Params[0] as XObject; XElement toAdd = Variation.Params[1] as XElement; XElement xElem = new XElement("root", content); XElement xElemOriginal = new XElement(xElem); using (UndoManager undo = new UndoManager(xElem)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(xElem)) { xElem.SetElementValue(toAdd.Name, toAdd.Value); xElem.Verify(); eHelper.Verify(XObjectChange.Add, xElem.Element(toAdd.Name)); } undo.Undo(); TestLog.Compare(xElem.Nodes().SequenceEqual(xElemOriginal.Nodes(), XNode.EqualityComparer), "Undo did not work!"); TestLog.Compare(xElem.Attributes().EqualsAllAttributes(xElemOriginal.Attributes(), Helpers.MyAttributeComparer), "Undo did not work!"); } } public void ExecuteRemoveVariation() { XElement content = Variation.Params[0] as XElement; XElement xElem = new XElement("root", content); XElement xElemOriginal = new XElement(xElem); using (UndoManager undo = new UndoManager(xElem)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(xElem)) { xElem.SetElementValue(content.Name, null); xElem.Verify(); eHelper.Verify(XObjectChange.Remove, content); } undo.Undo(); TestLog.Compare(xElem.Nodes().SequenceEqual(xElemOriginal.Nodes(), XNode.EqualityComparer), "Undo did not work!"); TestLog.Compare(xElem.Attributes().EqualsAllAttributes(xElemOriginal.Attributes(), Helpers.MyAttributeComparer), "Undo did not work!"); } } public void ExecuteValueVariation() { XElement content = Variation.Params[0] as XElement; int count = content.Nodes().Count(); Object newValue = Variation.Params[1]; XElement xElem = new XElement("root", content); XElement xElemOriginal = new XElement(xElem); using (UndoManager undo = new UndoManager(xElem)) { undo.Group(); using (EventsHelper eHelper = new EventsHelper(xElem)) { xElem.SetElementValue(content.Name, newValue); // First all contents are removed and then new element with the value is added. xElem.Verify(); eHelper.Verify(count + 1); } undo.Undo(); TestLog.Compare(xElem.Nodes().SequenceEqual(xElemOriginal.Nodes(), XNode.EqualityComparer), "Undo did not work!"); TestLog.Compare(xElem.Attributes().EqualsAllAttributes(xElemOriginal.Attributes(), Helpers.MyAttributeComparer), "Undo did not work!"); } } } } } }
using System; using System.Linq; using Bedrock.Properties; namespace Bedrock.Events { /// <summary> /// Defines a class that manages publication and subscription to events. /// </summary> public class PubSubEvent : EventBase { /// <summary> /// Subscribes a delegate to an event that will be published on the <see cref="ThreadOption.PublisherThread"/>. /// <see cref="PubSubEvent"/> will maintain a <see cref="WeakReference"/> to the target of the supplied <paramref name="action"/> delegate. /// </summary> /// <param name="action">The delegate that gets executed when the event is published.</param> /// <returns>A <see cref="SubscriptionToken"/> that uniquely identifies the added subscription.</returns> /// <remarks> /// The PubSubEvent collection is thread-safe. /// </remarks> public SubscriptionToken Subscribe(Action action) { return Subscribe(action, ThreadOption.PublisherThread); } /// <summary> /// Subscribes a delegate to an event. /// PubSubEvent will maintain a <see cref="WeakReference"/> to the Target of the supplied <paramref name="action"/> delegate. /// </summary> /// <param name="action">The delegate that gets executed when the event is raised.</param> /// <param name="threadOption">Specifies on which thread to receive the delegate callback.</param> /// <returns>A <see cref="SubscriptionToken"/> that uniquely identifies the added subscription.</returns> /// <remarks> /// The PubSubEvent collection is thread-safe. /// </remarks> public SubscriptionToken Subscribe(Action action, ThreadOption threadOption) { return Subscribe(action, threadOption, false); } /// <summary> /// Subscribes a delegate to an event that will be published on the <see cref="ThreadOption.PublisherThread"/>. /// </summary> /// <param name="action">The delegate that gets executed when the event is published.</param> /// <param name="keepSubscriberReferenceAlive">When <see langword="true"/>, the <see cref="PubSubEvent"/> keeps a reference to the subscriber so it does not get garbage collected.</param> /// <returns>A <see cref="SubscriptionToken"/> that uniquely identifies the added subscription.</returns> /// <remarks> /// If <paramref name="keepSubscriberReferenceAlive"/> is set to <see langword="false" />, <see cref="PubSubEvent"/> will maintain a <see cref="WeakReference"/> to the Target of the supplied <paramref name="action"/> delegate. /// If not using a WeakReference (<paramref name="keepSubscriberReferenceAlive"/> is <see langword="true" />), the user must explicitly call Unsubscribe for the event when disposing the subscriber in order to avoid memory leaks or unexpected behavior. /// <para/> /// The PubSubEvent collection is thread-safe. /// </remarks> public SubscriptionToken Subscribe(Action action, bool keepSubscriberReferenceAlive) { return Subscribe(action, ThreadOption.PublisherThread, keepSubscriberReferenceAlive); } /// <summary> /// Subscribes a delegate to an event. /// </summary> /// <param name="action">The delegate that gets executed when the event is published.</param> /// <param name="threadOption">Specifies on which thread to receive the delegate callback.</param> /// <param name="keepSubscriberReferenceAlive">When <see langword="true"/>, the <see cref="PubSubEvent"/> keeps a reference to the subscriber so it does not get garbage collected.</param> /// <returns>A <see cref="SubscriptionToken"/> that uniquely identifies the added subscription.</returns> /// <remarks> /// If <paramref name="keepSubscriberReferenceAlive"/> is set to <see langword="false" />, <see cref="PubSubEvent"/> will maintain a <see cref="WeakReference"/> to the Target of the supplied <paramref name="action"/> delegate. /// If not using a WeakReference (<paramref name="keepSubscriberReferenceAlive"/> is <see langword="true" />), the user must explicitly call Unsubscribe for the event when disposing the subscriber in order to avoid memory leaks or unexpected behavior. /// <para/> /// The PubSubEvent collection is thread-safe. /// </remarks> public virtual SubscriptionToken Subscribe(Action action, ThreadOption threadOption, bool keepSubscriberReferenceAlive) { IDelegateReference actionReference = new DelegateReference(action, keepSubscriberReferenceAlive); EventSubscription subscription; switch (threadOption) { case ThreadOption.PublisherThread: subscription = new EventSubscription(actionReference); break; case ThreadOption.BackgroundThread: subscription = new BackgroundEventSubscription(actionReference); break; case ThreadOption.UIThread: if (SynchronizationContext == null) throw new InvalidOperationException(Resources.EventAggregatorNotConstructedOnUIThread); subscription = new DispatcherEventSubscription(actionReference, SynchronizationContext); break; default: subscription = new EventSubscription(actionReference); break; } return InternalSubscribe(subscription); } /// <summary> /// Publishes the <see cref="PubSubEvent"/>. /// </summary> public virtual void Publish() { InternalPublish(); } /// <summary> /// Removes the first subscriber matching <see cref="Action"/> from the subscribers' list. /// </summary> /// <param name="subscriber">The <see cref="Action"/> used when subscribing to the event.</param> public virtual void Unsubscribe(Action subscriber) { lock (Subscriptions) { IEventSubscription eventSubscription = Subscriptions.Cast<EventSubscription>().FirstOrDefault(evt => evt.Action == subscriber); if (eventSubscription != null) { Subscriptions.Remove(eventSubscription); } } } /// <summary> /// Returns <see langword="true"/> if there is a subscriber matching <see cref="Action"/>. /// </summary> /// <param name="subscriber">The <see cref="Action"/> used when subscribing to the event.</param> /// <returns><see langword="true"/> if there is an <see cref="Action"/> that matches; otherwise <see langword="false"/>.</returns> public virtual bool Contains(Action subscriber) { IEventSubscription eventSubscription; lock (Subscriptions) { eventSubscription = Subscriptions.Cast<EventSubscription>().FirstOrDefault(evt => evt.Action == subscriber); } return eventSubscription != null; } } /// <summary> /// Defines a class that manages publication and subscription to events. /// </summary> /// <typeparam name="TPayload">The type of message that will be passed to the subscribers.</typeparam> public class PubSubEvent<TPayload> : EventBase { /// <summary> /// Subscribes a delegate to an event that will be published on the <see cref="ThreadOption.PublisherThread"/>. /// <see cref="PubSubEvent{TPayload}"/> will maintain a <see cref="WeakReference"/> to the target of the supplied <paramref name="action"/> delegate. /// </summary> /// <param name="action">The delegate that gets executed when the event is published.</param> /// <returns>A <see cref="SubscriptionToken"/> that uniquely identifies the added subscription.</returns> /// <remarks> /// The PubSubEvent collection is thread-safe. /// </remarks> public SubscriptionToken Subscribe(Action<TPayload> action) { return Subscribe(action, ThreadOption.PublisherThread); } /// <summary> /// Subscribes a delegate to an event. /// PubSubEvent will maintain a <see cref="WeakReference"/> to the Target of the supplied <paramref name="action"/> delegate. /// </summary> /// <param name="action">The delegate that gets executed when the event is raised.</param> /// <param name="threadOption">Specifies on which thread to receive the delegate callback.</param> /// <returns>A <see cref="SubscriptionToken"/> that uniquely identifies the added subscription.</returns> /// <remarks> /// The PubSubEvent collection is thread-safe. /// </remarks> public SubscriptionToken Subscribe(Action<TPayload> action, ThreadOption threadOption) { return Subscribe(action, threadOption, false); } /// <summary> /// Subscribes a delegate to an event that will be published on the <see cref="ThreadOption.PublisherThread"/>. /// </summary> /// <param name="action">The delegate that gets executed when the event is published.</param> /// <param name="keepSubscriberReferenceAlive">When <see langword="true"/>, the <see cref="PubSubEvent{TPayload}"/> keeps a reference to the subscriber so it does not get garbage collected.</param> /// <returns>A <see cref="SubscriptionToken"/> that uniquely identifies the added subscription.</returns> /// <remarks> /// If <paramref name="keepSubscriberReferenceAlive"/> is set to <see langword="false" />, <see cref="PubSubEvent{TPayload}"/> will maintain a <see cref="WeakReference"/> to the Target of the supplied <paramref name="action"/> delegate. /// If not using a WeakReference (<paramref name="keepSubscriberReferenceAlive"/> is <see langword="true" />), the user must explicitly call Unsubscribe for the event when disposing the subscriber in order to avoid memory leaks or unexpected behavior. /// <para/> /// The PubSubEvent collection is thread-safe. /// </remarks> public SubscriptionToken Subscribe(Action<TPayload> action, bool keepSubscriberReferenceAlive) { return Subscribe(action, ThreadOption.PublisherThread, keepSubscriberReferenceAlive); } /// <summary> /// Subscribes a delegate to an event. /// </summary> /// <param name="action">The delegate that gets executed when the event is published.</param> /// <param name="threadOption">Specifies on which thread to receive the delegate callback.</param> /// <param name="keepSubscriberReferenceAlive">When <see langword="true"/>, the <see cref="PubSubEvent{TPayload}"/> keeps a reference to the subscriber so it does not get garbage collected.</param> /// <returns>A <see cref="SubscriptionToken"/> that uniquely identifies the added subscription.</returns> /// <remarks> /// If <paramref name="keepSubscriberReferenceAlive"/> is set to <see langword="false" />, <see cref="PubSubEvent{TPayload}"/> will maintain a <see cref="WeakReference"/> to the Target of the supplied <paramref name="action"/> delegate. /// If not using a WeakReference (<paramref name="keepSubscriberReferenceAlive"/> is <see langword="true" />), the user must explicitly call Unsubscribe for the event when disposing the subscriber in order to avoid memory leaks or unexpected behavior. /// <para/> /// The PubSubEvent collection is thread-safe. /// </remarks> public SubscriptionToken Subscribe(Action<TPayload> action, ThreadOption threadOption, bool keepSubscriberReferenceAlive) { return Subscribe(action, threadOption, keepSubscriberReferenceAlive, null); } /// <summary> /// Subscribes a delegate to an event. /// </summary> /// <param name="action">The delegate that gets executed when the event is published.</param> /// <param name="threadOption">Specifies on which thread to receive the delegate callback.</param> /// <param name="keepSubscriberReferenceAlive">When <see langword="true"/>, the <see cref="PubSubEvent{TPayload}"/> keeps a reference to the subscriber so it does not get garbage collected.</param> /// <param name="filter">Filter to evaluate if the subscriber should receive the event.</param> /// <returns>A <see cref="SubscriptionToken"/> that uniquely identifies the added subscription.</returns> /// <remarks> /// If <paramref name="keepSubscriberReferenceAlive"/> is set to <see langword="false" />, <see cref="PubSubEvent{TPayload}"/> will maintain a <see cref="WeakReference"/> to the Target of the supplied <paramref name="action"/> delegate. /// If not using a WeakReference (<paramref name="keepSubscriberReferenceAlive"/> is <see langword="true" />), the user must explicitly call Unsubscribe for the event when disposing the subscriber in order to avoid memory leaks or unexpected behavior. /// /// The PubSubEvent collection is thread-safe. /// </remarks> public virtual SubscriptionToken Subscribe(Action<TPayload> action, ThreadOption threadOption, bool keepSubscriberReferenceAlive, Predicate<TPayload> filter) { IDelegateReference actionReference = new DelegateReference(action, keepSubscriberReferenceAlive); IDelegateReference filterReference; if (filter != null) { filterReference = new DelegateReference(filter, keepSubscriberReferenceAlive); } else { filterReference = new DelegateReference(new Predicate<TPayload>(delegate { return true; }), true); } EventSubscription<TPayload> subscription; switch (threadOption) { case ThreadOption.PublisherThread: subscription = new EventSubscription<TPayload>(actionReference, filterReference); break; case ThreadOption.BackgroundThread: subscription = new BackgroundEventSubscription<TPayload>(actionReference, filterReference); break; case ThreadOption.UIThread: if (SynchronizationContext == null) throw new InvalidOperationException(Resources.EventAggregatorNotConstructedOnUIThread); subscription = new DispatcherEventSubscription<TPayload>(actionReference, filterReference, SynchronizationContext); break; default: subscription = new EventSubscription<TPayload>(actionReference, filterReference); break; } return InternalSubscribe(subscription); } /// <summary> /// Publishes the <see cref="PubSubEvent{TPayload}"/>. /// </summary> /// <param name="payload">Message to pass to the subscribers.</param> public virtual void Publish(TPayload payload) { InternalPublish(payload); } /// <summary> /// Removes the first subscriber matching <see cref="Action{TPayload}"/> from the subscribers' list. /// </summary> /// <param name="subscriber">The <see cref="Action{TPayload}"/> used when subscribing to the event.</param> public virtual void Unsubscribe(Action<TPayload> subscriber) { lock (Subscriptions) { IEventSubscription eventSubscription = Subscriptions.Cast<EventSubscription<TPayload>>().FirstOrDefault(evt => evt.Action == subscriber); if (eventSubscription != null) { Subscriptions.Remove(eventSubscription); } } } /// <summary> /// Returns <see langword="true"/> if there is a subscriber matching <see cref="Action{TPayload}"/>. /// </summary> /// <param name="subscriber">The <see cref="Action{TPayload}"/> used when subscribing to the event.</param> /// <returns><see langword="true"/> if there is an <see cref="Action{TPayload}"/> that matches; otherwise <see langword="false"/>.</returns> public virtual bool Contains(Action<TPayload> subscriber) { IEventSubscription eventSubscription; lock (Subscriptions) { eventSubscription = Subscriptions.Cast<EventSubscription<TPayload>>().FirstOrDefault(evt => evt.Action == subscriber); } return eventSubscription != null; } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Build.Construction; using Microsoft.DotNet.Tools.Test.Utilities; using System.Linq; using Xunit; using FluentAssertions; using Microsoft.DotNet.ProjectJsonMigration.Rules; using System; namespace Microsoft.DotNet.ProjectJsonMigration.Tests { public class GivenThatIWantToMigratePackOptions : TestBase { [Fact] public void It_does_not_migrate_Summary() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""summary"": ""Some not important summary"" } }"); EmitsOnlyAlwaysEmittedPackOptionsProperties(mockProj); } [Fact] public void It_does_not_migrate_Owner() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""owner"": ""Some not important owner"" } }"); EmitsOnlyAlwaysEmittedPackOptionsProperties(mockProj); } [Fact] public void Migrating__empty_tags_does_not_populate_PackageTags() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""tags"": [] } }"); mockProj.Properties.Count(p => p.Name == "PackageTags").Should().Be(0); } [Fact] public void Migrating_tags_populates_PackageTags_semicolon_delimited() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""tags"": [""hyperscale"", ""cats""] } }"); mockProj.Properties.Count(p => p.Name == "PackageTags").Should().Be(1); mockProj.Properties.First(p => p.Name == "PackageTags").Value.Should().Be("hyperscale;cats"); } [Fact] public void Migrating_ReleaseNotes_populates_PackageReleaseNotes() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""releaseNotes"": ""Some release notes value."" } }"); mockProj.Properties.Count(p => p.Name == "PackageReleaseNotes").Should().Be(1); mockProj.Properties.First(p => p.Name == "PackageReleaseNotes").Value.Should() .Be("Some release notes value."); } [Fact] public void Migrating_IconUrl_populates_PackageIconUrl() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""iconUrl"": ""http://www.mylibrary.gov/favicon.ico"" } }"); mockProj.Properties.Count(p => p.Name == "PackageIconUrl").Should().Be(1); mockProj.Properties.First(p => p.Name == "PackageIconUrl").Value.Should() .Be("http://www.mylibrary.gov/favicon.ico"); } [Fact] public void Migrating_ProjectUrl_populates_PackageProjectUrl() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""projectUrl"": ""http://www.url.to.library.com"" } }"); mockProj.Properties.Count(p => p.Name == "PackageProjectUrl").Should().Be(1); mockProj.Properties.First(p => p.Name == "PackageProjectUrl").Value.Should() .Be("http://www.url.to.library.com"); } [Fact] public void Migrating_LicenseUrl_populates_PackageLicenseUrl() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""licenseUrl"": ""http://www.url.to.library.com/licence"" } }"); mockProj.Properties.Count(p => p.Name == "PackageLicenseUrl").Should().Be(1); mockProj.Properties.First(p => p.Name == "PackageLicenseUrl").Value.Should() .Be("http://www.url.to.library.com/licence"); } [Fact] public void Migrating_RequireLicenseAcceptance_populates_PackageRequireLicenseAcceptance() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""requireLicenseAcceptance"": ""true"" } }"); mockProj.Properties.Count(p => p.Name == "PackageRequireLicenseAcceptance").Should().Be(1); mockProj.Properties.First(p => p.Name == "PackageRequireLicenseAcceptance").Value.Should().Be("true"); } [Fact] public void Migrating_RequireLicenseAcceptance_populates_PackageRequireLicenseAcceptance_even_if_its_value_is_false() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""requireLicenseAcceptance"": ""false"" } }"); mockProj.Properties.Count(p => p.Name == "PackageRequireLicenseAcceptance").Should().Be(1); mockProj.Properties.First(p => p.Name == "PackageRequireLicenseAcceptance").Value.Should().Be("false"); } [Fact] public void Migrating_Repository_Type_populates_RepositoryType() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""repository"": { ""type"": ""git"" } } }"); mockProj.Properties.Count(p => p.Name == "RepositoryType").Should().Be(1); mockProj.Properties.First(p => p.Name == "RepositoryType").Value.Should().Be("git"); } [Fact] public void Migrating_Repository_Url_populates_RepositoryUrl() { var mockProj = RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""repository"": { ""url"": ""http://github.com/dotnet/cli"" } } }"); mockProj.Properties.Count(p => p.Name == "RepositoryUrl").Should().Be(1); mockProj.Properties.First(p => p.Name == "RepositoryUrl").Value.Should().Be("http://github.com/dotnet/cli"); } [Fact] public void Migrating_Files_throws_an_exception_for_now() { Action action = () => RunPackOptionsRuleOnPj(@" { ""packOptions"": { ""files"": { ""include"": [""somefile.cs""] } } }"); action.ShouldThrow<Exception>() .Where(e => e.Message.Contains("Migrating projects with Files specified in PackOptions is not supported.")); } private ProjectRootElement RunPackOptionsRuleOnPj(string packOptions, string testDirectory = null) { testDirectory = testDirectory ?? Temp.CreateDirectory().Path; return TemporaryProjectFileRuleRunner.RunRules(new IMigrationRule[] { new MigratePackOptionsRule() }, packOptions, testDirectory); } private void EmitsOnlyAlwaysEmittedPackOptionsProperties(ProjectRootElement project) { project.Properties.Count().Should().Be(1); project.Properties.All(p => p.Name == "PackageRequireLicenseAcceptance").Should().BeTrue(); } } }
using UnityEngine; using UnityEditor; using System.IO; using System.Xml; using System.Text; using System.Linq; namespace UnityEditor.FacebookEditor { public class ManifestMod { public const string DeepLinkingActivityName = "com.facebook.unity.FBUnityDeepLinkingActivity"; public const string LoginActivityName = "com.facebook.LoginActivity"; public const string UnityLoginActivityName = "com.facebook.unity.FBUnityLoginActivity"; public const string ApplicationIdMetaDataName = "com.facebook.sdk.ApplicationId"; public static void GenerateManifest() { var outputFile = Path.Combine(Application.dataPath, "Plugins/Android/AndroidManifest.xml"); // only copy over a fresh copy of the AndroidManifest if one does not exist if (!File.Exists(outputFile)) { var inputFile = Path.Combine(EditorApplication.applicationContentsPath, "PlaybackEngines/androidplayer/AndroidManifest.xml"); File.Copy(inputFile, outputFile); } UpdateManifest(outputFile); } public static bool CheckManifest() { bool result = true; var outputFile = Path.Combine(Application.dataPath, "Plugins/Android/AndroidManifest.xml"); if (!File.Exists(outputFile)) { Debug.LogError("An android manifest must be generated for the Facebook SDK to work. Go to Facebook->Edit Settings and press \"Regenerate Android Manifest\""); return false; } XmlDocument doc = new XmlDocument(); doc.Load(outputFile); if (doc == null) { Debug.LogError("Couldn't load " + outputFile); return false; } XmlNode manNode = FindChildNode(doc, "manifest"); XmlNode dict = FindChildNode(manNode, "application"); if (dict == null) { Debug.LogError("Error parsing " + outputFile); return false; } string ns = dict.GetNamespaceOfPrefix("android"); XmlElement loginElement = FindElementWithAndroidName("activity", "name", ns, UnityLoginActivityName, dict); if (loginElement == null) { Debug.LogError(string.Format("{0} is missing from your android manifest. Go to Facebook->Edit Settings and press \"Regenerate Android Manifest\"", LoginActivityName)); result = false; } var deprecatedMainActivityName = "com.facebook.unity.FBUnityPlayerActivity"; XmlElement deprecatedElement = FindElementWithAndroidName("activity", "name", ns, deprecatedMainActivityName, dict); if (deprecatedElement != null) { Debug.LogWarning(string.Format("{0} is deprecated and no longer needed for the Facebook SDK. Feel free to use your own main activity or use the default \"com.unity3d.player.UnityPlayerNativeActivity\"", deprecatedMainActivityName)); } return result; } private static XmlNode FindChildNode(XmlNode parent, string name) { XmlNode curr = parent.FirstChild; while (curr != null) { if (curr.Name.Equals(name)) { return curr; } curr = curr.NextSibling; } return null; } private static XmlElement FindElementWithAndroidName(string name, string androidName, string ns, string value, XmlNode parent) { var curr = parent.FirstChild; while (curr != null) { if (curr.Name.Equals(name) && curr is XmlElement && ((XmlElement)curr).GetAttribute(androidName, ns) == value) { return curr as XmlElement; } curr = curr.NextSibling; } return null; } public static void UpdateManifest(string fullPath) { string appId = FBSettings.AppId; if (!FBSettings.IsValidAppId) { Debug.LogError("You didn't specify a Facebook app ID. Please add one using the Facebook menu in the main Unity editor."); return; } XmlDocument doc = new XmlDocument(); doc.Load(fullPath); if (doc == null) { Debug.LogError("Couldn't load " + fullPath); return; } XmlNode manNode = FindChildNode(doc, "manifest"); XmlNode dict = FindChildNode(manNode, "application"); if (dict == null) { Debug.LogError("Error parsing " + fullPath); return; } string ns = dict.GetNamespaceOfPrefix("android"); //add the unity login activity XmlElement unityLoginElement = FindElementWithAndroidName("activity", "name", ns, UnityLoginActivityName, dict); if (unityLoginElement == null) { unityLoginElement = CreateUnityLoginElement(doc, ns); dict.AppendChild(unityLoginElement); } //add the login activity XmlElement loginElement = FindElementWithAndroidName("activity", "name", ns, LoginActivityName, dict); if (loginElement == null) { loginElement = CreateLoginElement(doc, ns); dict.AppendChild(loginElement); } //add deep linking activity XmlElement deepLinkingElement = FindElementWithAndroidName("activity", "name", ns, DeepLinkingActivityName, dict); if (deepLinkingElement == null) { deepLinkingElement = CreateDeepLinkingElement(doc, ns); dict.AppendChild(deepLinkingElement); } //add the app id //<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="\ 409682555812308" /> XmlElement appIdElement = FindElementWithAndroidName("meta-data", "name", ns, ApplicationIdMetaDataName, dict); if (appIdElement == null) { appIdElement = doc.CreateElement("meta-data"); appIdElement.SetAttribute("name", ns, ApplicationIdMetaDataName); dict.AppendChild(appIdElement); } appIdElement.SetAttribute("value", ns, "\\ " + appId); //stupid hack so that the id comes out as a string doc.Save(fullPath); } private static XmlElement CreateLoginElement(XmlDocument doc, string ns) { //<activity android:name="com.facebook.LoginActivity" android:screenOrientation="portrait" android:configChanges="keyboardHidden|orientation" android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"> //</activity> XmlElement activityElement = doc.CreateElement("activity"); activityElement.SetAttribute("name", ns, LoginActivityName); activityElement.SetAttribute("screenOrientation", ns, "portrait"); activityElement.SetAttribute("configChanges", ns, "keyboardHidden|orientation"); activityElement.SetAttribute("theme", ns, "@android:style/Theme.Translucent.NoTitleBar.Fullscreen"); activityElement.InnerText = "\n "; //be extremely anal to make diff tools happy return activityElement; } private static XmlElement CreateDeepLinkingElement(XmlDocument doc, string ns) { //<activity android:name="com.facebook.unity.FBDeepLinkingActivity" android:exported="true"> //</activity> XmlElement activityElement = doc.CreateElement("activity"); activityElement.SetAttribute("name", ns, DeepLinkingActivityName); activityElement.SetAttribute("exported", ns, "true"); activityElement.InnerText = "\n "; //be extremely anal to make diff tools happy return activityElement; } private static XmlElement CreateUnityLoginElement(XmlDocument doc, string ns) { //<activity android:name="com.facebook.unity.FBUnityLoginActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"> //</activity> XmlElement activityElement = doc.CreateElement("activity"); activityElement.SetAttribute("name", ns, UnityLoginActivityName); activityElement.SetAttribute("theme", ns, "@android:style/Theme.Translucent.NoTitleBar.Fullscreen"); activityElement.InnerText = "\n "; //be extremely anal to make diff tools happy return activityElement; } } }
// 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.Text { using System; using System.Runtime; using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] public sealed class EncoderReplacementFallback : EncoderFallback { // Our variables private String strDefault; // Construction. Default replacement fallback uses no best fit and ? replacement string public EncoderReplacementFallback() : this("?") { } public EncoderReplacementFallback(String replacement) { // Must not be null if (replacement == null) throw new ArgumentNullException(nameof(replacement)); Contract.EndContractBlock(); // Make sure it doesn't have bad surrogate pairs bool bFoundHigh=false; for (int i = 0; i < replacement.Length; i++) { // Found a surrogate? if (Char.IsSurrogate(replacement,i)) { // High or Low? if (Char.IsHighSurrogate(replacement, i)) { // if already had a high one, stop if (bFoundHigh) break; // break & throw at the bFoundHIgh below bFoundHigh = true; } else { // Low, did we have a high? if (!bFoundHigh) { // Didn't have one, make if fail when we stop bFoundHigh = true; break; } // Clear flag bFoundHigh = false; } } // If last was high we're in trouble (not surrogate so not low surrogate, so break) else if (bFoundHigh) break; } if (bFoundHigh) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex", nameof(replacement))); strDefault = replacement; } public String DefaultString { get { return strDefault; } } public override EncoderFallbackBuffer CreateFallbackBuffer() { return new EncoderReplacementFallbackBuffer(this); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { return strDefault.Length; } } public override bool Equals(Object value) { EncoderReplacementFallback that = value as EncoderReplacementFallback; if (that != null) { return (this.strDefault == that.strDefault); } return (false); } public override int GetHashCode() { return strDefault.GetHashCode(); } } public sealed class EncoderReplacementFallbackBuffer : EncoderFallbackBuffer { // Store our default string private String strDefault; int fallbackCount = -1; int fallbackIndex = -1; // Construction public EncoderReplacementFallbackBuffer(EncoderReplacementFallback fallback) { // 2X in case we're a surrogate pair this.strDefault = fallback.DefaultString + fallback.DefaultString; } // Fallback Methods public override bool Fallback(char charUnknown, int index) { // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. if (fallbackCount >= 1) { // If we're recursive we may still have something in our buffer that makes this a surrogate if (char.IsHighSurrogate(charUnknown) && fallbackCount >= 0 && char.IsLowSurrogate(strDefault[fallbackIndex+1])) ThrowLastCharRecursive(Char.ConvertToUtf32(charUnknown, strDefault[fallbackIndex+1])); // Nope, just one character ThrowLastCharRecursive(unchecked((int)charUnknown)); } // Go ahead and get our fallback // Divide by 2 because we aren't a surrogate pair fallbackCount = strDefault.Length/2; fallbackIndex = -1; return fallbackCount != 0; } public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { // Double check input surrogate pair if (!Char.IsHighSurrogate(charUnknownHigh)) throw new ArgumentOutOfRangeException(nameof(charUnknownHigh), Environment.GetResourceString("ArgumentOutOfRange_Range", 0xD800, 0xDBFF)); if (!Char.IsLowSurrogate(charUnknownLow)) throw new ArgumentOutOfRangeException(nameof(charUnknownLow), Environment.GetResourceString("ArgumentOutOfRange_Range", 0xDC00, 0xDFFF)); Contract.EndContractBlock(); // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. if (fallbackCount >= 1) ThrowLastCharRecursive(Char.ConvertToUtf32(charUnknownHigh, charUnknownLow)); // Go ahead and get our fallback fallbackCount = strDefault.Length; fallbackIndex = -1; return fallbackCount != 0; } public override char GetNextChar() { // We want it to get < 0 because == 0 means that the current/last character is a fallback // and we need to detect recursion. We could have a flag but we already have this counter. fallbackCount--; fallbackIndex++; // Do we have anything left? 0 is now last fallback char, negative is nothing left if (fallbackCount < 0) return '\0'; // Need to get it out of the buffer. // Make sure it didn't wrap from the fast count-- path if (fallbackCount == int.MaxValue) { fallbackCount = -1; return '\0'; } // Now make sure its in the expected range Debug.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0, "Index exceeds buffer range"); return strDefault[fallbackIndex]; } public override bool MovePrevious() { // Back up one, only if we just processed the last character (or earlier) if (fallbackCount >= -1 && fallbackIndex >= 0) { fallbackIndex--; fallbackCount++; return true; } // Return false 'cause we couldn't do it. return false; } // How many characters left to output? public override int Remaining { get { // Our count is 0 for 1 character left. return (fallbackCount < 0) ? 0 : fallbackCount; } } // Clear the buffer public override unsafe void Reset() { fallbackCount = -1; fallbackIndex = 0; charStart = null; bFallingBack = false; } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Management.Automation; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Management.Automation.Runspaces; using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell.Commands { /// <summary> /// This class implements update-typeData command. /// </summary> [Cmdlet(VerbsData.Update, "TypeData", SupportsShouldProcess = true, DefaultParameterSetName = FileParameterSet, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113421")] public class UpdateTypeDataCommand : UpdateData { #region dynamic type set // Dynamic type set name and type data set name private const string DynamicTypeSet = "DynamicTypeSet"; private const string TypeDataSet = "TypeDataSet"; private static object s_notSpecified = new object(); private static bool HasBeenSpecified(object obj) { return !System.Object.ReferenceEquals(obj, s_notSpecified); } private PSMemberTypes _memberType; private bool _isMemberTypeSet = false; /// <summary> /// The member type of to be added /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] [ValidateSet(System.Management.Automation.Runspaces.TypeData.NoteProperty, System.Management.Automation.Runspaces.TypeData.AliasProperty, System.Management.Automation.Runspaces.TypeData.ScriptProperty, System.Management.Automation.Runspaces.TypeData.CodeProperty, System.Management.Automation.Runspaces.TypeData.ScriptMethod, System.Management.Automation.Runspaces.TypeData.CodeMethod, IgnoreCase = true)] public PSMemberTypes MemberType { set { _memberType = value; _isMemberTypeSet = true; } get { return _memberType; } } private string _memberName; /// <summary> /// The name of the new member /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] public string MemberName { set { _memberName = value; } get { return _memberName; } } private object _value1 = s_notSpecified; /// <summary> /// First value of the new member. The meaning of this value /// changes according to the member type. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] public object Value { set { _value1 = value; } get { return _value1; } } private object _value2; /// <summary> /// Second value of the new member. The meaning of this value /// changes according to the member type. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNull] public object SecondValue { set { _value2 = value; } get { return _value2; } } private Type _typeConverter; /// <summary> /// The type converter to be added /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNull] public Type TypeConverter { set { _typeConverter = value; } get { return _typeConverter; } } private Type _typeAdapter; /// <summary> /// The type adapter to be added /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNull] public Type TypeAdapter { set { _typeAdapter = value; } get { return _typeAdapter; } } /// <summary> /// SerializationMethod /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] public string SerializationMethod { set { _serializationMethod = value; } get { return _serializationMethod; } } /// <summary> /// TargetTypeForDeserialization /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNull] public Type TargetTypeForDeserialization { set { _targetTypeForDeserialization = value; } get { return _targetTypeForDeserialization; } } /// <summary> /// SerializationDepth /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNull] [ValidateRange(0, int.MaxValue)] public int SerializationDepth { set { _serializationDepth = value; } get { return _serializationDepth; } } /// <summary> /// DefaultDisplayProperty /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] public string DefaultDisplayProperty { set { _defaultDisplayProperty = value; } get { return _defaultDisplayProperty; } } /// <summary> /// InheritPropertySerializationSet /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNull] public Nullable<bool> InheritPropertySerializationSet { set { _inheritPropertySerializationSet = value; } get { return _inheritPropertySerializationSet; } } /// <summary> /// StringSerializationSource /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] public string StringSerializationSource { set { _stringSerializationSource = value; } get { return _stringSerializationSource; } } /// <summary> /// DefaultDisplayPropertySet /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] public string[] DefaultDisplayPropertySet { set { _defaultDisplayPropertySet = value; } get { return _defaultDisplayPropertySet; } } /// <summary> /// DefaultKeyPropertySet /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] public string[] DefaultKeyPropertySet { set { _defaultKeyPropertySet = value; } get { return _defaultKeyPropertySet; } } /// <summary> /// PropertySerializationSet /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] public string[] PropertySerializationSet { set { _propertySerializationSet = value; } get { return _propertySerializationSet; } } // These members are represeted as NoteProperty in types.ps1xml private string _serializationMethod; private Type _targetTypeForDeserialization; private int _serializationDepth = int.MinValue; private string _defaultDisplayProperty; private Nullable<bool> _inheritPropertySerializationSet; // These members are represented as AliasProperty in types.ps1xml private string _stringSerializationSource; // These members are represented as PropertySet in types.ps1xml private string[] _defaultDisplayPropertySet; private string[] _defaultKeyPropertySet; private string[] _propertySerializationSet; private string _typeName; /// <summary> /// The type name we want to update on /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = DynamicTypeSet)] [ArgumentToTypeNameTransformationAttribute()] [ValidateNotNullOrEmpty] public string TypeName { set { _typeName = value; } get { return _typeName; } } private bool _force = false; /// <summary> /// True if we should overwrite a possibly existing member /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [Parameter(ParameterSetName = TypeDataSet)] public SwitchParameter Force { set { _force = value; } get { return _force; } } #endregion dynamic type set #region strong type data set private TypeData[] _typeData; /// <summary> /// The TypeData instances /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = TypeDataSet)] public TypeData[] TypeData { set { _typeData = value; } get { return _typeData; } } #endregion strong type data set /// <summary> /// This method verify if the Type Table is shared and cannot be updated /// </summary> protected override void BeginProcessing() { if (Context.TypeTable.isShared) { var ex = new InvalidOperationException(TypesXmlStrings.SharedTypeTableCannotBeUpdated); this.ThrowTerminatingError(new ErrorRecord(ex, "CannotUpdateSharedTypeTable", ErrorCategory.InvalidOperation, null)); } } /// <summary> /// This method implements the ProcessRecord method for update-typeData command /// </summary> protected override void ProcessRecord() { switch (ParameterSetName) { case FileParameterSet: ProcessTypeFiles(); break; case DynamicTypeSet: ProcessDynamicType(); break; case TypeDataSet: ProcessStrongTypeData(); break; } } /// <summary> /// This method implements the EndProcessing method for update-typeData command /// </summary> protected override void EndProcessing() { this.Context.TypeTable.ClearConsolidatedMembers(); } #region strong typeData private void ProcessStrongTypeData() { string action = UpdateDataStrings.UpdateTypeDataAction; string target = UpdateDataStrings.UpdateTypeDataTarget; foreach (TypeData item in _typeData) { // If type contains no members at all, report the error and skip it if (!EnsureTypeDataIsNotEmpty(item)) { continue; } TypeData type = item.Copy(); // Set property IsOverride to be true if -Force parameter is specified if (_force) { type.IsOverride = true; } string formattedTarget = string.Format(CultureInfo.InvariantCulture, target, type.TypeName); if (ShouldProcess(formattedTarget, action)) { try { var errors = new ConcurrentBag<string>(); this.Context.TypeTable.Update(type, errors, false); // Write out errors... if (errors.Count > 0) { foreach (string s in errors) { RuntimeException rte = new RuntimeException(s); this.WriteError(new ErrorRecord(rte, "TypesDynamicUpdateException", ErrorCategory.InvalidOperation, null)); } } else { // Update successfully, we add the TypeData into cache if (Context.RunspaceConfiguration != null) { Context.RunspaceConfiguration.Types.Append(new TypeConfigurationEntry(type, false)); } else if (Context.InitialSessionState != null) { Context.InitialSessionState.Types.Add(new SessionStateTypeEntry(type, false)); } else { Dbg.Assert(false, "Either RunspaceConfiguration or InitiaSessionState must be non-null for Update-Typedata to work"); } } } catch (RuntimeException e) { this.WriteError(new ErrorRecord(e, "TypesDynamicUpdateException", ErrorCategory.InvalidOperation, null)); } } } } #endregion strong typeData #region dynamic type processing /// <summary> /// Process the dynamic type update /// </summary> private void ProcessDynamicType() { if (String.IsNullOrWhiteSpace(_typeName)) { ThrowTerminatingError(NewError("TargetTypeNameEmpty", UpdateDataStrings.TargetTypeNameEmpty, _typeName)); } TypeData type = new TypeData(_typeName) { IsOverride = _force }; GetMembers(type.Members); if (_typeConverter != null) { type.TypeConverter = _typeConverter; } if (_typeAdapter != null) { type.TypeAdapter = _typeAdapter; } if (_serializationMethod != null) { type.SerializationMethod = _serializationMethod; } if (_targetTypeForDeserialization != null) { type.TargetTypeForDeserialization = _targetTypeForDeserialization; } if (_serializationDepth != int.MinValue) { type.SerializationDepth = (uint)_serializationDepth; } if (_defaultDisplayProperty != null) { type.DefaultDisplayProperty = _defaultDisplayProperty; } if (_inheritPropertySerializationSet != null) { type.InheritPropertySerializationSet = _inheritPropertySerializationSet.Value; } if (_stringSerializationSource != null) { type.StringSerializationSource = _stringSerializationSource; } if (_defaultDisplayPropertySet != null) { PropertySetData defaultDisplayPropertySet = new PropertySetData(_defaultDisplayPropertySet); type.DefaultDisplayPropertySet = defaultDisplayPropertySet; } if (_defaultKeyPropertySet != null) { PropertySetData defaultKeyPropertySet = new PropertySetData(_defaultKeyPropertySet); type.DefaultKeyPropertySet = defaultKeyPropertySet; } if (_propertySerializationSet != null) { PropertySetData propertySerializationSet = new PropertySetData(_propertySerializationSet); type.PropertySerializationSet = propertySerializationSet; } // If the type contains no members at all, report the error and return if (!EnsureTypeDataIsNotEmpty(type)) { return; } // Load the resource strings string action = UpdateDataStrings.UpdateTypeDataAction; string target = UpdateDataStrings.UpdateTypeDataTarget; string formattedTarget = string.Format(CultureInfo.InvariantCulture, target, _typeName); if (ShouldProcess(formattedTarget, action)) { try { var errors = new ConcurrentBag<string>(); this.Context.TypeTable.Update(type, errors, false); // Write out errors... if (errors.Count > 0) { foreach (string s in errors) { RuntimeException rte = new RuntimeException(s); this.WriteError(new ErrorRecord(rte, "TypesDynamicUpdateException", ErrorCategory.InvalidOperation, null)); } } else { // Update successfully, we add the TypeData into cache if (Context.RunspaceConfiguration != null) { Context.RunspaceConfiguration.Types.Append(new TypeConfigurationEntry(type, false)); } else if (Context.InitialSessionState != null) { Context.InitialSessionState.Types.Add(new SessionStateTypeEntry(type, false)); } else { Dbg.Assert(false, "Either RunspaceConfiguration or InitiaSessionState must be non-null for Update-Typedata to work"); } } } catch (RuntimeException e) { this.WriteError(new ErrorRecord(e, "TypesDynamicUpdateException", ErrorCategory.InvalidOperation, null)); } } } /// <summary> /// Get the members for the TypeData /// </summary> /// <returns></returns> private void GetMembers(Dictionary<string, TypeMemberData> members) { if (!_isMemberTypeSet) { // If the MemberType is not specified, the MemberName, Value, and SecondValue parameters // should not be specified either if (_memberName != null || HasBeenSpecified(_value1) || _value2 != null) { ThrowTerminatingError(NewError("MemberTypeIsMissing", UpdateDataStrings.MemberTypeIsMissing, null)); } return; } switch (MemberType) { case PSMemberTypes.NoteProperty: NotePropertyData note = GetNoteProperty(); members.Add(note.Name, note); break; case PSMemberTypes.AliasProperty: AliasPropertyData alias = GetAliasProperty(); members.Add(alias.Name, alias); break; case PSMemberTypes.ScriptProperty: ScriptPropertyData scriptProperty = GetScriptProperty(); members.Add(scriptProperty.Name, scriptProperty); break; case PSMemberTypes.CodeProperty: CodePropertyData codeProperty = GetCodeProperty(); members.Add(codeProperty.Name, codeProperty); break; case PSMemberTypes.ScriptMethod: ScriptMethodData scriptMethod = GetScriptMethod(); members.Add(scriptMethod.Name, scriptMethod); break; case PSMemberTypes.CodeMethod: CodeMethodData codeMethod = GetCodeMethod(); members.Add(codeMethod.Name, codeMethod); break; default: ThrowTerminatingError(NewError("CannotUpdateMemberType", UpdateDataStrings.CannotUpdateMemberType, null, _memberType.ToString())); break; } } private T GetParameterType<T>(object sourceValue) { return (T)LanguagePrimitives.ConvertTo(sourceValue, typeof(T), CultureInfo.InvariantCulture); } private void EnsureMemberNameHasBeenSpecified() { if (String.IsNullOrEmpty(_memberName)) { ThrowTerminatingError(NewError("MemberNameShouldBeSpecified", UpdateDataStrings.ShouldBeSpecified, null, "MemberName", _memberType)); } } private void EnsureValue1HasBeenSpecified() { if (!HasBeenSpecified(_value1)) { ThrowTerminatingError(NewError("ValueShouldBeSpecified", UpdateDataStrings.ShouldBeSpecified, null, "Value", _memberType)); } } private void EnsureValue1NotNullOrEmpty() { if (_value1 is string) { if (String.IsNullOrEmpty((string)_value1)) { ThrowTerminatingError(NewError("ValueShouldBeSpecified", UpdateDataStrings.ShouldNotBeNull, null, "Value", _memberType)); } return; } if (_value1 == null) { ThrowTerminatingError(NewError("ValueShouldBeSpecified", UpdateDataStrings.ShouldNotBeNull, null, "Value", _memberType)); } } private void EnsureValue2HasNotBeenSpecified() { if (_value2 != null) { ThrowTerminatingError(NewError("SecondValueShouldNotBeSpecified", UpdateDataStrings.ShouldNotBeSpecified, null, "SecondValue", _memberType)); } } private void EnsureValue1AndValue2AreNotBothNull() { if (_value1 == null && _value2 == null) { ThrowTerminatingError(NewError("ValueAndSecondValueAreNotBothNull", UpdateDataStrings.Value1AndValue2AreNotBothNull, null, _memberType)); } } /// <summary> /// Check if the TypeData instance contains no members /// </summary> /// <param name="typeData"></param> /// <returns>false if empty, true if not</returns> private bool EnsureTypeDataIsNotEmpty(TypeData typeData) { if (typeData.Members.Count == 0 && typeData.StandardMembers.Count == 0 && typeData.TypeConverter == null && typeData.TypeAdapter == null && typeData.DefaultDisplayPropertySet == null && typeData.DefaultKeyPropertySet == null && typeData.PropertySerializationSet == null) { this.WriteError(NewError("TypeDataEmpty", UpdateDataStrings.TypeDataEmpty, null, typeData.TypeName)); return false; } return true; } private NotePropertyData GetNoteProperty() { EnsureMemberNameHasBeenSpecified(); EnsureValue1HasBeenSpecified(); EnsureValue2HasNotBeenSpecified(); return new NotePropertyData(_memberName, _value1); } private AliasPropertyData GetAliasProperty() { EnsureMemberNameHasBeenSpecified(); EnsureValue1HasBeenSpecified(); EnsureValue1NotNullOrEmpty(); AliasPropertyData alias; string referencedName = GetParameterType<string>(_value1); if (_value2 != null) { Type type = GetParameterType<Type>(_value2); alias = new AliasPropertyData(_memberName, referencedName, type); return alias; } alias = new AliasPropertyData(_memberName, referencedName); return alias; } private ScriptPropertyData GetScriptProperty() { EnsureMemberNameHasBeenSpecified(); EnsureValue1HasBeenSpecified(); EnsureValue1AndValue2AreNotBothNull(); ScriptBlock value1ScriptBlock = null; if (_value1 != null) { value1ScriptBlock = GetParameterType<ScriptBlock>(_value1); } ScriptBlock value2ScriptBlock = null; if (_value2 != null) { value2ScriptBlock = GetParameterType<ScriptBlock>(_value2); } ScriptPropertyData scriptProperty = new ScriptPropertyData(_memberName, value1ScriptBlock, value2ScriptBlock); return scriptProperty; } private CodePropertyData GetCodeProperty() { EnsureMemberNameHasBeenSpecified(); EnsureValue1HasBeenSpecified(); EnsureValue1AndValue2AreNotBothNull(); MethodInfo value1CodeReference = null; if (_value1 != null) { value1CodeReference = GetParameterType<MethodInfo>(_value1); } MethodInfo value2CodeReference = null; if (_value2 != null) { value2CodeReference = GetParameterType<MethodInfo>(_value2); } CodePropertyData codeProperty = new CodePropertyData(_memberName, value1CodeReference, value2CodeReference); return codeProperty; } private ScriptMethodData GetScriptMethod() { EnsureMemberNameHasBeenSpecified(); EnsureValue1HasBeenSpecified(); EnsureValue2HasNotBeenSpecified(); ScriptBlock method = GetParameterType<ScriptBlock>(_value1); ScriptMethodData scriptMethod = new ScriptMethodData(_memberName, method); return scriptMethod; } private CodeMethodData GetCodeMethod() { EnsureMemberNameHasBeenSpecified(); EnsureValue1HasBeenSpecified(); EnsureValue2HasNotBeenSpecified(); MethodInfo codeReference = GetParameterType<MethodInfo>(_value1); CodeMethodData codeMethod = new CodeMethodData(_memberName, codeReference); return codeMethod; } /// <summary> /// Generate error record /// </summary> /// <param name="errorId"></param> /// <param name="template"></param> /// <param name="targetObject"></param> /// <param name="args"></param> /// <returns></returns> private ErrorRecord NewError(string errorId, string template, object targetObject, params object[] args) { string message = string.Format(CultureInfo.CurrentCulture, template, args); ErrorRecord errorRecord = new ErrorRecord( new InvalidOperationException(message), errorId, ErrorCategory.InvalidOperation, targetObject); return errorRecord; } #endregion dynamic type processing #region type files processing private void ProcessTypeFiles() { Collection<string> prependPathTotal = Glob(this.PrependPath, "TypesPrependPathException", this); Collection<string> appendPathTotal = Glob(this.AppendPath, "TypesAppendPathException", this); // There are file path input but they did not pass the validation in the method Glob if ((PrependPath.Length > 0 || AppendPath.Length > 0) && prependPathTotal.Count == 0 && appendPathTotal.Count == 0) { return; } string action = UpdateDataStrings.UpdateTypeDataAction; // Load the resource once and format it whenver a new target // filename is available string target = UpdateDataStrings.UpdateTarget; if (Context.RunspaceConfiguration != null) { for (int i = prependPathTotal.Count - 1; i >= 0; i--) { string formattedTarget = string.Format(CultureInfo.InvariantCulture, target, prependPathTotal[i]); if (ShouldProcess(formattedTarget, action)) { this.Context.RunspaceConfiguration.Types.Prepend(new TypeConfigurationEntry(prependPathTotal[i])); } } foreach (string appendPathTotalItem in appendPathTotal) { string formattedTarget = string.Format(CultureInfo.InvariantCulture, target, appendPathTotalItem); if (ShouldProcess(formattedTarget, action)) { this.Context.RunspaceConfiguration.Types.Append(new TypeConfigurationEntry(appendPathTotalItem)); } } try { this.Context.CurrentRunspace.RunspaceConfiguration.Types.Update(true); } catch (RuntimeException e) { this.WriteError(new ErrorRecord(e, "TypesXmlUpdateException", ErrorCategory.InvalidOperation, null)); } } else if (Context.InitialSessionState != null) { // This hashSet is to detect if there are duplicate type files var fullFileNameHash = new HashSet<string>(StringComparer.CurrentCultureIgnoreCase); var newTypes = new Collection<SessionStateTypeEntry>(); for (int i = prependPathTotal.Count - 1; i >= 0; i--) { string formattedTarget = string.Format(CultureInfo.InvariantCulture, target, prependPathTotal[i]); string resolvedPath = ModuleCmdletBase.ResolveRootedFilePath(prependPathTotal[i], Context) ?? prependPathTotal[i]; if (ShouldProcess(formattedTarget, action)) { if (!fullFileNameHash.Contains(resolvedPath)) { fullFileNameHash.Add(resolvedPath); newTypes.Add(new SessionStateTypeEntry(prependPathTotal[i])); } } } // Copy everything from context's TypeTable to newTypes foreach (var entry in Context.InitialSessionState.Types) { if (entry.FileName != null) { string resolvedPath = ModuleCmdletBase.ResolveRootedFilePath(entry.FileName, Context) ?? entry.FileName; if (!fullFileNameHash.Contains(resolvedPath)) { fullFileNameHash.Add(resolvedPath); newTypes.Add(entry); } } else { newTypes.Add(entry); } } foreach (string appendPathTotalItem in appendPathTotal) { string formattedTarget = string.Format(CultureInfo.InvariantCulture, target, appendPathTotalItem); string resolvedPath = ModuleCmdletBase.ResolveRootedFilePath(appendPathTotalItem, Context) ?? appendPathTotalItem; if (ShouldProcess(formattedTarget, action)) { if (!fullFileNameHash.Contains(resolvedPath)) { fullFileNameHash.Add(resolvedPath); newTypes.Add(new SessionStateTypeEntry(appendPathTotalItem)); } } } Context.InitialSessionState.Types.Clear(); Context.TypeTable.Clear(); var errors = new ConcurrentBag<string>(); foreach (SessionStateTypeEntry sste in newTypes) { try { if (sste.TypeTable != null) { var ex = new PSInvalidOperationException(UpdateDataStrings.CannotUpdateTypeWithTypeTable); this.WriteError(new ErrorRecord(ex, "CannotUpdateTypeWithTypeTable", ErrorCategory.InvalidOperation, null)); continue; } else if (sste.FileName != null) { bool unused; Context.TypeTable.Update(sste.FileName, sste.FileName, errors, Context.AuthorizationManager, Context.InitialSessionState.Host, out unused); } else { Context.TypeTable.Update(sste.TypeData, errors, sste.IsRemove); } } catch (RuntimeException ex) { this.WriteError(new ErrorRecord(ex, "TypesXmlUpdateException", ErrorCategory.InvalidOperation, null)); } Context.InitialSessionState.Types.Add(sste); // Write out any errors... if (errors.Count > 0) { foreach (string s in errors) { RuntimeException rte = new RuntimeException(s); this.WriteError(new ErrorRecord(rte, "TypesXmlUpdateException", ErrorCategory.InvalidOperation, null)); } errors = new ConcurrentBag<string>(); } } } else { Dbg.Assert(false, "Either RunspaceConfiguration or InitiaSessionState must be non-null for Update-Typedata to work"); } } #endregion type files processing } /// <summary> /// This class implements update-typeData command. /// </summary> [Cmdlet(VerbsData.Update, "FormatData", SupportsShouldProcess = true, DefaultParameterSetName = FileParameterSet, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113420")] public class UpdateFormatDataCommand : UpdateData { /// <summary> /// This method verify if the Format database manager is shared and cannot be updated /// </summary> protected override void BeginProcessing() { if (Context.FormatDBManager.isShared) { var ex = new InvalidOperationException(FormatAndOutXmlLoadingStrings.SharedFormatTableCannotBeUpdated); this.ThrowTerminatingError(new ErrorRecord(ex, "CannotUpdateSharedFormatTable", ErrorCategory.InvalidOperation, null)); } } /// <summary> /// This method implements the ProcessRecord method for update-FormatData command /// </summary> protected override void ProcessRecord() { Collection<string> prependPathTotal = Glob(this.PrependPath, "FormatPrependPathException", this); Collection<string> appendPathTotal = Glob(this.AppendPath, "FormatAppendPathException", this); // There are file path input but they did not pass the validation in the method Glob if ((PrependPath.Length > 0 || AppendPath.Length > 0) && prependPathTotal.Count == 0 && appendPathTotal.Count == 0) { return; } string action = UpdateDataStrings.UpdateFormatDataAction; // Load the resource once and format it whenver a new target // filename is available string target = UpdateDataStrings.UpdateTarget; if (Context.RunspaceConfiguration != null) { for (int i = prependPathTotal.Count - 1; i >= 0; i--) { string formattedTarget = string.Format(CultureInfo.CurrentCulture, target, prependPathTotal[i]); if (ShouldProcess(formattedTarget, action)) { this.Context.RunspaceConfiguration.Formats.Prepend(new FormatConfigurationEntry(prependPathTotal[i])); } } foreach (string appendPathTotalItem in appendPathTotal) { string formattedTarget = string.Format(CultureInfo.CurrentCulture, target, appendPathTotalItem); if (ShouldProcess(formattedTarget, action)) { this.Context.RunspaceConfiguration.Formats.Append(new FormatConfigurationEntry(appendPathTotalItem)); } } try { this.Context.CurrentRunspace.RunspaceConfiguration.Formats.Update(true); } catch (RuntimeException e) { this.WriteError(new ErrorRecord(e, "FormatXmlUpdateException", ErrorCategory.InvalidOperation, null)); } } else if (Context.InitialSessionState != null) { if (Context.InitialSessionState.DisableFormatUpdates) { throw new PSInvalidOperationException(UpdateDataStrings.FormatUpdatesDisabled); } // This hashSet is to detect if there are duplicate format files var fullFileNameHash = new HashSet<string>(StringComparer.CurrentCultureIgnoreCase); var newFormats = new Collection<SessionStateFormatEntry>(); for (int i = prependPathTotal.Count - 1; i >= 0; i--) { string formattedTarget = string.Format(CultureInfo.CurrentCulture, target, prependPathTotal[i]); if (ShouldProcess(formattedTarget, action)) { if (!fullFileNameHash.Contains(prependPathTotal[i])) { fullFileNameHash.Add(prependPathTotal[i]); newFormats.Add(new SessionStateFormatEntry(prependPathTotal[i])); } } } // Always add InitialSessionState.Formats to the new list foreach (SessionStateFormatEntry entry in Context.InitialSessionState.Formats) { if (entry.FileName != null) { if (!fullFileNameHash.Contains(entry.FileName)) { fullFileNameHash.Add(entry.FileName); newFormats.Add(entry); } } else { newFormats.Add(entry); } } foreach (string appendPathTotalItem in appendPathTotal) { string formattedTarget = string.Format(CultureInfo.CurrentCulture, target, appendPathTotalItem); if (ShouldProcess(formattedTarget, action)) { if (!fullFileNameHash.Contains(appendPathTotalItem)) { fullFileNameHash.Add(appendPathTotalItem); newFormats.Add(new SessionStateFormatEntry(appendPathTotalItem)); } } } try { // Always rebuild the format information Context.InitialSessionState.Formats.Clear(); var entries = new Collection<PSSnapInTypeAndFormatErrors>(); // Now update the formats... foreach (SessionStateFormatEntry ssfe in newFormats) { string name = ssfe.FileName; PSSnapInInfo snapin = ssfe.PSSnapIn; if (snapin != null && !string.IsNullOrEmpty(snapin.Name)) { name = snapin.Name; } if (ssfe.Formattable != null) { var ex = new PSInvalidOperationException(UpdateDataStrings.CannotUpdateFormatWithFormatTable); this.WriteError(new ErrorRecord(ex, "CannotUpdateFormatWithFormatTable", ErrorCategory.InvalidOperation, null)); continue; } else if (ssfe.FormatData != null) { entries.Add(new PSSnapInTypeAndFormatErrors(name, ssfe.FormatData)); } else { entries.Add(new PSSnapInTypeAndFormatErrors(name, ssfe.FileName)); } Context.InitialSessionState.Formats.Add(ssfe); } if (entries.Count > 0) { Context.FormatDBManager.UpdateDataBase(entries, this.Context.AuthorizationManager, this.Context.EngineHostInterface, false); FormatAndTypeDataHelper.ThrowExceptionOnError( "ErrorsUpdatingFormats", null, entries, RunspaceConfigurationCategory.Formats); } } catch (RuntimeException e) { this.WriteError(new ErrorRecord(e, "FormatXmlUpdateException", ErrorCategory.InvalidOperation, null)); } } else { Dbg.Assert(false, "Either RunspaceConfiguration or InitiaSessionState must be non-null for Update-FormatData to work"); } } } /// <summary> /// Remove-TypeData cmdlet /// </summary> [Cmdlet(VerbsCommon.Remove, "TypeData", SupportsShouldProcess = true, DefaultParameterSetName = RemoveTypeDataSet, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=217038")] public class RemoveTypeDataCommand : PSCmdlet { private const string RemoveTypeSet = "RemoveTypeSet"; private const string RemoveFileSet = "RemoveFileSet"; private const string RemoveTypeDataSet = "RemoveTypeDataSet"; private string _typeName; /// <summary> /// The target type to remove /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = RemoveTypeSet)] [ArgumentToTypeNameTransformationAttribute()] [ValidateNotNullOrEmpty] public string TypeName { get { return _typeName; } set { _typeName = value; } } private string[] _typeFiles; /// <summary> /// The type xml file to remove from the cache /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] [Parameter(Mandatory = true, ParameterSetName = RemoveFileSet)] [ValidateNotNullOrEmpty] public string[] Path { get { return _typeFiles; } set { _typeFiles = value; } } private TypeData _typeData; /// <summary> /// The TypeData to remove /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = RemoveTypeDataSet)] public TypeData TypeData { get { return _typeData; } set { _typeData = value; } } private static void ConstructFileToIndexMap(string fileName, int index, Dictionary<string, List<int>> fileNameToIndexMap) { List<int> indexList; if (fileNameToIndexMap.TryGetValue(fileName, out indexList)) { indexList.Add(index); } else { fileNameToIndexMap[fileName] = new List<int> { index }; } } /// <summary> /// This method implements the ProcessRecord method for Remove-TypeData command /// </summary> protected override void ProcessRecord() { if (ParameterSetName == RemoveFileSet) { // Load the resource strings string removeFileAction = UpdateDataStrings.RemoveTypeFileAction; string removeFileTarget = UpdateDataStrings.UpdateTarget; Collection<string> typeFileTotal = UpdateData.Glob(_typeFiles, "TypePathException", this); if (typeFileTotal.Count == 0) { return; } // Key of the map is the name of the file that is in the cache. Value of the map is a index list. Duplicate files might // exist in the cache because the user can add arbitrary files to the cache by $host.Runspace.InitialSessionState.Types.Add() Dictionary<string, List<int>> fileToIndexMap = new Dictionary<string, List<int>>(StringComparer.OrdinalIgnoreCase); List<int> indicesToRemove = new List<int>(); if (Context.RunspaceConfiguration != null) { for (int index = 0; index < Context.RunspaceConfiguration.Types.Count; index++) { string fileName = Context.RunspaceConfiguration.Types[index].FileName; if (fileName == null) { continue; } ConstructFileToIndexMap(fileName, index, fileToIndexMap); } } else if (Context.InitialSessionState != null) { for (int index = 0; index < Context.InitialSessionState.Types.Count; index++) { string fileName = Context.InitialSessionState.Types[index].FileName; if (fileName == null) { continue; } // Resolving the file path because the path to the types file in module manifest is now specified as // ..\..\types.ps1xml which expands to C:\Windows\System32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Core\..\..\types.ps1xml fileName = ModuleCmdletBase.ResolveRootedFilePath(fileName, Context) ?? fileName; ConstructFileToIndexMap(fileName, index, fileToIndexMap); } } foreach (string typeFile in typeFileTotal) { string removeFileFormattedTarget = string.Format(CultureInfo.InvariantCulture, removeFileTarget, typeFile); if (ShouldProcess(removeFileFormattedTarget, removeFileAction)) { List<int> indexList; if (fileToIndexMap.TryGetValue(typeFile, out indexList)) { indicesToRemove.AddRange(indexList); } else { this.WriteError(NewError("TypeFileNotExistsInCurrentSession", UpdateDataStrings.TypeFileNotExistsInCurrentSession, null, typeFile)); } } } if (indicesToRemove.Count > 0) { indicesToRemove.Sort(); for (int i = indicesToRemove.Count - 1; i >= 0; i--) { if (Context.RunspaceConfiguration != null) { Context.RunspaceConfiguration.Types.RemoveItem(indicesToRemove[i]); } else if (Context.InitialSessionState != null) { Context.InitialSessionState.Types.RemoveItem(indicesToRemove[i]); } } try { if (Context.RunspaceConfiguration != null) { Context.RunspaceConfiguration.Types.Update(); } else if (Context.InitialSessionState != null) { bool oldRefreshTypeFormatSetting = Context.InitialSessionState.RefreshTypeAndFormatSetting; try { Context.InitialSessionState.RefreshTypeAndFormatSetting = true; Context.InitialSessionState.UpdateTypes(Context, false); } finally { Context.InitialSessionState.RefreshTypeAndFormatSetting = oldRefreshTypeFormatSetting; } } } catch (RuntimeException ex) { this.WriteError(new ErrorRecord(ex, "TypesFileRemoveException", ErrorCategory.InvalidOperation, null)); } } return; } // Load the resource strings string removeTypeAction = UpdateDataStrings.RemoveTypeDataAction; string removeTypeTarget = UpdateDataStrings.RemoveTypeDataTarget; string typeNameToRemove = null; if (ParameterSetName == RemoveTypeDataSet) { typeNameToRemove = _typeData.TypeName; } else { if (String.IsNullOrWhiteSpace(_typeName)) { ThrowTerminatingError(NewError("TargetTypeNameEmpty", UpdateDataStrings.TargetTypeNameEmpty, _typeName)); } typeNameToRemove = _typeName; } Dbg.Assert(!String.IsNullOrEmpty(typeNameToRemove), "TypeNameToRemove should be not null and not empty at this point"); TypeData type = new TypeData(typeNameToRemove); string removeTypeFormattedTarget = string.Format(CultureInfo.InvariantCulture, removeTypeTarget, typeNameToRemove); if (ShouldProcess(removeTypeFormattedTarget, removeTypeAction)) { try { var errors = new ConcurrentBag<string>(); Context.TypeTable.Update(type, errors, true); // Write out errors... if (errors.Count > 0) { foreach (string s in errors) { RuntimeException rte = new RuntimeException(s); this.WriteError(new ErrorRecord(rte, "TypesDynamicRemoveException", ErrorCategory.InvalidOperation, null)); } } else { // Type is removed successfully, add it into the cache if (Context.RunspaceConfiguration != null) { Context.RunspaceConfiguration.Types.Append(new TypeConfigurationEntry(type, true)); } else if (Context.InitialSessionState != null) { Context.InitialSessionState.Types.Add(new SessionStateTypeEntry(type, true)); } else { Dbg.Assert(false, "Either RunspaceConfiguration or InitiaSessionState must be non-null for Remove-Typedata to work"); } } } catch (RuntimeException e) { this.WriteError(new ErrorRecord(e, "TypesDynamicRemoveException", ErrorCategory.InvalidOperation, null)); } } } /// <summary> /// This method implements the EndProcessing method for Remove-TypeData command /// </summary> protected override void EndProcessing() { this.Context.TypeTable.ClearConsolidatedMembers(); } private ErrorRecord NewError(string errorId, string template, object targetObject, params object[] args) { string message = string.Format(CultureInfo.CurrentCulture, template, args); ErrorRecord errorRecord = new ErrorRecord( new InvalidOperationException(message), errorId, ErrorCategory.InvalidOperation, targetObject); return errorRecord; } } /// <summary> /// Get-TypeData cmdlet /// </summary> [Cmdlet(VerbsCommon.Get, "TypeData", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=217033")] [OutputType(typeof(System.Management.Automation.PSObject))] public class GetTypeDataCommand : PSCmdlet { private WildcardPattern[] _filter; /// <summary> /// Get Formatting information only for the specified /// typename /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [ValidateNotNullOrEmpty] [Parameter(Position = 0, ValueFromPipeline = true)] public string[] TypeName { get; set; } private void ValidateTypeName() { if (TypeName == null) { _filter = new WildcardPattern[] { WildcardPattern.Get("*", WildcardOptions.None) }; return; } var typeNames = new List<string>(); var exception = new InvalidOperationException(UpdateDataStrings.TargetTypeNameEmpty); foreach (string typeName in TypeName) { if (String.IsNullOrWhiteSpace(typeName)) { WriteError( new ErrorRecord( exception, "TargetTypeNameEmpty", ErrorCategory.InvalidOperation, typeName)); continue; } Type type; string typeNameInUse = typeName; // Respect the type shortcut if (LanguagePrimitives.TryConvertTo(typeNameInUse, out type)) { typeNameInUse = type.FullName; } typeNames.Add(typeNameInUse); } _filter = new WildcardPattern[typeNames.Count]; for (int i = 0; i < _filter.Length; i++) { _filter[i] = WildcardPattern.Get(typeNames[i], WildcardOptions.Compiled | WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase); } } /// <summary> /// Takes out the content from the database and writes them /// out /// </summary> protected override void ProcessRecord() { ValidateTypeName(); Dictionary<string, TypeData> alltypes = Context.TypeTable.GetAllTypeData(); Collection<TypeData> typedefs = new Collection<TypeData>(); foreach (string type in alltypes.Keys) { foreach (WildcardPattern pattern in _filter) { if (pattern.IsMatch(type)) { typedefs.Add(alltypes[type]); break; } } } // write out all the available type definitions foreach (TypeData typedef in typedefs) { WriteObject(typedef); } } } /// <summary> /// To make it easier to specify a TypeName, we add an ArgumentTransformationAttribute here. /// * string: retrun the string /// * Type: return the Type.ToString() /// * instance: return instance.GetType().ToString() /// </summary> internal sealed class ArgumentToTypeNameTransformationAttribute : ArgumentTransformationAttribute { public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) { string typeName; object target = PSObject.Base(inputData); if (target is Type) { typeName = ((Type)target).FullName; } else if (target is string) { // Respect the type shortcut Type type; typeName = (string)target; if (LanguagePrimitives.TryConvertTo(typeName, out type)) { typeName = type.FullName; } } else if (target is TypeData) { typeName = ((TypeData)target).TypeName; } else { typeName = target.GetType().FullName; } return typeName; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Threading.Tasks; using Azure.Core; using Azure.Core.Pipeline; using Azure.Storage.Queues.Models; using Azure.Storage.Shared; namespace Azure.Storage.Queues { /// <summary> /// Provides the client configuration options for connecting to Azure Queue /// Storage /// </summary> public class QueueClientOptions : ClientOptions, ISupportsTenantIdChallenges { /// <summary> /// The Latest service version supported by this client library. /// </summary> internal const ServiceVersion LatestVersion = StorageVersionExtensions.LatestVersion; /// <summary> /// The versions of Azure Queue Storage supported by this client /// library. /// /// For more information, see /// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/versioning-for-the-azure-storage-services"> /// Versioning for the Azure Storage services</see>. /// </summary> public enum ServiceVersion { #pragma warning disable CA1707 // Identifiers should not contain underscores /// <summary> /// The 2019-02-02 service version described at /// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/version-2019-02-02"> /// Version 2019-02-02</see>. /// </summary> V2019_02_02 = 1, /// <summary> /// The 2019-07-07 service version described at /// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/version-2019-07-07"> /// Version 2019-07-07</see>. /// </summary> V2019_07_07 = 2, /// <summary> /// The 2019-12-12 service version. /// </summary> V2019_12_12 = 3, /// <summary> /// The 2020-02-10 service version. /// </summary> V2020_02_10 = 4, /// <summary> /// The 2020-04-08 service version. /// </summary> V2020_04_08 = 5, /// <summary> /// The 2020-06-12 service version. /// </summary> V2020_06_12 = 6, /// <summary> /// The 2020-08-14 service version. /// </summary> V2020_08_04 = 7, /// <summary> /// The 2020-10-02 service version. /// </summary> V2020_10_02 = 8, /// <summary> /// The 2020-12-06 service version. /// </summary> V2020_12_06 = 9, /// <summary> /// The 2021-02-12 service version. /// </summary> V2021_02_12 = 10, /// <summary> /// The 2021-04-10 serivce version. /// </summary> V2021_04_10 = 11 #pragma warning restore CA1707 // Identifiers should not contain underscores } /// <summary> /// Gets the <see cref="ServiceVersion"/> of the service API used when /// making requests. For more, see /// For more information, see /// <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/versioning-for-the-azure-storage-services"> /// Versioning for the Azure Storage services</see>. /// </summary> public ServiceVersion Version { get; } /// <summary> /// Initializes a new instance of the <see cref="QueueClientOptions"/> /// class. /// </summary> /// <param name="version"> /// The <see cref="ServiceVersion"/> of the service API used when /// making requests. /// </param> public QueueClientOptions(ServiceVersion version = LatestVersion) { if (ServiceVersion.V2019_02_02 <= version && version <= StorageVersionExtensions.MaxVersion) { Version = version; } else { throw Errors.VersionNotSupported(nameof(version)); } this.Initialize(); AddHeadersAndQueryParameters(); } /// <summary> /// Gets or sets the secondary storage <see cref="Uri"/> that can be read from for the storage account if the /// account is enabled for RA-GRS. /// /// If this property is set, the secondary Uri will be used for GET or HEAD requests during retries. /// If the status of the response from the secondary Uri is a 404, then subsequent retries for /// the request will not use the secondary Uri again, as this indicates that the resource /// may not have propagated there yet. Otherwise, subsequent retries will alternate back and forth /// between primary and secondary Uri. /// </summary> public Uri GeoRedundantSecondaryUri { get; set; } /// <summary> /// Gets or sets a message encoding that determines how <see cref="QueueMessage.Body"/> is represented in HTTP requests and responses. /// The default is <see cref="QueueMessageEncoding.None"/>. /// </summary> public QueueMessageEncoding MessageEncoding { get; set; } = QueueMessageEncoding.None; /// <inheritdoc /> public bool EnableTenantDiscovery { get; set; } /// <summary> /// Optional. Performs the tasks needed when a message is received or peaked from the queue but cannot be decoded. /// /// <para>Such message can be received or peaked when <see cref="QueueClient"/> is expecting certain <see cref="QueueMessageEncoding"/> /// but there's another producer that is not encoding messages in expected way. I.e. the queue contains messages with different encoding.</para> /// /// <para><see cref="QueueMessageDecodingFailedEventArgs"/> contains <see cref="QueueClient"/> that has received the message as well as /// <see cref="QueueMessageDecodingFailedEventArgs.ReceivedMessage"/> or <see cref="QueueMessageDecodingFailedEventArgs.PeekedMessage"/> /// with raw body, i.e. no decoding will be attempted so that /// body can be inspected as has been received from the queue.</para> /// /// <para>The <see cref="QueueClient"/> won't attempt to remove the message from the queue. Therefore such handling should be included into /// the event handler itself.</para> /// /// <para>The handler is potentially invoked by both synchronous and asynchronous receive and peek APIs. Therefore implementation of the handler should align with /// <see cref="QueueClient"/> APIs that are being used. /// See <see cref="SyncAsyncEventHandler{T}"/> about how to implement handler correctly. The example below shows a handler with all possible cases explored. /// <code snippet="Snippet:Azure_Storage_Queues_Samples_Sample03_MessageEncoding_MessageDecodingFailedHandlerAsync" language="csharp"> /// QueueClientOptions queueClientOptions = new QueueClientOptions() /// { /// MessageEncoding = QueueMessageEncoding.Base64 /// }; /// /// queueClientOptions.MessageDecodingFailed += async (QueueMessageDecodingFailedEventArgs args) =&gt; /// { /// if (args.PeekedMessage != null) /// { /// Console.WriteLine($&quot;Invalid message has been peeked, message id={args.PeekedMessage.MessageId} body={args.PeekedMessage.Body}&quot;); /// } /// else if (args.ReceivedMessage != null) /// { /// Console.WriteLine($&quot;Invalid message has been received, message id={args.ReceivedMessage.MessageId} body={args.ReceivedMessage.Body}&quot;); /// /// if (args.IsRunningSynchronously) /// { /// args.Queue.DeleteMessage(args.ReceivedMessage.MessageId, args.ReceivedMessage.PopReceipt); /// } /// else /// { /// await args.Queue.DeleteMessageAsync(args.ReceivedMessage.MessageId, args.ReceivedMessage.PopReceipt); /// } /// } /// }; /// /// QueueClient queueClient = new QueueClient(connectionString, queueName, queueClientOptions); /// </code> /// </para> /// </summary> public event SyncAsyncEventHandler<QueueMessageDecodingFailedEventArgs> MessageDecodingFailed; internal SyncAsyncEventHandler<QueueMessageDecodingFailedEventArgs> GetMessageDecodingFailedHandlers() => MessageDecodingFailed; #region Advanced Options internal ClientSideEncryptionOptions _clientSideEncryptionOptions; #endregion /// <summary> /// Add headers and query parameters in <see cref="DiagnosticsOptions.LoggedHeaderNames"/> and <see cref="DiagnosticsOptions.LoggedQueryParameters"/> /// </summary> private void AddHeadersAndQueryParameters() { Diagnostics.LoggedHeaderNames.Add("Access-Control-Allow-Origin"); Diagnostics.LoggedHeaderNames.Add("x-ms-date"); Diagnostics.LoggedHeaderNames.Add("x-ms-error-code"); Diagnostics.LoggedHeaderNames.Add("x-ms-request-id"); Diagnostics.LoggedHeaderNames.Add("x-ms-version"); Diagnostics.LoggedHeaderNames.Add("x-ms-approximate-messages-count"); Diagnostics.LoggedHeaderNames.Add("x-ms-popreceipt"); Diagnostics.LoggedHeaderNames.Add("x-ms-time-next-visible"); Diagnostics.LoggedQueryParameters.Add("comp"); Diagnostics.LoggedQueryParameters.Add("maxresults"); Diagnostics.LoggedQueryParameters.Add("rscc"); Diagnostics.LoggedQueryParameters.Add("rscd"); Diagnostics.LoggedQueryParameters.Add("rsce"); Diagnostics.LoggedQueryParameters.Add("rscl"); Diagnostics.LoggedQueryParameters.Add("rsct"); Diagnostics.LoggedQueryParameters.Add("se"); Diagnostics.LoggedQueryParameters.Add("si"); Diagnostics.LoggedQueryParameters.Add("sip"); Diagnostics.LoggedQueryParameters.Add("sp"); Diagnostics.LoggedQueryParameters.Add("spr"); Diagnostics.LoggedQueryParameters.Add("sr"); Diagnostics.LoggedQueryParameters.Add("srt"); Diagnostics.LoggedQueryParameters.Add("ss"); Diagnostics.LoggedQueryParameters.Add("st"); Diagnostics.LoggedQueryParameters.Add("sv"); Diagnostics.LoggedQueryParameters.Add("include"); Diagnostics.LoggedQueryParameters.Add("marker"); Diagnostics.LoggedQueryParameters.Add("prefix"); Diagnostics.LoggedQueryParameters.Add("messagettl"); Diagnostics.LoggedQueryParameters.Add("numofmessages"); Diagnostics.LoggedQueryParameters.Add("peekonly"); Diagnostics.LoggedQueryParameters.Add("popreceipt"); Diagnostics.LoggedQueryParameters.Add("visibilitytimeout"); } /// <summary> /// Create an HttpPipeline from QueueClientOptions. /// </summary> /// <param name="authentication">Optional authentication policy.</param> /// <returns>An HttpPipeline to use for Storage requests.</returns> internal HttpPipeline Build(HttpPipelinePolicy authentication = null) { return this.Build(authentication, GeoRedundantSecondaryUri); } /// <summary> /// Create an HttpPipeline from QueueClientOptions. /// </summary> /// <param name="credentials">Optional authentication credentials.</param> /// <returns>An HttpPipeline to use for Storage requests.</returns> internal HttpPipeline Build(object credentials) { return this.Build(credentials, GeoRedundantSecondaryUri); } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using Gallio.Common.Collections; using Gallio.Framework.Data; using MbUnit.Framework; using Rhino.Mocks; namespace Gallio.Tests.Framework.Data { [TestFixture] [TestsOn(typeof(JoinedDataSet))] [DependsOn(typeof(BaseDataSetTest))] public class JoinedDataSetTest : BaseTestWithMocks { private delegate IEnumerable<IList<IDataItem>> JoinDelegate(IList<IDataProvider> providers, IList<ICollection<DataBinding>> bindingsPerProvider, bool includeDynamicItems); [Test] public void DefaultStrategyIsCombinatorial() { JoinedDataSet dataSet = new JoinedDataSet(); Assert.AreSame(CombinatorialJoinStrategy.Instance, dataSet.Strategy); } [Test, ExpectedArgumentNullException] public void StrategySetterThrowsIfValueIsNull() { JoinedDataSet dataSet = new JoinedDataSet(); dataSet.Strategy = null; } [Test] public void StrategySetThenGet() { JoinedDataSet dataSet = new JoinedDataSet(); dataSet.Strategy = PairwiseJoinStrategy.Instance; Assert.AreSame(PairwiseJoinStrategy.Instance, dataSet.Strategy); } [Test] public void AddingDataSetsUpdatesTheColumnCountAndDataSetsCollection() { JoinedDataSet dataSet = new JoinedDataSet(); IDataSet dataSetWithTwoColumns = Mocks.StrictMock<IDataSet>(); IDataSet dataSetWithThreeColumns = Mocks.StrictMock<IDataSet>(); using (Mocks.Record()) { SetupResult.For(dataSetWithTwoColumns.ColumnCount).Return(2); SetupResult.For(dataSetWithThreeColumns.ColumnCount).Return(3); } using (Mocks.Playback()) { Assert.AreEqual(0, dataSet.ColumnCount); Assert.AreElementsEqual(new IDataSet[] { }, dataSet.DataSets); dataSet.AddDataSet(dataSetWithTwoColumns); Assert.AreEqual(2, dataSet.ColumnCount); Assert.AreElementsEqual(new IDataSet[] { dataSetWithTwoColumns }, dataSet.DataSets); dataSet.AddDataSet(dataSetWithThreeColumns); Assert.AreEqual(5, dataSet.ColumnCount); Assert.AreElementsEqual(new IDataSet[] { dataSetWithTwoColumns, dataSetWithThreeColumns }, dataSet.DataSets); } } [Test, ExpectedArgumentNullException] public void AddingDataSetWithNullArgumentThrows() { JoinedDataSet dataSet = new JoinedDataSet(); dataSet.AddDataSet(null); } [Test, ExpectedArgumentException] public void AddingDataSetThatIsAlreadyAddedThrows() { JoinedDataSet dataSet = new JoinedDataSet(); IDataSet dataSetToAdd = Mocks.Stub<IDataSet>(); dataSet.AddDataSet(dataSetToAdd); dataSet.AddDataSet(dataSetToAdd); } [Test] public void CanBindReturnsFalseIfThereAreNoDataSets() { JoinedDataSet dataSet = new JoinedDataSet(); Assert.IsFalse(dataSet.CanBind(new DataBinding(0, null)), "Cannot bind because there are no data sets."); } [Test] public void CanBindResolvesExternalBindings() { JoinedDataSet dataSet = new JoinedDataSet(); DataSource dataSet1 = new DataSource(""); dataSet1.AddIndexAlias("path", 1); dataSet1.AddDataSet(new ItemSequenceDataSet(EmptyArray<IDataItem>.Instance, 3)); IDataSet dataSet2 = new ItemSequenceDataSet(EmptyArray<IDataItem>.Instance, 2); dataSet.AddDataSet(dataSet1); dataSet.AddDataSet(dataSet2); Assert.IsFalse(dataSet.CanBind(new DataBinding(null, null)), "Cannot bind because there is no path or index."); Assert.IsFalse(dataSet.CanBind(new DataBinding(5, null)), "Cannot bind because index 5 is beyond the range of columns in the joined data set."); Assert.IsTrue(dataSet.CanBind(new DataBinding(4, null)), "Can bind because index 4 is within the range of columns in the joined data set."); Assert.IsTrue(dataSet.CanBind(new DataBinding(0, null)), "Can bind because index 0 is within the range of columns in the joined data set."); Assert.IsTrue(dataSet.CanBind(new DataBinding(null, "path")), "Can bind because path is supported by one of the data sets."); } [Test] public void CanBindResolvesScopedBindings() { JoinedDataSet dataSet = new JoinedDataSet(); DataSource dataSet1 = new DataSource(""); dataSet1.AddIndexAlias("path", 1); dataSet1.AddDataSet(new ItemSequenceDataSet(EmptyArray<IDataItem>.Instance, 3)); IDataSet dataSet2 = new ItemSequenceDataSet(EmptyArray<IDataItem>.Instance, 2); dataSet.AddDataSet(dataSet1); dataSet.AddDataSet(dataSet2); Assert.IsFalse(dataSet.CanBind(dataSet.TranslateBinding(dataSet1, new DataBinding(null, null))), "Cannot bind because there is no path or index in the translated binding."); Assert.IsFalse(dataSet.CanBind(dataSet.TranslateBinding(dataSet1, new DataBinding(3, null))), "Cannot bind because index 3 is beyond the range of columns in the scoped data set."); Assert.IsFalse(dataSet.CanBind(dataSet.TranslateBinding(dataSet2, new DataBinding(2, null))), "Cannot bind because index 2 is beyond the range of columns in the scoped data set."); Assert.IsTrue(dataSet.CanBind(dataSet.TranslateBinding(dataSet2, new DataBinding(1, null))), "Can bind because index 1 is within the range of columns in the scoped data set."); Assert.IsTrue(dataSet.CanBind(dataSet.TranslateBinding(dataSet1, new DataBinding(null, "path"))), "Can bind because path is supported by one of the scoped data set."); Assert.IsFalse(dataSet.CanBind(dataSet.TranslateBinding(dataSet2, new DataBinding(null, "path"))), "Cannot bind because path is supported by one of the scoped data set."); } [Test] public void GetItemsDelegatesToTheStrategy() { JoinedDataSet dataSet = new JoinedDataSet(); IList<KeyValuePair<string, string>> metadata1 = new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("abc", "123"), new KeyValuePair<string, string>("def", "456") }; IList<KeyValuePair<string, string>> metadata2 = new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("ghi", "789"), }; DataSource dataSet1 = new DataSource(""); dataSet1.AddIndexAlias("path", 1); dataSet1.AddDataSet(new ItemSequenceDataSet(new IDataItem[] { new ListDataItem<int>(new int[] { 1, 2, 3 }, metadata1, false), new ListDataItem<int>(new int[] { -1, -2, -3 }, metadata2, false) }, 3)); dataSet.AddDataSet(dataSet1); IDataSet dataSet2 = new ItemSequenceDataSet(new IDataItem[] { new ListDataItem<int>(new int[] { 4, 5 }, metadata2, false), new ListDataItem<int>(new int[] { -4, -5 }, null, true) }, 2); dataSet.AddDataSet(dataSet2); List<IDataItem> dataSet1Items = new List<IDataItem>(dataSet1.GetItems(EmptyArray<DataBinding>.Instance, true)); List<IDataItem> dataSet2Items = new List<IDataItem>(dataSet2.GetItems(EmptyArray<DataBinding>.Instance, true)); List<IList<IDataItem>> results = new List<IList<IDataItem>>(); results.Add(new IDataItem[] { dataSet1Items[0], dataSet2Items[0] }); results.Add(new IDataItem[] { dataSet1Items[1], dataSet2Items[1] }); IJoinStrategy strategy = Mocks.StrictMock<IJoinStrategy>(); dataSet.Strategy = strategy; DataBinding pathBinding = new DataBinding(null, "path"); DataBinding indexZeroBinding = new DataBinding(0, null); DataBinding indexOneBinding = new DataBinding(1, null); DataBinding indexThreeBinding = new DataBinding(3, null); DataBinding[] bindings = new DataBinding[] { new DataBinding(null, null), // unresolvable binding because no data sets can claim it pathBinding, // claimed by dataSet1 indexZeroBinding, // claimed by dataSet1 indexThreeBinding, // claimed by dataSet2 dataSet.TranslateBinding(dataSet1, pathBinding), // scoped by dataSet1 dataSet.TranslateBinding(dataSet2, indexOneBinding), // scoped by dataSet2 }; using (Mocks.Record()) { Expect.Call(strategy.Join(null, null, true)).IgnoreArguments().Do((JoinDelegate)delegate(IList<IDataProvider> joinProviders, IList<ICollection<DataBinding>> joinBindingsPerProvider, bool includeDynamicItems) { Assert.IsTrue(includeDynamicItems); Assert.AreElementsEqual(new IDataProvider[] { dataSet1, dataSet2 }, joinProviders); Assert.Count(2, joinBindingsPerProvider); Assert.AreElementsEqual(new DataBinding[] { pathBinding, indexZeroBinding, pathBinding }, joinBindingsPerProvider[0]); Assert.AreElementsEqual(new DataBinding[] { indexZeroBinding, indexOneBinding }, joinBindingsPerProvider[1]); return results; }); } using (Mocks.Playback()) { List<IDataItem> items = new List<IDataItem>(dataSet.GetItems(bindings, true)); Assert.Count(2, items); Assert.Throws<ArgumentNullException>(delegate { items[0].GetValue(null); }); Assert.Throws<DataBindingException>(delegate { items[0].GetValue(bindings[0]); }); Assert.AreEqual(2, items[0].GetValue(bindings[1])); Assert.AreEqual(1, items[0].GetValue(bindings[2])); Assert.AreEqual(4, items[0].GetValue(bindings[3])); Assert.AreEqual(2, items[0].GetValue(bindings[4])); Assert.AreEqual(5, items[0].GetValue(bindings[5])); PropertyBag map = DataItemUtils.GetMetadata(items[0]); Assert.Count(3, map); Assert.AreEqual("123", map.GetValue("abc")); Assert.AreEqual("456", map.GetValue("def")); Assert.AreEqual("789", map.GetValue("ghi")); Assert.IsFalse(items[0].IsDynamic); Assert.Throws<DataBindingException>(delegate { items[1].GetValue(bindings[0]); }); Assert.AreEqual(-2, items[1].GetValue(bindings[1])); Assert.AreEqual(-1, items[1].GetValue(bindings[2])); Assert.AreEqual(-4, items[1].GetValue(bindings[3])); Assert.AreEqual(-2, items[1].GetValue(bindings[4])); Assert.AreEqual(-5, items[1].GetValue(bindings[5])); map = DataItemUtils.GetMetadata(items[1]); Assert.Count(1, map); Assert.AreEqual("789", map.GetValue("ghi")); Assert.IsTrue(items[1].IsDynamic); } } [Test] public void TranslateBindingReplacesTheDataBindingIndexWhenPresentAsNeeded() { JoinedDataSet dataSet = new JoinedDataSet(); IDataSet dataSetWithTwoColumns = Mocks.StrictMock<IDataSet>(); IDataSet dataSetWithThreeColumns = Mocks.StrictMock<IDataSet>(); using (Mocks.Record()) { SetupResult.For(dataSetWithTwoColumns.ColumnCount).Return(2); SetupResult.For(dataSetWithThreeColumns.ColumnCount).Return(3); } using (Mocks.Playback()) { dataSet.AddDataSet(dataSetWithTwoColumns); dataSet.AddDataSet(dataSetWithThreeColumns); DataBinding bindingWithNoIndex = new DataBinding(null, null); DataBinding bindingWithIndex = new DataBinding(1, null); AssertTranslateReplacedIndex(dataSet, dataSetWithTwoColumns, bindingWithNoIndex, null, "No binding index in original so none should be present when translated."); AssertTranslateReplacedIndex(dataSet, dataSetWithTwoColumns, bindingWithIndex, 1, "Offset of data set is 0 so index should be unchanged."); AssertTranslateReplacedIndex(dataSet, dataSetWithThreeColumns, bindingWithNoIndex, null, "No binding index in original so none should be present when translated."); AssertTranslateReplacedIndex(dataSet, dataSetWithThreeColumns, bindingWithIndex, 3, "Offset of data set is 2 so index should be incremented by 2."); } } private void AssertTranslateReplacedIndex(JoinedDataSet joinedDataSet, IDataSet innerDataSet, DataBinding binding, int? expectedIndex, string message) { DataBinding translatedBinding = joinedDataSet.TranslateBinding(innerDataSet, binding); Assert.AreEqual(expectedIndex, translatedBinding.Index, message); Assert.AreEqual(binding.Path, translatedBinding.Path, "Path should be preserved."); } [Test, ExpectedArgumentNullException] public void TranslateBindingThrowsIfDataSetIsNull() { JoinedDataSet dataSet = new JoinedDataSet(); dataSet.TranslateBinding(null, new DataBinding(0, null)); } [Test, ExpectedArgumentNullException] public void TranslateBindingThrowsIfDataBindingIsNull() { JoinedDataSet dataSet = new JoinedDataSet(); dataSet.TranslateBinding(Mocks.Stub<IDataSet>(), null); } [Test, ExpectedArgumentException] public void TranslateBindingThrowsIfDataSetNotAMember() { JoinedDataSet dataSet = new JoinedDataSet(); dataSet.TranslateBinding(Mocks.Stub<IDataSet>(), new DataBinding(0, null)); } [Test] public void TranslateBindingSupportsReplaceIndex() { JoinedDataSet dataSet = new JoinedDataSet(); DataSource source = new DataSource("dummy"); dataSet.AddDataSet(source); DataBinding dataBinding = dataSet.TranslateBinding(source, new DataBinding(null, "path")); Assert.IsNull(dataBinding.Index); Assert.AreEqual("path", dataBinding.Path); DataBinding changedDataBinding = dataBinding.ReplaceIndex(5); Assert.AreEqual(5, changedDataBinding.Index); Assert.AreEqual("path", dataBinding.Path); } [Test] public void CanGetDescriptiveDataBindingsFromItem() { DataSource source = new DataSource("Source"); source.AddDataSet(new ItemSequenceDataSet(new[] { new DataRow("abc", "def") }, 2)); source.AddIndexAlias("abc", 0); JoinedDataSet dataSet = new JoinedDataSet(); dataSet.AddDataSet(new ItemSequenceDataSet(new[] { new DataRow("xyz") }, 1)); dataSet.AddDataSet(source); List<IDataItem> items = new List<IDataItem>(dataSet.GetItems(EmptyArray<DataBinding>.Instance, true)); Assert.AreElementsEqual(new[] { new DataBinding(0, null), new DataBinding(1, "abc"), new DataBinding(2, null) }, items[0].GetBindingsForInformalDescription()); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using lro = Google.LongRunning; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.Retail.V2 { /// <summary>Settings for <see cref="CompletionServiceClient"/> instances.</summary> public sealed partial class CompletionServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="CompletionServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="CompletionServiceSettings"/>.</returns> public static CompletionServiceSettings GetDefault() => new CompletionServiceSettings(); /// <summary>Constructs a new <see cref="CompletionServiceSettings"/> object with default settings.</summary> public CompletionServiceSettings() { } private CompletionServiceSettings(CompletionServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); CompleteQuerySettings = existing.CompleteQuerySettings; ImportCompletionDataSettings = existing.ImportCompletionDataSettings; ImportCompletionDataOperationsSettings = existing.ImportCompletionDataOperationsSettings.Clone(); OnCopy(existing); } partial void OnCopy(CompletionServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>CompletionServiceClient.CompleteQuery</c> and <c>CompletionServiceClient.CompleteQueryAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 5000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 5 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings CompleteQuerySettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(5000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(5000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>CompletionServiceClient.ImportCompletionData</c> and <c>CompletionServiceClient.ImportCompletionDataAsync</c> /// . /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 5000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 5 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ImportCompletionDataSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(5000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(5000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// Long Running Operation settings for calls to <c>CompletionServiceClient.ImportCompletionData</c> and /// <c>CompletionServiceClient.ImportCompletionDataAsync</c>. /// </summary> /// <remarks> /// Uses default <see cref="gax::PollSettings"/> of: /// <list type="bullet"> /// <item><description>Initial delay: 20 seconds.</description></item> /// <item><description>Delay multiplier: 1.5</description></item> /// <item><description>Maximum delay: 45 seconds.</description></item> /// <item><description>Total timeout: 24 hours.</description></item> /// </list> /// </remarks> public lro::OperationsSettings ImportCompletionDataOperationsSettings { get; set; } = new lro::OperationsSettings { DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)), }; /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="CompletionServiceSettings"/> object.</returns> public CompletionServiceSettings Clone() => new CompletionServiceSettings(this); } /// <summary> /// Builder class for <see cref="CompletionServiceClient"/> to provide simple configuration of credentials, endpoint /// etc. /// </summary> public sealed partial class CompletionServiceClientBuilder : gaxgrpc::ClientBuilderBase<CompletionServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public CompletionServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public CompletionServiceClientBuilder() { UseJwtAccessWithScopes = CompletionServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref CompletionServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CompletionServiceClient> task); /// <summary>Builds the resulting client.</summary> public override CompletionServiceClient Build() { CompletionServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<CompletionServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<CompletionServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private CompletionServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return CompletionServiceClient.Create(callInvoker, Settings); } private async stt::Task<CompletionServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return CompletionServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => CompletionServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => CompletionServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => CompletionServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>CompletionService client wrapper, for convenient use.</summary> /// <remarks> /// Auto-completion service for retail. /// /// This feature is only available for users who have Retail Search enabled. /// Please submit a form [here](https://cloud.google.com/contact) to contact /// cloud sales if you are interested in using Retail Search. /// </remarks> public abstract partial class CompletionServiceClient { /// <summary> /// The default endpoint for the CompletionService service, which is a host of "retail.googleapis.com" and a /// port of 443. /// </summary> public static string DefaultEndpoint { get; } = "retail.googleapis.com:443"; /// <summary>The default CompletionService scopes.</summary> /// <remarks> /// The default CompletionService scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="CompletionServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="CompletionServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="CompletionServiceClient"/>.</returns> public static stt::Task<CompletionServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new CompletionServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="CompletionServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="CompletionServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="CompletionServiceClient"/>.</returns> public static CompletionServiceClient Create() => new CompletionServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="CompletionServiceClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="CompletionServiceSettings"/>.</param> /// <returns>The created <see cref="CompletionServiceClient"/>.</returns> internal static CompletionServiceClient Create(grpccore::CallInvoker callInvoker, CompletionServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } CompletionService.CompletionServiceClient grpcClient = new CompletionService.CompletionServiceClient(callInvoker); return new CompletionServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC CompletionService client</summary> public virtual CompletionService.CompletionServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Completes the specified prefix with keyword suggestions. /// /// This feature is only available for users who have Retail Search enabled. /// Please submit a form [here](https://cloud.google.com/contact) to contact /// cloud sales if you are interested in using Retail Search. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual CompleteQueryResponse CompleteQuery(CompleteQueryRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Completes the specified prefix with keyword suggestions. /// /// This feature is only available for users who have Retail Search enabled. /// Please submit a form [here](https://cloud.google.com/contact) to contact /// cloud sales if you are interested in using Retail Search. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<CompleteQueryResponse> CompleteQueryAsync(CompleteQueryRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Completes the specified prefix with keyword suggestions. /// /// This feature is only available for users who have Retail Search enabled. /// Please submit a form [here](https://cloud.google.com/contact) to contact /// cloud sales if you are interested in using Retail Search. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<CompleteQueryResponse> CompleteQueryAsync(CompleteQueryRequest request, st::CancellationToken cancellationToken) => CompleteQueryAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Bulk import of processed completion dataset. /// /// Request processing may be synchronous. Partial updating is not supported. /// /// This feature is only available for users who have Retail Search enabled. /// Please submit a form [here](https://cloud.google.com/contact) to contact /// cloud sales if you are interested in using Retail Search. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<ImportCompletionDataResponse, ImportMetadata> ImportCompletionData(ImportCompletionDataRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Bulk import of processed completion dataset. /// /// Request processing may be synchronous. Partial updating is not supported. /// /// This feature is only available for users who have Retail Search enabled. /// Please submit a form [here](https://cloud.google.com/contact) to contact /// cloud sales if you are interested in using Retail Search. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<ImportCompletionDataResponse, ImportMetadata>> ImportCompletionDataAsync(ImportCompletionDataRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Bulk import of processed completion dataset. /// /// Request processing may be synchronous. Partial updating is not supported. /// /// This feature is only available for users who have Retail Search enabled. /// Please submit a form [here](https://cloud.google.com/contact) to contact /// cloud sales if you are interested in using Retail Search. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<ImportCompletionDataResponse, ImportMetadata>> ImportCompletionDataAsync(ImportCompletionDataRequest request, st::CancellationToken cancellationToken) => ImportCompletionDataAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary>The long-running operations client for <c>ImportCompletionData</c>.</summary> public virtual lro::OperationsClient ImportCompletionDataOperationsClient => throw new sys::NotImplementedException(); /// <summary> /// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>ImportCompletionData</c> /// . /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The result of polling the operation.</returns> public virtual lro::Operation<ImportCompletionDataResponse, ImportMetadata> PollOnceImportCompletionData(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<ImportCompletionDataResponse, ImportMetadata>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), ImportCompletionDataOperationsClient, callSettings); /// <summary> /// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of /// <c>ImportCompletionData</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A task representing the result of polling the operation.</returns> public virtual stt::Task<lro::Operation<ImportCompletionDataResponse, ImportMetadata>> PollOnceImportCompletionDataAsync(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<ImportCompletionDataResponse, ImportMetadata>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), ImportCompletionDataOperationsClient, callSettings); } /// <summary>CompletionService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Auto-completion service for retail. /// /// This feature is only available for users who have Retail Search enabled. /// Please submit a form [here](https://cloud.google.com/contact) to contact /// cloud sales if you are interested in using Retail Search. /// </remarks> public sealed partial class CompletionServiceClientImpl : CompletionServiceClient { private readonly gaxgrpc::ApiCall<CompleteQueryRequest, CompleteQueryResponse> _callCompleteQuery; private readonly gaxgrpc::ApiCall<ImportCompletionDataRequest, lro::Operation> _callImportCompletionData; /// <summary> /// Constructs a client wrapper for the CompletionService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="CompletionServiceSettings"/> used within this client.</param> public CompletionServiceClientImpl(CompletionService.CompletionServiceClient grpcClient, CompletionServiceSettings settings) { GrpcClient = grpcClient; CompletionServiceSettings effectiveSettings = settings ?? CompletionServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); ImportCompletionDataOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.ImportCompletionDataOperationsSettings); _callCompleteQuery = clientHelper.BuildApiCall<CompleteQueryRequest, CompleteQueryResponse>(grpcClient.CompleteQueryAsync, grpcClient.CompleteQuery, effectiveSettings.CompleteQuerySettings).WithGoogleRequestParam("catalog", request => request.Catalog); Modify_ApiCall(ref _callCompleteQuery); Modify_CompleteQueryApiCall(ref _callCompleteQuery); _callImportCompletionData = clientHelper.BuildApiCall<ImportCompletionDataRequest, lro::Operation>(grpcClient.ImportCompletionDataAsync, grpcClient.ImportCompletionData, effectiveSettings.ImportCompletionDataSettings).WithGoogleRequestParam("parent", request => request.Parent); Modify_ApiCall(ref _callImportCompletionData); Modify_ImportCompletionDataApiCall(ref _callImportCompletionData); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_CompleteQueryApiCall(ref gaxgrpc::ApiCall<CompleteQueryRequest, CompleteQueryResponse> call); partial void Modify_ImportCompletionDataApiCall(ref gaxgrpc::ApiCall<ImportCompletionDataRequest, lro::Operation> call); partial void OnConstruction(CompletionService.CompletionServiceClient grpcClient, CompletionServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC CompletionService client</summary> public override CompletionService.CompletionServiceClient GrpcClient { get; } partial void Modify_CompleteQueryRequest(ref CompleteQueryRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_ImportCompletionDataRequest(ref ImportCompletionDataRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Completes the specified prefix with keyword suggestions. /// /// This feature is only available for users who have Retail Search enabled. /// Please submit a form [here](https://cloud.google.com/contact) to contact /// cloud sales if you are interested in using Retail Search. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override CompleteQueryResponse CompleteQuery(CompleteQueryRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CompleteQueryRequest(ref request, ref callSettings); return _callCompleteQuery.Sync(request, callSettings); } /// <summary> /// Completes the specified prefix with keyword suggestions. /// /// This feature is only available for users who have Retail Search enabled. /// Please submit a form [here](https://cloud.google.com/contact) to contact /// cloud sales if you are interested in using Retail Search. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<CompleteQueryResponse> CompleteQueryAsync(CompleteQueryRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CompleteQueryRequest(ref request, ref callSettings); return _callCompleteQuery.Async(request, callSettings); } /// <summary>The long-running operations client for <c>ImportCompletionData</c>.</summary> public override lro::OperationsClient ImportCompletionDataOperationsClient { get; } /// <summary> /// Bulk import of processed completion dataset. /// /// Request processing may be synchronous. Partial updating is not supported. /// /// This feature is only available for users who have Retail Search enabled. /// Please submit a form [here](https://cloud.google.com/contact) to contact /// cloud sales if you are interested in using Retail Search. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override lro::Operation<ImportCompletionDataResponse, ImportMetadata> ImportCompletionData(ImportCompletionDataRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ImportCompletionDataRequest(ref request, ref callSettings); return new lro::Operation<ImportCompletionDataResponse, ImportMetadata>(_callImportCompletionData.Sync(request, callSettings), ImportCompletionDataOperationsClient); } /// <summary> /// Bulk import of processed completion dataset. /// /// Request processing may be synchronous. Partial updating is not supported. /// /// This feature is only available for users who have Retail Search enabled. /// Please submit a form [here](https://cloud.google.com/contact) to contact /// cloud sales if you are interested in using Retail Search. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override async stt::Task<lro::Operation<ImportCompletionDataResponse, ImportMetadata>> ImportCompletionDataAsync(ImportCompletionDataRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ImportCompletionDataRequest(ref request, ref callSettings); return new lro::Operation<ImportCompletionDataResponse, ImportMetadata>(await _callImportCompletionData.Async(request, callSettings).ConfigureAwait(false), ImportCompletionDataOperationsClient); } } public static partial class CompletionService { public partial class CompletionServiceClient { /// <summary> /// Creates a new instance of <see cref="lro::Operations.OperationsClient"/> using the same call invoker as /// this client. /// </summary> /// <returns>A new Operations client for the same target as this client.</returns> public virtual lro::Operations.OperationsClient CreateOperationsClient() => new lro::Operations.OperationsClient(CallInvoker); } } }
namespace java.lang { [global::MonoJavaBridge.JavaClass(typeof(global::java.lang.AbstractStringBuilder_))] public abstract partial class AbstractStringBuilder : java.lang.Object, Appendable, CharSequence { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected AbstractStringBuilder(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public abstract global::java.lang.String toString(); private static global::MonoJavaBridge.MethodId _m1; public virtual global::java.lang.AbstractStringBuilder append(long arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "append", "(J)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m2; public virtual global::java.lang.Appendable append(java.lang.CharSequence arg0, int arg1, int arg2) { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.lang.Appendable>(this, global::java.lang.AbstractStringBuilder.staticClass, "append", "(Ljava/lang/CharSequence;II)Ljava/lang/Appendable;", ref global::java.lang.AbstractStringBuilder._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as java.lang.Appendable; } public java.lang.Appendable append(string arg0, int arg1, int arg2) { return append((global::java.lang.CharSequence)(global::java.lang.String)arg0, arg1, arg2); } private static global::MonoJavaBridge.MethodId _m3; public virtual global::java.lang.AbstractStringBuilder append(int arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "append", "(I)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m4; public virtual global::java.lang.Appendable append(char arg0) { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.lang.Appendable>(this, global::java.lang.AbstractStringBuilder.staticClass, "append", "(C)Ljava/lang/Appendable;", ref global::java.lang.AbstractStringBuilder._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Appendable; } private static global::MonoJavaBridge.MethodId _m5; public virtual global::java.lang.AbstractStringBuilder append(bool arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "append", "(Z)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m6; public virtual global::java.lang.AbstractStringBuilder append(char[] arg0, int arg1, int arg2) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "append", "([CII)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m7; public virtual global::java.lang.Appendable append(java.lang.CharSequence arg0) { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.lang.Appendable>(this, global::java.lang.AbstractStringBuilder.staticClass, "append", "(Ljava/lang/CharSequence;)Ljava/lang/Appendable;", ref global::java.lang.AbstractStringBuilder._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Appendable; } public java.lang.Appendable append(string arg0) { return append((global::java.lang.CharSequence)(global::java.lang.String)arg0); } private static global::MonoJavaBridge.MethodId _m8; public virtual global::java.lang.AbstractStringBuilder append(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "append", "(Ljava/lang/Object;)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m9; public virtual global::java.lang.AbstractStringBuilder append(java.lang.String arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "append", "(Ljava/lang/String;)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m10; public virtual global::java.lang.AbstractStringBuilder append(java.lang.StringBuffer arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "append", "(Ljava/lang/StringBuffer;)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m11; public virtual global::java.lang.AbstractStringBuilder append(char[] arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "append", "([C)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m12; public virtual global::java.lang.AbstractStringBuilder append(double arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "append", "(D)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m13; public virtual global::java.lang.AbstractStringBuilder append(float arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "append", "(F)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m14; public virtual int indexOf(java.lang.String arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "indexOf", "(Ljava/lang/String;I)I", ref global::java.lang.AbstractStringBuilder._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m15; public virtual int indexOf(java.lang.String arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "indexOf", "(Ljava/lang/String;)I", ref global::java.lang.AbstractStringBuilder._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m16; public virtual int length() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "length", "()I", ref global::java.lang.AbstractStringBuilder._m16); } private static global::MonoJavaBridge.MethodId _m17; public virtual char charAt(int arg0) { return global::MonoJavaBridge.JavaBridge.CallCharMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "charAt", "(I)C", ref global::java.lang.AbstractStringBuilder._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m18; public virtual int codePointAt(int arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "codePointAt", "(I)I", ref global::java.lang.AbstractStringBuilder._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m19; public virtual int codePointBefore(int arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "codePointBefore", "(I)I", ref global::java.lang.AbstractStringBuilder._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m20; public virtual int codePointCount(int arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "codePointCount", "(II)I", ref global::java.lang.AbstractStringBuilder._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m21; public virtual int offsetByCodePoints(int arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "offsetByCodePoints", "(II)I", ref global::java.lang.AbstractStringBuilder._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m22; public virtual void getChars(int arg0, int arg1, char[] arg2, int arg3) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "getChars", "(II[CI)V", ref global::java.lang.AbstractStringBuilder._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m23; public virtual int lastIndexOf(java.lang.String arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "lastIndexOf", "(Ljava/lang/String;I)I", ref global::java.lang.AbstractStringBuilder._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m24; public virtual int lastIndexOf(java.lang.String arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "lastIndexOf", "(Ljava/lang/String;)I", ref global::java.lang.AbstractStringBuilder._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m25; public virtual global::java.lang.String substring(int arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.lang.AbstractStringBuilder.staticClass, "substring", "(II)Ljava/lang/String;", ref global::java.lang.AbstractStringBuilder._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m26; public virtual global::java.lang.String substring(int arg0) { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.lang.AbstractStringBuilder.staticClass, "substring", "(I)Ljava/lang/String;", ref global::java.lang.AbstractStringBuilder._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m27; public virtual global::java.lang.CharSequence subSequence(int arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.lang.CharSequence>(this, global::java.lang.AbstractStringBuilder.staticClass, "subSequence", "(II)Ljava/lang/CharSequence;", ref global::java.lang.AbstractStringBuilder._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.CharSequence; } private static global::MonoJavaBridge.MethodId _m28; public virtual global::java.lang.AbstractStringBuilder replace(int arg0, int arg1, java.lang.String arg2) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "replace", "(IILjava/lang/String;)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m29; public virtual void trimToSize() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "trimToSize", "()V", ref global::java.lang.AbstractStringBuilder._m29); } private static global::MonoJavaBridge.MethodId _m30; public virtual void ensureCapacity(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "ensureCapacity", "(I)V", ref global::java.lang.AbstractStringBuilder._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m31; public virtual int capacity() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "capacity", "()I", ref global::java.lang.AbstractStringBuilder._m31); } private static global::MonoJavaBridge.MethodId _m32; public virtual void setLength(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "setLength", "(I)V", ref global::java.lang.AbstractStringBuilder._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m33; public virtual void setCharAt(int arg0, char arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "setCharAt", "(IC)V", ref global::java.lang.AbstractStringBuilder._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m34; public virtual global::java.lang.AbstractStringBuilder appendCodePoint(int arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "appendCodePoint", "(I)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m35; public virtual global::java.lang.AbstractStringBuilder delete(int arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "delete", "(II)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m36; public virtual global::java.lang.AbstractStringBuilder deleteCharAt(int arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "deleteCharAt", "(I)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m37; public virtual global::java.lang.AbstractStringBuilder insert(int arg0, char arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "insert", "(IC)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m37, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m38; public virtual global::java.lang.AbstractStringBuilder insert(int arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "insert", "(II)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m38, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m39; public virtual global::java.lang.AbstractStringBuilder insert(int arg0, long arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "insert", "(IJ)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m39, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m40; public virtual global::java.lang.AbstractStringBuilder insert(int arg0, float arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "insert", "(IF)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m40, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m41; public virtual global::java.lang.AbstractStringBuilder insert(int arg0, double arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "insert", "(ID)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m41, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m42; public virtual global::java.lang.AbstractStringBuilder insert(int arg0, java.lang.String arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "insert", "(ILjava/lang/String;)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m42, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m43; public virtual global::java.lang.AbstractStringBuilder insert(int arg0, java.lang.Object arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "insert", "(ILjava/lang/Object;)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m43, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m44; public virtual global::java.lang.AbstractStringBuilder insert(int arg0, char[] arg1, int arg2, int arg3) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "insert", "(I[CII)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m44, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m45; public virtual global::java.lang.AbstractStringBuilder insert(int arg0, char[] arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "insert", "(I[C)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m45, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m46; public virtual global::java.lang.AbstractStringBuilder insert(int arg0, java.lang.CharSequence arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "insert", "(ILjava/lang/CharSequence;)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m46, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.AbstractStringBuilder; } public java.lang.AbstractStringBuilder insert(int arg0, string arg1) { return insert(arg0, (global::java.lang.CharSequence)(global::java.lang.String)arg1); } private static global::MonoJavaBridge.MethodId _m47; public virtual global::java.lang.AbstractStringBuilder insert(int arg0, java.lang.CharSequence arg1, int arg2, int arg3) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "insert", "(ILjava/lang/CharSequence;II)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m47, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)) as java.lang.AbstractStringBuilder; } public java.lang.AbstractStringBuilder insert(int arg0, string arg1, int arg2, int arg3) { return insert(arg0, (global::java.lang.CharSequence)(global::java.lang.String)arg1, arg2, arg3); } private static global::MonoJavaBridge.MethodId _m48; public virtual global::java.lang.AbstractStringBuilder insert(int arg0, bool arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "insert", "(IZ)Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m48, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.AbstractStringBuilder; } private static global::MonoJavaBridge.MethodId _m49; public virtual global::java.lang.AbstractStringBuilder reverse() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.AbstractStringBuilder.staticClass, "reverse", "()Ljava/lang/AbstractStringBuilder;", ref global::java.lang.AbstractStringBuilder._m49) as java.lang.AbstractStringBuilder; } static AbstractStringBuilder() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.lang.AbstractStringBuilder.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/lang/AbstractStringBuilder")); } } [global::MonoJavaBridge.JavaProxy(typeof(global::java.lang.AbstractStringBuilder))] internal sealed partial class AbstractStringBuilder_ : java.lang.AbstractStringBuilder { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal AbstractStringBuilder_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public override global::java.lang.String toString() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.lang.AbstractStringBuilder_.staticClass, "toString", "()Ljava/lang/String;", ref global::java.lang.AbstractStringBuilder_._m0) as java.lang.String; } static AbstractStringBuilder_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.lang.AbstractStringBuilder_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/lang/AbstractStringBuilder")); } } }
/* * 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. */ // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable MemberCanBePrivate.Global #pragma warning disable 618 namespace Apache.Ignite.Core.Tests { using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Xml; using System.Xml.Linq; using System.Xml.Schema; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache.Affinity.Rendezvous; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cache.Eviction; using Apache.Ignite.Core.Cache.Expiry; using Apache.Ignite.Core.Cache.Store; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Communication.Tcp; using Apache.Ignite.Core.Configuration; using Apache.Ignite.Core.DataStructures.Configuration; using Apache.Ignite.Core.Deployment; using Apache.Ignite.Core.Discovery.Tcp; using Apache.Ignite.Core.Discovery.Tcp.Multicast; using Apache.Ignite.Core.Events; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.PersistentStore; using Apache.Ignite.Core.Plugin.Cache; using Apache.Ignite.Core.Tests.Binary; using Apache.Ignite.Core.Tests.Plugin; using Apache.Ignite.Core.Transactions; using Apache.Ignite.NLog; using NUnit.Framework; using CheckpointWriteOrder = Apache.Ignite.Core.PersistentStore.CheckpointWriteOrder; using DataPageEvictionMode = Apache.Ignite.Core.Cache.Configuration.DataPageEvictionMode; using WalMode = Apache.Ignite.Core.PersistentStore.WalMode; /// <summary> /// Tests <see cref="IgniteConfiguration"/> serialization. /// </summary> public class IgniteConfigurationSerializerTest { /// <summary> /// Tests the predefined XML. /// </summary> [Test] public void TestPredefinedXml() { var xml = File.ReadAllText("Config\\full-config.xml"); var cfg = IgniteConfiguration.FromXml(xml); Assert.AreEqual("c:", cfg.WorkDirectory); Assert.AreEqual("127.1.1.1", cfg.Localhost); Assert.IsTrue(cfg.IsDaemon); Assert.AreEqual(1024, cfg.JvmMaxMemoryMb); Assert.AreEqual(TimeSpan.FromSeconds(10), cfg.MetricsLogFrequency); Assert.AreEqual(TimeSpan.FromMinutes(1), ((TcpDiscoverySpi)cfg.DiscoverySpi).JoinTimeout); Assert.AreEqual("192.168.1.1", ((TcpDiscoverySpi)cfg.DiscoverySpi).LocalAddress); Assert.AreEqual(6655, ((TcpDiscoverySpi)cfg.DiscoverySpi).LocalPort); Assert.AreEqual(7, ((TcpDiscoveryMulticastIpFinder) ((TcpDiscoverySpi) cfg.DiscoverySpi).IpFinder).AddressRequestAttempts); Assert.AreEqual(new[] { "-Xms1g", "-Xmx4g" }, cfg.JvmOptions); Assert.AreEqual(15, ((LifecycleBean) cfg.LifecycleHandlers.Single()).Foo); Assert.AreEqual("testBar", ((NameMapper) cfg.BinaryConfiguration.NameMapper).Bar); Assert.AreEqual( "Apache.Ignite.Core.Tests.IgniteConfigurationSerializerTest+FooClass, Apache.Ignite.Core.Tests", cfg.BinaryConfiguration.Types.Single()); Assert.IsFalse(cfg.BinaryConfiguration.CompactFooter); Assert.AreEqual(new[] {42, EventType.TaskFailed, EventType.JobFinished}, cfg.IncludedEventTypes); Assert.AreEqual(@"c:\myconfig.xml", cfg.SpringConfigUrl); Assert.IsTrue(cfg.AutoGenerateIgniteInstanceName); Assert.AreEqual(new TimeSpan(1, 2, 3), cfg.LongQueryWarningTimeout); Assert.IsFalse(cfg.IsActiveOnStart); Assert.AreEqual("someId012", cfg.ConsistentId); Assert.IsFalse(cfg.RedirectJavaConsoleOutput); Assert.AreEqual("secondCache", cfg.CacheConfiguration.Last().Name); var cacheCfg = cfg.CacheConfiguration.First(); Assert.AreEqual(CacheMode.Replicated, cacheCfg.CacheMode); Assert.IsTrue(cacheCfg.ReadThrough); Assert.IsTrue(cacheCfg.WriteThrough); Assert.IsInstanceOf<MyPolicyFactory>(cacheCfg.ExpiryPolicyFactory); Assert.IsTrue(cacheCfg.EnableStatistics); Assert.IsFalse(cacheCfg.WriteBehindCoalescing); Assert.AreEqual(PartitionLossPolicy.ReadWriteAll, cacheCfg.PartitionLossPolicy); Assert.AreEqual("fooGroup", cacheCfg.GroupName); Assert.AreEqual("bar", cacheCfg.KeyConfiguration.Single().AffinityKeyFieldName); Assert.AreEqual("foo", cacheCfg.KeyConfiguration.Single().TypeName); Assert.IsTrue(cacheCfg.OnheapCacheEnabled); Assert.AreEqual(8, cacheCfg.StoreConcurrentLoadAllThreshold); Assert.AreEqual(9, cacheCfg.RebalanceOrder); Assert.AreEqual(10, cacheCfg.RebalanceBatchesPrefetchCount); Assert.AreEqual(11, cacheCfg.MaxQueryIteratorsCount); Assert.AreEqual(12, cacheCfg.QueryDetailMetricsSize); Assert.AreEqual(13, cacheCfg.QueryParallelism); Assert.AreEqual("mySchema", cacheCfg.SqlSchema); var queryEntity = cacheCfg.QueryEntities.Single(); Assert.AreEqual(typeof(int), queryEntity.KeyType); Assert.AreEqual(typeof(string), queryEntity.ValueType); Assert.AreEqual("myTable", queryEntity.TableName); Assert.AreEqual("length", queryEntity.Fields.Single().Name); Assert.AreEqual(typeof(int), queryEntity.Fields.Single().FieldType); Assert.IsTrue(queryEntity.Fields.Single().IsKeyField); Assert.IsTrue(queryEntity.Fields.Single().NotNull); Assert.AreEqual(3.456d, (double)queryEntity.Fields.Single().DefaultValue); Assert.AreEqual("somefield.field", queryEntity.Aliases.Single().FullName); Assert.AreEqual("shortField", queryEntity.Aliases.Single().Alias); var queryIndex = queryEntity.Indexes.Single(); Assert.AreEqual(QueryIndexType.Geospatial, queryIndex.IndexType); Assert.AreEqual("indexFld", queryIndex.Fields.Single().Name); Assert.AreEqual(true, queryIndex.Fields.Single().IsDescending); Assert.AreEqual(123, queryIndex.InlineSize); var nearCfg = cacheCfg.NearConfiguration; Assert.IsNotNull(nearCfg); Assert.AreEqual(7, nearCfg.NearStartSize); var plc = nearCfg.EvictionPolicy as FifoEvictionPolicy; Assert.IsNotNull(plc); Assert.AreEqual(10, plc.BatchSize); Assert.AreEqual(20, plc.MaxSize); Assert.AreEqual(30, plc.MaxMemorySize); var plc2 = cacheCfg.EvictionPolicy as LruEvictionPolicy; Assert.IsNotNull(plc2); Assert.AreEqual(1, plc2.BatchSize); Assert.AreEqual(2, plc2.MaxSize); Assert.AreEqual(3, plc2.MaxMemorySize); var af = cacheCfg.AffinityFunction as RendezvousAffinityFunction; Assert.IsNotNull(af); Assert.AreEqual(99, af.Partitions); Assert.IsTrue(af.ExcludeNeighbors); Assert.AreEqual(new Dictionary<string, object> { {"myNode", "true"}, {"foo", new FooClass {Bar = "Baz"}} }, cfg.UserAttributes); var atomicCfg = cfg.AtomicConfiguration; Assert.AreEqual(2, atomicCfg.Backups); Assert.AreEqual(CacheMode.Local, atomicCfg.CacheMode); Assert.AreEqual(250, atomicCfg.AtomicSequenceReserveSize); var tx = cfg.TransactionConfiguration; Assert.AreEqual(TransactionConcurrency.Optimistic, tx.DefaultTransactionConcurrency); Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.DefaultTransactionIsolation); Assert.AreEqual(new TimeSpan(0,1,2), tx.DefaultTimeout); Assert.AreEqual(15, tx.PessimisticTransactionLogSize); Assert.AreEqual(TimeSpan.FromSeconds(33), tx.PessimisticTransactionLogLinger); var comm = cfg.CommunicationSpi as TcpCommunicationSpi; Assert.IsNotNull(comm); Assert.AreEqual(33, comm.AckSendThreshold); Assert.AreEqual(new TimeSpan(0, 1, 2), comm.IdleConnectionTimeout); Assert.IsInstanceOf<TestLogger>(cfg.Logger); var binType = cfg.BinaryConfiguration.TypeConfigurations.Single(); Assert.AreEqual("typeName", binType.TypeName); Assert.AreEqual("affKeyFieldName", binType.AffinityKeyFieldName); Assert.IsTrue(binType.IsEnum); Assert.AreEqual(true, binType.KeepDeserialized); Assert.IsInstanceOf<IdMapper>(binType.IdMapper); Assert.IsInstanceOf<NameMapper>(binType.NameMapper); Assert.IsInstanceOf<TestSerializer>(binType.Serializer); var plugins = cfg.PluginConfigurations; Assert.IsNotNull(plugins); Assert.IsNotNull(plugins.Cast<TestIgnitePluginConfiguration>().SingleOrDefault()); Assert.IsNotNull(cacheCfg.PluginConfigurations.Cast<MyPluginConfiguration>().SingleOrDefault()); var eventStorage = cfg.EventStorageSpi as MemoryEventStorageSpi; Assert.IsNotNull(eventStorage); Assert.AreEqual(23.45, eventStorage.ExpirationTimeout.TotalSeconds); Assert.AreEqual(129, eventStorage.MaxEventCount); var memCfg = cfg.MemoryConfiguration; Assert.IsNotNull(memCfg); Assert.AreEqual(3, memCfg.ConcurrencyLevel); Assert.AreEqual("dfPlc", memCfg.DefaultMemoryPolicyName); Assert.AreEqual(45, memCfg.PageSize); Assert.AreEqual(67, memCfg.SystemCacheInitialSize); Assert.AreEqual(68, memCfg.SystemCacheMaxSize); var memPlc = memCfg.MemoryPolicies.Single(); Assert.AreEqual(1, memPlc.EmptyPagesPoolSize); Assert.AreEqual(0.2, memPlc.EvictionThreshold); Assert.AreEqual("dfPlc", memPlc.Name); Assert.AreEqual(DataPageEvictionMode.RandomLru, memPlc.PageEvictionMode); Assert.AreEqual("abc", memPlc.SwapFilePath); Assert.AreEqual(89, memPlc.InitialSize); Assert.AreEqual(98, memPlc.MaxSize); Assert.IsTrue(memPlc.MetricsEnabled); Assert.AreEqual(9, memPlc.SubIntervals); Assert.AreEqual(TimeSpan.FromSeconds(62), memPlc.RateTimeInterval); Assert.AreEqual(PeerAssemblyLoadingMode.CurrentAppDomain, cfg.PeerAssemblyLoadingMode); var sql = cfg.SqlConnectorConfiguration; Assert.IsNotNull(sql); Assert.AreEqual("bar", sql.Host); Assert.AreEqual(10, sql.Port); Assert.AreEqual(11, sql.PortRange); Assert.AreEqual(12, sql.SocketSendBufferSize); Assert.AreEqual(13, sql.SocketReceiveBufferSize); Assert.IsTrue(sql.TcpNoDelay); Assert.AreEqual(14, sql.MaxOpenCursorsPerConnection); Assert.AreEqual(15, sql.ThreadPoolSize); var client = cfg.ClientConnectorConfiguration; Assert.IsNotNull(client); Assert.AreEqual("bar", client.Host); Assert.AreEqual(10, client.Port); Assert.AreEqual(11, client.PortRange); Assert.AreEqual(12, client.SocketSendBufferSize); Assert.AreEqual(13, client.SocketReceiveBufferSize); Assert.IsTrue(client.TcpNoDelay); Assert.AreEqual(14, client.MaxOpenCursorsPerConnection); Assert.AreEqual(15, client.ThreadPoolSize); Assert.AreEqual(19, client.IdleTimeout.TotalSeconds); var pers = cfg.PersistentStoreConfiguration; Assert.AreEqual(true, pers.AlwaysWriteFullPages); Assert.AreEqual(TimeSpan.FromSeconds(1), pers.CheckpointingFrequency); Assert.AreEqual(2, pers.CheckpointingPageBufferSize); Assert.AreEqual(3, pers.CheckpointingThreads); Assert.AreEqual(TimeSpan.FromSeconds(4), pers.LockWaitTime); Assert.AreEqual("foo", pers.PersistentStorePath); Assert.AreEqual(5, pers.TlbSize); Assert.AreEqual("bar", pers.WalArchivePath); Assert.AreEqual(TimeSpan.FromSeconds(6), pers.WalFlushFrequency); Assert.AreEqual(7, pers.WalFsyncDelayNanos); Assert.AreEqual(8, pers.WalHistorySize); Assert.AreEqual(WalMode.None, pers.WalMode); Assert.AreEqual(9, pers.WalRecordIteratorBufferSize); Assert.AreEqual(10, pers.WalSegments); Assert.AreEqual(11, pers.WalSegmentSize); Assert.AreEqual("baz", pers.WalStorePath); Assert.IsTrue(pers.MetricsEnabled); Assert.AreEqual(3, pers.SubIntervals); Assert.AreEqual(TimeSpan.FromSeconds(6), pers.RateTimeInterval); Assert.AreEqual(CheckpointWriteOrder.Random, pers.CheckpointWriteOrder); Assert.IsTrue(pers.WriteThrottlingEnabled); var listeners = cfg.LocalEventListeners; Assert.AreEqual(2, listeners.Count); var rebalListener = (LocalEventListener<CacheRebalancingEvent>) listeners.First(); Assert.AreEqual(new[] {EventType.CacheObjectPut, 81}, rebalListener.EventTypes); Assert.AreEqual("Apache.Ignite.Core.Tests.EventsTestLocalListeners+Listener`1" + "[Apache.Ignite.Core.Events.CacheRebalancingEvent]", rebalListener.Listener.GetType().ToString()); var ds = cfg.DataStorageConfiguration; Assert.IsFalse(ds.AlwaysWriteFullPages); Assert.AreEqual(TimeSpan.FromSeconds(1), ds.CheckpointFrequency); Assert.AreEqual(3, ds.CheckpointThreads); Assert.AreEqual(4, ds.ConcurrencyLevel); Assert.AreEqual(TimeSpan.FromSeconds(5), ds.LockWaitTime); Assert.IsTrue(ds.MetricsEnabled); Assert.AreEqual(6, ds.PageSize); Assert.AreEqual("cde", ds.StoragePath); Assert.AreEqual(TimeSpan.FromSeconds(7), ds.MetricsRateTimeInterval); Assert.AreEqual(8, ds.MetricsSubIntervalCount); Assert.AreEqual(9, ds.SystemRegionInitialSize); Assert.AreEqual(10, ds.SystemRegionMaxSize); Assert.AreEqual(11, ds.WalThreadLocalBufferSize); Assert.AreEqual("abc", ds.WalArchivePath); Assert.AreEqual(TimeSpan.FromSeconds(12), ds.WalFlushFrequency); Assert.AreEqual(13, ds.WalFsyncDelayNanos); Assert.AreEqual(14, ds.WalHistorySize); Assert.AreEqual(Core.Configuration.WalMode.Background, ds.WalMode); Assert.AreEqual(15, ds.WalRecordIteratorBufferSize); Assert.AreEqual(16, ds.WalSegments); Assert.AreEqual(17, ds.WalSegmentSize); Assert.AreEqual("wal-store", ds.WalPath); Assert.AreEqual(TimeSpan.FromSeconds(18), ds.WalAutoArchiveAfterInactivity); Assert.IsTrue(ds.WriteThrottlingEnabled); var dr = ds.DataRegionConfigurations.Single(); Assert.AreEqual(1, dr.EmptyPagesPoolSize); Assert.AreEqual(2, dr.EvictionThreshold); Assert.AreEqual(3, dr.InitialSize); Assert.AreEqual(4, dr.MaxSize); Assert.AreEqual("reg2", dr.Name); Assert.AreEqual(Core.Configuration.DataPageEvictionMode.RandomLru, dr.PageEvictionMode); Assert.AreEqual(TimeSpan.FromSeconds(1), dr.MetricsRateTimeInterval); Assert.AreEqual(5, dr.MetricsSubIntervalCount); Assert.AreEqual("swap", dr.SwapPath); Assert.IsTrue(dr.MetricsEnabled); Assert.AreEqual(7, dr.CheckpointPageBufferSize); dr = ds.DefaultDataRegionConfiguration; Assert.AreEqual(2, dr.EmptyPagesPoolSize); Assert.AreEqual(3, dr.EvictionThreshold); Assert.AreEqual(4, dr.InitialSize); Assert.AreEqual(5, dr.MaxSize); Assert.AreEqual("reg1", dr.Name); Assert.AreEqual(Core.Configuration.DataPageEvictionMode.Disabled, dr.PageEvictionMode); Assert.AreEqual(TimeSpan.FromSeconds(3), dr.MetricsRateTimeInterval); Assert.AreEqual(6, dr.MetricsSubIntervalCount); Assert.AreEqual("swap2", dr.SwapPath); Assert.IsFalse(dr.MetricsEnabled); } /// <summary> /// Tests the serialize deserialize. /// </summary> [Test] public void TestSerializeDeserialize() { // Test custom CheckSerializeDeserialize(GetTestConfig()); // Test custom with different culture to make sure numbers are serialized properly RunWithCustomCulture(() => CheckSerializeDeserialize(GetTestConfig())); // Test default CheckSerializeDeserialize(new IgniteConfiguration()); } /// <summary> /// Tests that all properties are present in the schema. /// </summary> [Test] public void TestAllPropertiesArePresentInSchema() { CheckAllPropertiesArePresentInSchema("IgniteConfigurationSection.xsd", "igniteConfiguration", typeof(IgniteConfiguration)); } /// <summary> /// Checks that all properties are present in schema. /// </summary> [SuppressMessage("ReSharper", "PossibleNullReferenceException")] public static void CheckAllPropertiesArePresentInSchema(string xsd, string sectionName, Type type) { var schema = XDocument.Load(xsd) .Root.Elements() .Single(x => x.Attribute("name").Value == sectionName); CheckPropertyIsPresentInSchema(type, schema); } /// <summary> /// Checks the property is present in schema. /// </summary> // ReSharper disable once UnusedParameter.Local // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local private static void CheckPropertyIsPresentInSchema(Type type, XElement schema) { Func<string, string> toLowerCamel = x => char.ToLowerInvariant(x[0]) + x.Substring(1); foreach (var prop in type.GetProperties()) { if (!prop.CanWrite) continue; // Read-only properties are not configured in XML. if (prop.GetCustomAttributes(typeof(ObsoleteAttribute), true).Any()) continue; // Skip deprecated. var propType = prop.PropertyType; var isCollection = propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(ICollection<>); if (isCollection) propType = propType.GetGenericArguments().First(); var propName = toLowerCamel(prop.Name); Assert.IsTrue(schema.Descendants().Select(x => x.Attribute("name")) .Any(x => x != null && x.Value == propName), "Property is missing in XML schema: " + propName); var isComplexProp = propType.Namespace != null && propType.Namespace.StartsWith("Apache.Ignite.Core"); if (isComplexProp) CheckPropertyIsPresentInSchema(propType, schema); } } /// <summary> /// Tests the schema validation. /// </summary> [Test] public void TestSchemaValidation() { CheckSchemaValidation(); RunWithCustomCulture(CheckSchemaValidation); // Check invalid xml const string invalidXml = @"<igniteConfiguration xmlns='http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection'> <binaryConfiguration /><binaryConfiguration /> </igniteConfiguration>"; Assert.Throws<XmlSchemaValidationException>(() => CheckSchemaValidation(invalidXml)); } /// <summary> /// Tests the XML conversion. /// </summary> [Test] public void TestToXml() { // Empty config Assert.AreEqual("<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n<igniteConfiguration " + "xmlns=\"http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection\" />", new IgniteConfiguration().ToXml()); // Some properties var cfg = new IgniteConfiguration { IgniteInstanceName = "myGrid", ClientMode = true, CacheConfiguration = new[] { new CacheConfiguration("myCache") { CacheMode = CacheMode.Replicated, QueryEntities = new[] { new QueryEntity(typeof(int)), new QueryEntity(typeof(int), typeof(string)) } } }, IncludedEventTypes = new[] { EventType.CacheEntryCreated, EventType.CacheNodesLeft } }; Assert.AreEqual(FixLineEndings(@"<?xml version=""1.0"" encoding=""utf-16""?> <igniteConfiguration clientMode=""true"" igniteInstanceName=""myGrid"" xmlns=""http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection""> <cacheConfiguration> <cacheConfiguration cacheMode=""Replicated"" name=""myCache""> <queryEntities> <queryEntity valueType=""System.Int32"" valueTypeName=""java.lang.Integer"" /> <queryEntity keyType=""System.Int32"" keyTypeName=""java.lang.Integer"" valueType=""System.String"" valueTypeName=""java.lang.String"" /> </queryEntities> </cacheConfiguration> </cacheConfiguration> <includedEventTypes> <int>CacheEntryCreated</int> <int>CacheNodesLeft</int> </includedEventTypes> </igniteConfiguration>"), cfg.ToXml()); // Custom section name and indent var sb = new StringBuilder(); var settings = new XmlWriterSettings { Indent = true, IndentChars = " " }; using (var xmlWriter = XmlWriter.Create(sb, settings)) { cfg.ToXml(xmlWriter, "igCfg"); } Assert.AreEqual(FixLineEndings(@"<?xml version=""1.0"" encoding=""utf-16""?> <igCfg clientMode=""true"" igniteInstanceName=""myGrid"" xmlns=""http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection""> <cacheConfiguration> <cacheConfiguration cacheMode=""Replicated"" name=""myCache""> <queryEntities> <queryEntity valueType=""System.Int32"" valueTypeName=""java.lang.Integer"" /> <queryEntity keyType=""System.Int32"" keyTypeName=""java.lang.Integer"" valueType=""System.String"" valueTypeName=""java.lang.String"" /> </queryEntities> </cacheConfiguration> </cacheConfiguration> <includedEventTypes> <int>CacheEntryCreated</int> <int>CacheNodesLeft</int> </includedEventTypes> </igCfg>"), sb.ToString()); } /// <summary> /// Tests the deserialization. /// </summary> [Test] public void TestFromXml() { // Empty section. var cfg = IgniteConfiguration.FromXml("<x />"); AssertExtensions.ReflectionEqual(new IgniteConfiguration(), cfg); // Empty section with XML header. cfg = IgniteConfiguration.FromXml("<?xml version=\"1.0\" encoding=\"utf-16\"?><x />"); AssertExtensions.ReflectionEqual(new IgniteConfiguration(), cfg); // Simple test. cfg = IgniteConfiguration.FromXml(@"<igCfg igniteInstanceName=""myGrid"" clientMode=""true"" />"); AssertExtensions.ReflectionEqual(new IgniteConfiguration {IgniteInstanceName = "myGrid", ClientMode = true}, cfg); // Invalid xml. var ex = Assert.Throws<ConfigurationErrorsException>(() => IgniteConfiguration.FromXml(@"<igCfg foo=""bar"" />")); Assert.AreEqual("Invalid IgniteConfiguration attribute 'foo=bar', there is no such property " + "on 'Apache.Ignite.Core.IgniteConfiguration'", ex.Message); // Xml reader. using (var xmlReader = XmlReader.Create( new StringReader(@"<igCfg igniteInstanceName=""myGrid"" clientMode=""true"" />"))) { cfg = IgniteConfiguration.FromXml(xmlReader); } AssertExtensions.ReflectionEqual(new IgniteConfiguration { IgniteInstanceName = "myGrid", ClientMode = true }, cfg); } /// <summary> /// Ensures windows-style \r\n line endings in a string literal. /// Git settings may cause string literals in both styles. /// </summary> private static string FixLineEndings(string s) { return s.Split('\n').Select(x => x.TrimEnd('\r')) .Aggregate((acc, x) => string.Format("{0}\r\n{1}", acc, x)); } /// <summary> /// Checks the schema validation. /// </summary> private static void CheckSchemaValidation() { CheckSchemaValidation(GetTestConfig().ToXml()); } /// <summary> /// Checks the schema validation. /// </summary> private static void CheckSchemaValidation(string xml) { var xmlns = "http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection"; var schemaFile = "IgniteConfigurationSection.xsd"; CheckSchemaValidation(xml, xmlns, schemaFile); } /// <summary> /// Checks the schema validation. /// </summary> public static void CheckSchemaValidation(string xml, string xmlns, string schemaFile) { var document = new XmlDocument(); document.Schemas.Add(xmlns, XmlReader.Create(schemaFile)); document.Load(new StringReader(xml)); document.Validate(null); } /// <summary> /// Checks the serialize deserialize. /// </summary> /// <param name="cfg">The config.</param> private static void CheckSerializeDeserialize(IgniteConfiguration cfg) { var resCfg = SerializeDeserialize(cfg); AssertExtensions.ReflectionEqual(cfg, resCfg); } /// <summary> /// Serializes and deserializes a config. /// </summary> private static IgniteConfiguration SerializeDeserialize(IgniteConfiguration cfg) { var xml = cfg.ToXml(); return IgniteConfiguration.FromXml(xml); } /// <summary> /// Gets the test configuration. /// </summary> private static IgniteConfiguration GetTestConfig() { return new IgniteConfiguration { IgniteInstanceName = "gridName", JvmOptions = new[] {"1", "2"}, Localhost = "localhost11", JvmClasspath = "classpath", Assemblies = new[] {"asm1", "asm2", "asm3"}, BinaryConfiguration = new BinaryConfiguration { TypeConfigurations = new[] { new BinaryTypeConfiguration { IsEnum = true, KeepDeserialized = true, AffinityKeyFieldName = "affKeyFieldName", TypeName = "typeName", IdMapper = new IdMapper(), NameMapper = new NameMapper(), Serializer = new TestSerializer() }, new BinaryTypeConfiguration { IsEnum = false, KeepDeserialized = false, AffinityKeyFieldName = "affKeyFieldName", TypeName = "typeName2", Serializer = new BinaryReflectiveSerializer() } }, Types = new[] {typeof(string).FullName}, IdMapper = new IdMapper(), KeepDeserialized = true, NameMapper = new NameMapper(), Serializer = new TestSerializer() }, CacheConfiguration = new[] { new CacheConfiguration("cacheName") { AtomicityMode = CacheAtomicityMode.Transactional, Backups = 15, CacheMode = CacheMode.Replicated, CacheStoreFactory = new TestCacheStoreFactory(), CopyOnRead = false, EagerTtl = false, Invalidate = true, KeepBinaryInStore = true, LoadPreviousValue = true, LockTimeout = TimeSpan.FromSeconds(56), MaxConcurrentAsyncOperations = 24, QueryEntities = new[] { new QueryEntity { Fields = new[] { new QueryField("field", typeof(int)) { IsKeyField = true, NotNull = true, DefaultValue = "foo" } }, Indexes = new[] { new QueryIndex("field") { IndexType = QueryIndexType.FullText, InlineSize = 32 } }, Aliases = new[] { new QueryAlias("field.field", "fld") }, KeyType = typeof(string), ValueType = typeof(long), TableName = "table-1", KeyFieldName = "k", ValueFieldName = "v" }, }, ReadFromBackup = false, RebalanceBatchSize = 33, RebalanceDelay = TimeSpan.MaxValue, RebalanceMode = CacheRebalanceMode.Sync, RebalanceThrottle = TimeSpan.FromHours(44), RebalanceTimeout = TimeSpan.FromMinutes(8), SqlEscapeAll = true, WriteBehindBatchSize = 45, WriteBehindEnabled = true, WriteBehindFlushFrequency = TimeSpan.FromSeconds(55), WriteBehindFlushSize = 66, WriteBehindFlushThreadCount = 2, WriteBehindCoalescing = false, WriteSynchronizationMode = CacheWriteSynchronizationMode.FullAsync, NearConfiguration = new NearCacheConfiguration { NearStartSize = 5, EvictionPolicy = new FifoEvictionPolicy { BatchSize = 19, MaxMemorySize = 1024, MaxSize = 555 } }, EvictionPolicy = new LruEvictionPolicy { BatchSize = 18, MaxMemorySize = 1023, MaxSize = 554 }, AffinityFunction = new RendezvousAffinityFunction { ExcludeNeighbors = true, Partitions = 48 }, ExpiryPolicyFactory = new MyPolicyFactory(), EnableStatistics = true, PluginConfigurations = new[] { new MyPluginConfiguration() }, MemoryPolicyName = "somePolicy", PartitionLossPolicy = PartitionLossPolicy.ReadOnlyAll, GroupName = "abc", SqlIndexMaxInlineSize = 24, KeyConfiguration = new[] { new CacheKeyConfiguration { AffinityKeyFieldName = "abc", TypeName = "def" }, }, OnheapCacheEnabled = true, StoreConcurrentLoadAllThreshold = 7, RebalanceOrder = 3, RebalanceBatchesPrefetchCount = 4, MaxQueryIteratorsCount = 512, QueryDetailMetricsSize = 100, QueryParallelism = 16, SqlSchema = "foo" } }, ClientMode = true, DiscoverySpi = new TcpDiscoverySpi { NetworkTimeout = TimeSpan.FromSeconds(1), SocketTimeout = TimeSpan.FromSeconds(2), AckTimeout = TimeSpan.FromSeconds(3), JoinTimeout = TimeSpan.FromSeconds(4), MaxAckTimeout = TimeSpan.FromSeconds(5), IpFinder = new TcpDiscoveryMulticastIpFinder { TimeToLive = 110, MulticastGroup = "multicastGroup", AddressRequestAttempts = 10, MulticastPort = 987, ResponseTimeout = TimeSpan.FromDays(1), LocalAddress = "127.0.0.2", Endpoints = new[] {"", "abc"} }, ClientReconnectDisabled = true, ForceServerMode = true, IpFinderCleanFrequency = TimeSpan.FromMinutes(7), LocalAddress = "127.0.0.1", LocalPort = 49900, LocalPortRange = 13, ReconnectCount = 11, StatisticsPrintFrequency = TimeSpan.FromSeconds(20), ThreadPriority = 6, TopologyHistorySize = 1234567 }, IgniteHome = "igniteHome", IncludedEventTypes = EventType.CacheQueryAll, JvmDllPath = @"c:\jvm", JvmInitialMemoryMb = 1024, JvmMaxMemoryMb = 2048, LifecycleHandlers = new[] {new LifecycleBean(), new LifecycleBean()}, MetricsExpireTime = TimeSpan.FromSeconds(15), MetricsHistorySize = 45, MetricsLogFrequency = TimeSpan.FromDays(2), MetricsUpdateFrequency = TimeSpan.MinValue, NetworkSendRetryCount = 7, NetworkSendRetryDelay = TimeSpan.FromSeconds(98), NetworkTimeout = TimeSpan.FromMinutes(4), SuppressWarnings = true, WorkDirectory = @"c:\work", IsDaemon = true, UserAttributes = Enumerable.Range(1, 10).ToDictionary(x => x.ToString(), x => x % 2 == 0 ? (object) x : new FooClass {Bar = x.ToString()}), AtomicConfiguration = new AtomicConfiguration { CacheMode = CacheMode.Replicated, AtomicSequenceReserveSize = 200, Backups = 2 }, TransactionConfiguration = new TransactionConfiguration { PessimisticTransactionLogSize = 23, DefaultTransactionIsolation = TransactionIsolation.ReadCommitted, DefaultTimeout = TimeSpan.FromDays(2), DefaultTransactionConcurrency = TransactionConcurrency.Optimistic, PessimisticTransactionLogLinger = TimeSpan.FromHours(3) }, CommunicationSpi = new TcpCommunicationSpi { LocalPort = 47501, MaxConnectTimeout = TimeSpan.FromSeconds(34), MessageQueueLimit = 15, ConnectTimeout = TimeSpan.FromSeconds(17), IdleConnectionTimeout = TimeSpan.FromSeconds(19), SelectorsCount = 8, ReconnectCount = 33, SocketReceiveBufferSize = 512, AckSendThreshold = 99, DirectBuffer = false, DirectSendBuffer = true, LocalPortRange = 45, LocalAddress = "127.0.0.1", TcpNoDelay = false, SlowClientQueueLimit = 98, SocketSendBufferSize = 2045, UnacknowledgedMessagesBufferSize = 3450 }, SpringConfigUrl = "test", Logger = new IgniteNLogLogger(), FailureDetectionTimeout = TimeSpan.FromMinutes(2), ClientFailureDetectionTimeout = TimeSpan.FromMinutes(3), LongQueryWarningTimeout = TimeSpan.FromDays(4), PluginConfigurations = new[] {new TestIgnitePluginConfiguration()}, EventStorageSpi = new MemoryEventStorageSpi { ExpirationTimeout = TimeSpan.FromMilliseconds(12345), MaxEventCount = 257 }, MemoryConfiguration = new MemoryConfiguration { ConcurrencyLevel = 3, DefaultMemoryPolicyName = "somePolicy", PageSize = 4, SystemCacheInitialSize = 5, SystemCacheMaxSize = 6, MemoryPolicies = new[] { new MemoryPolicyConfiguration { Name = "myDefaultPlc", PageEvictionMode = DataPageEvictionMode.Random2Lru, InitialSize = 245 * 1024 * 1024, MaxSize = 345 * 1024 * 1024, EvictionThreshold = 0.88, EmptyPagesPoolSize = 77, SwapFilePath = "myPath1", RateTimeInterval = TimeSpan.FromSeconds(22), SubIntervals = 99 }, new MemoryPolicyConfiguration { Name = "customPlc", PageEvictionMode = DataPageEvictionMode.RandomLru, EvictionThreshold = 0.77, EmptyPagesPoolSize = 66, SwapFilePath = "somePath2", MetricsEnabled = true } } }, PeerAssemblyLoadingMode = PeerAssemblyLoadingMode.CurrentAppDomain, ClientConnectorConfiguration = new ClientConnectorConfiguration { Host = "foo", Port = 2, PortRange = 3, MaxOpenCursorsPerConnection = 4, SocketReceiveBufferSize = 5, SocketSendBufferSize = 6, TcpNoDelay = false, ThinClientEnabled = false, OdbcEnabled = false, JdbcEnabled = false, ThreadPoolSize = 7, IdleTimeout = TimeSpan.FromMinutes(5) }, PersistentStoreConfiguration = new PersistentStoreConfiguration { AlwaysWriteFullPages = true, CheckpointingFrequency = TimeSpan.FromSeconds(25), CheckpointingPageBufferSize = 28 * 1024 * 1024, CheckpointingThreads = 2, LockWaitTime = TimeSpan.FromSeconds(5), PersistentStorePath = Path.GetTempPath(), TlbSize = 64 * 1024, WalArchivePath = Path.GetTempPath(), WalFlushFrequency = TimeSpan.FromSeconds(3), WalFsyncDelayNanos = 3, WalHistorySize = 10, WalMode = WalMode.Background, WalRecordIteratorBufferSize = 32 * 1024 * 1024, WalSegments = 6, WalSegmentSize = 5 * 1024 * 1024, WalStorePath = Path.GetTempPath(), SubIntervals = 25, MetricsEnabled = true, RateTimeInterval = TimeSpan.FromDays(1), CheckpointWriteOrder = CheckpointWriteOrder.Random, WriteThrottlingEnabled = true }, IsActiveOnStart = false, ConsistentId = "myId123", LocalEventListeners = new[] { new LocalEventListener<IEvent> { EventTypes = new[] {1, 2}, Listener = new MyEventListener() } }, DataStorageConfiguration = new DataStorageConfiguration { AlwaysWriteFullPages = true, CheckpointFrequency = TimeSpan.FromSeconds(25), CheckpointThreads = 2, LockWaitTime = TimeSpan.FromSeconds(5), StoragePath = Path.GetTempPath(), WalThreadLocalBufferSize = 64 * 1024, WalArchivePath = Path.GetTempPath(), WalFlushFrequency = TimeSpan.FromSeconds(3), WalFsyncDelayNanos = 3, WalHistorySize = 10, WalMode = Core.Configuration.WalMode.None, WalRecordIteratorBufferSize = 32 * 1024 * 1024, WalSegments = 6, WalSegmentSize = 5 * 1024 * 1024, WalPath = Path.GetTempPath(), MetricsEnabled = true, MetricsSubIntervalCount = 7, MetricsRateTimeInterval = TimeSpan.FromSeconds(9), CheckpointWriteOrder = Core.Configuration.CheckpointWriteOrder.Sequential, WriteThrottlingEnabled = true, SystemRegionInitialSize = 64 * 1024 * 1024, SystemRegionMaxSize = 128 * 1024 * 1024, ConcurrencyLevel = 1, PageSize = 5 * 1024, WalAutoArchiveAfterInactivity = TimeSpan.FromSeconds(19), DefaultDataRegionConfiguration = new DataRegionConfiguration { Name = "reg1", EmptyPagesPoolSize = 50, EvictionThreshold = 0.8, InitialSize = 100 * 1024 * 1024, MaxSize = 150 * 1024 * 1024, MetricsEnabled = true, PageEvictionMode = Core.Configuration.DataPageEvictionMode.RandomLru, PersistenceEnabled = false, MetricsRateTimeInterval = TimeSpan.FromMinutes(2), MetricsSubIntervalCount = 6, SwapPath = Path.GetTempPath(), CheckpointPageBufferSize = 7 }, DataRegionConfigurations = new[] { new DataRegionConfiguration { Name = "reg2", EmptyPagesPoolSize = 51, EvictionThreshold = 0.7, InitialSize = 101 * 1024 * 1024, MaxSize = 151 * 1024 * 1024, MetricsEnabled = false, PageEvictionMode = Core.Configuration.DataPageEvictionMode.RandomLru, PersistenceEnabled = false, MetricsRateTimeInterval = TimeSpan.FromMinutes(3), MetricsSubIntervalCount = 7, SwapPath = Path.GetTempPath() } } } }; } /// <summary> /// Runs the with custom culture. /// </summary> /// <param name="action">The action.</param> private static void RunWithCustomCulture(Action action) { RunWithCulture(action, CultureInfo.InvariantCulture); RunWithCulture(action, CultureInfo.GetCultureInfo("ru-RU")); } /// <summary> /// Runs the with culture. /// </summary> /// <param name="action">The action.</param> /// <param name="cultureInfo">The culture information.</param> private static void RunWithCulture(Action action, CultureInfo cultureInfo) { var oldCulture = Thread.CurrentThread.CurrentCulture; try { Thread.CurrentThread.CurrentCulture = cultureInfo; action(); } finally { Thread.CurrentThread.CurrentCulture = oldCulture; } } /// <summary> /// Test bean. /// </summary> public class LifecycleBean : ILifecycleHandler { /// <summary> /// Gets or sets the foo. /// </summary> /// <value> /// The foo. /// </value> public int Foo { get; set; } /// <summary> /// This method is called when lifecycle event occurs. /// </summary> /// <param name="evt">Lifecycle event.</param> public void OnLifecycleEvent(LifecycleEventType evt) { // No-op. } } /// <summary> /// Test mapper. /// </summary> public class NameMapper : IBinaryNameMapper { /// <summary> /// Gets or sets the bar. /// </summary> /// <value> /// The bar. /// </value> public string Bar { get; set; } /// <summary> /// Gets the type name. /// </summary> /// <param name="name">The name.</param> /// <returns> /// Type name. /// </returns> public string GetTypeName(string name) { return name; } /// <summary> /// Gets the field name. /// </summary> /// <param name="name">The name.</param> /// <returns> /// Field name. /// </returns> public string GetFieldName(string name) { return name; } } /// <summary> /// Serializer. /// </summary> public class TestSerializer : IBinarySerializer { /** <inheritdoc /> */ public void WriteBinary(object obj, IBinaryWriter writer) { // No-op. } /** <inheritdoc /> */ public void ReadBinary(object obj, IBinaryReader reader) { // No-op. } } /// <summary> /// Test class. /// </summary> public class FooClass { public string Bar { get; set; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return string.Equals(Bar, ((FooClass) obj).Bar); } public override int GetHashCode() { return Bar != null ? Bar.GetHashCode() : 0; } public static bool operator ==(FooClass left, FooClass right) { return Equals(left, right); } public static bool operator !=(FooClass left, FooClass right) { return !Equals(left, right); } } /// <summary> /// Test factory. /// </summary> public class TestCacheStoreFactory : IFactory<ICacheStore> { /// <summary> /// Creates an instance of the cache store. /// </summary> /// <returns> /// New instance of the cache store. /// </returns> public ICacheStore CreateInstance() { return null; } } /// <summary> /// Test logger. /// </summary> public class TestLogger : ILogger { /** <inheritdoc /> */ public void Log(LogLevel level, string message, object[] args, IFormatProvider formatProvider, string category, string nativeErrorInfo, Exception ex) { throw new NotImplementedException(); } /** <inheritdoc /> */ public bool IsEnabled(LogLevel level) { throw new NotImplementedException(); } } /// <summary> /// Test factory. /// </summary> public class MyPolicyFactory : IFactory<IExpiryPolicy> { /** <inheritdoc /> */ public IExpiryPolicy CreateInstance() { throw new NotImplementedException(); } } public class MyPluginConfiguration : ICachePluginConfiguration { int? ICachePluginConfiguration.CachePluginConfigurationClosureFactoryId { get { return 0; } } void ICachePluginConfiguration.WriteBinary(IBinaryRawWriter writer) { throw new NotImplementedException(); } } public class MyEventListener : IEventListener<IEvent> { public bool Invoke(IEvent evt) { throw new NotImplementedException(); } } } }
// 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 gcsv = Google.Cloud.ServiceDirectory.V1Beta1; using sys = System; namespace Google.Cloud.ServiceDirectory.V1Beta1 { /// <summary>Resource name for the <c>Namespace</c> resource.</summary> public sealed partial class NamespaceName : gax::IResourceName, sys::IEquatable<NamespaceName> { /// <summary>The possible contents of <see cref="NamespaceName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/namespaces/{namespace}</c>. /// </summary> ProjectLocationNamespace = 1, } private static gax::PathTemplate s_projectLocationNamespace = new gax::PathTemplate("projects/{project}/locations/{location}/namespaces/{namespace}"); /// <summary>Creates a <see cref="NamespaceName"/> 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="NamespaceName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static NamespaceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new NamespaceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="NamespaceName"/> with the pattern /// <c>projects/{project}/locations/{location}/namespaces/{namespace}</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="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="NamespaceName"/> constructed from the provided ids.</returns> public static NamespaceName FromProjectLocationNamespace(string projectId, string locationId, string namespaceId) => new NamespaceName(ResourceNameType.ProjectLocationNamespace, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), namespaceId: gax::GaxPreconditions.CheckNotNullOrEmpty(namespaceId, nameof(namespaceId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="NamespaceName"/> with pattern /// <c>projects/{project}/locations/{location}/namespaces/{namespace}</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="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="NamespaceName"/> with pattern /// <c>projects/{project}/locations/{location}/namespaces/{namespace}</c>. /// </returns> public static string Format(string projectId, string locationId, string namespaceId) => FormatProjectLocationNamespace(projectId, locationId, namespaceId); /// <summary> /// Formats the IDs into the string representation of this <see cref="NamespaceName"/> with pattern /// <c>projects/{project}/locations/{location}/namespaces/{namespace}</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="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="NamespaceName"/> with pattern /// <c>projects/{project}/locations/{location}/namespaces/{namespace}</c>. /// </returns> public static string FormatProjectLocationNamespace(string projectId, string locationId, string namespaceId) => s_projectLocationNamespace.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(namespaceId, nameof(namespaceId))); /// <summary>Parses the given resource name string into a new <see cref="NamespaceName"/> 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}/namespaces/{namespace}</c></description> /// </item> /// </list> /// </remarks> /// <param name="namespaceName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="NamespaceName"/> if successful.</returns> public static NamespaceName Parse(string namespaceName) => Parse(namespaceName, false); /// <summary> /// Parses the given resource name string into a new <see cref="NamespaceName"/> 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}/namespaces/{namespace}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="namespaceName">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="NamespaceName"/> if successful.</returns> public static NamespaceName Parse(string namespaceName, bool allowUnparsed) => TryParse(namespaceName, allowUnparsed, out NamespaceName 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="NamespaceName"/> 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}/namespaces/{namespace}</c></description> /// </item> /// </list> /// </remarks> /// <param name="namespaceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="NamespaceName"/>, 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 namespaceName, out NamespaceName result) => TryParse(namespaceName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="NamespaceName"/> 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}/namespaces/{namespace}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="namespaceName">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="NamespaceName"/>, 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 namespaceName, bool allowUnparsed, out NamespaceName result) { gax::GaxPreconditions.CheckNotNull(namespaceName, nameof(namespaceName)); gax::TemplatedResourceName resourceName; if (s_projectLocationNamespace.TryParseName(namespaceName, out resourceName)) { result = FromProjectLocationNamespace(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(namespaceName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private NamespaceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string namespaceId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; NamespaceId = namespaceId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="NamespaceName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/namespaces/{namespace}</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="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param> public NamespaceName(string projectId, string locationId, string namespaceId) : this(ResourceNameType.ProjectLocationNamespace, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), namespaceId: gax::GaxPreconditions.CheckNotNullOrEmpty(namespaceId, nameof(namespaceId))) { } /// <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>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>Namespace</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string NamespaceId { 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.ProjectLocationNamespace: return s_projectLocationNamespace.Expand(ProjectId, LocationId, NamespaceId); 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 NamespaceName); /// <inheritdoc/> public bool Equals(NamespaceName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(NamespaceName a, NamespaceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(NamespaceName a, NamespaceName b) => !(a == b); } public partial class Namespace { /// <summary> /// <see cref="gcsv::NamespaceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcsv::NamespaceName NamespaceName { get => string.IsNullOrEmpty(Name) ? null : gcsv::NamespaceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
// Author: Robert Scheller, Melissa Lucash using Landis.Utilities; using System; using System.Threading; using Landis.Core; using Landis.SpatialModeling; namespace Landis.Extension.Succession.NECN { public enum LayerName {Leaf, FineRoot, Wood, CoarseRoot, Metabolic, Structural, SOM1, SOM2, SOM3, Other}; public enum LayerType {Surface, Soil, Other} /// <summary> /// A Century soil model carbon and nitrogen pool. /// </summary> public class Layer { private LayerName name; private LayerType type; private double carbon; private double nitrogen; private double decayValue; private double fractionLignin; private double netMineralization; private double grossMineralization; //--------------------------------------------------------------------- public Layer(LayerName name, LayerType type) { this.name = name; this.type = type; this.carbon = 0.0; this.nitrogen = 0.0; this.decayValue = 0.0; this.fractionLignin = 0.0; this.netMineralization = 0.0; this.grossMineralization = 0.0; } //--------------------------------------------------------------------- /// <summary> /// Layer Name /// </summary> public LayerName Name { get { return name; } set { name = value; } } //--------------------------------------------------------------------- /// <summary> /// Provides an index to LitterTypeTable /// </summary> public LayerType Type { get { return type; } set { type = value; } } //--------------------------------------------------------------------- /// <summary> /// Carbon /// </summary> public double Carbon { get { return carbon; } set { carbon = Math.Max(0.0, value); } } //--------------------------------------------------------------------- /// <summary> /// Nitrogen /// </summary> public double Nitrogen { get { return nitrogen; } set { nitrogen = Math.Max(0.0, value); } } //--------------------------------------------------------------------- /// <summary> /// Pool decay rate. /// </summary> public double DecayValue { get { return decayValue; } set { decayValue = value; } } //--------------------------------------------------------------------- /// <summary> /// Pool Carbon:Nitrogen Ratio /// </summary> public double FractionLignin { get { return fractionLignin; } set { fractionLignin = value; } } //--------------------------------------------------------------------- /// <summary> /// Net Mineralization /// </summary> public double NetMineralization { get { return netMineralization; } set { netMineralization = value; } } //--------------------------------------------------------------------- /// <summary> /// Gross Mineralization /// </summary> public double GrossMineralization { get { return grossMineralization; } set { grossMineralization = value; } } // -------------------------------------------------- public Layer Clone() { Layer newLayer = new Layer(this.Name, this.Type); newLayer.carbon = this.carbon; newLayer.nitrogen = this.nitrogen ; newLayer.decayValue = this.decayValue ; newLayer.fractionLignin = this.fractionLignin ; newLayer.netMineralization = this.netMineralization ; newLayer.grossMineralization = this.grossMineralization ; return newLayer; } // -------------------------------------------------- public void DecomposeStructural(ActiveSite site) { if (this.Carbon > 0.0000001) { double anerb = SiteVars.AnaerobicEffect[site]; if (this.Type == LayerType.Surface) anerb = 1.0; // No anaerobic effect on surface material //Compute total C flow out of structural in layer double totalCFlow = //System.Math.Min(this.Carbon, OtherData.MaxStructuralC) this.Carbon * SiteVars.DecayFactor[site] //* OtherData.LitterParameters[(int)this.Type].DecayRateStrucC // v6: Replace the fixed value (0.39) with the user input value for surficial C decay * PlugIn.Parameters.DecayRateSurf * anerb * System.Math.Exp(-1.0 * OtherData.LigninDecayEffect * this.FractionLignin) * OtherData.MonthAdjust; //Decompose structural into som1 and som2 with CO2 loss. if (totalCFlow > this.Carbon) { string mesg = string.Format("Error: Decompose Structural totalCFlow > this.Carbon: totalCFlow={0}, DecayFactor={1}, Anerb={2}", totalCFlow, SiteVars.DecayFactor[site], anerb); throw new ApplicationException(mesg); } this.DecomposeLignin(totalCFlow, site); } } // -------------------------------------------------- // Only wood contains lignin public void DecomposeLignin(double totalCFlow, ActiveSite site) { double carbonToSOM1; //Net C flow to SOM1 double carbonToSOM2; //Net C flow to SOM2 double litterC = this.Carbon; double ratioCN = litterC / this.Nitrogen; //See if Layer can decompose to SOM1. //If it can decompose to SOM1, it will also go to SOM2. //If it can't decompose to SOM1, it can't decompose at all. //If Wood Object can decompose if (this.DecomposePossible(ratioCN, SiteVars.MineralN[site])) { // Decompose Wood Object to SOM2 // ----------------------- // Gross C flow to som2 carbonToSOM2 = totalCFlow * this.FractionLignin; //MicrobialRespiration associated with decomposition to som2 double SOM2co2loss = carbonToSOM2 * OtherData.LigninRespirationRate; if (this.Type == LayerType.Surface) this.Respiration(SOM2co2loss, site, true); else this.Respiration(SOM2co2loss, site, false); //Net C flow to SOM2 double netCFlow = carbonToSOM2 - SOM2co2loss; // Partition and schedule C flows this.TransferCarbon(SiteVars.SOM2[site], netCFlow); this.TransferNitrogen(SiteVars.SOM2[site], netCFlow, litterC, ratioCN, site); // ---------------------------------------------- // Decompose Wood Object to SOM1 // Gross C flow to som1 carbonToSOM1 = totalCFlow - netCFlow; double SOM1co2loss; //MicrobialRespiration associated with decomposition to som1 if (this.Type == LayerType.Surface) { SOM1co2loss = carbonToSOM1 * OtherData.StructuralToCO2Surface; this.Respiration(SOM1co2loss, site, true); } else { SOM1co2loss = carbonToSOM1 * OtherData.StructuralToCO2Soil; this.Respiration(SOM1co2loss, site, false); } //Net C flow to SOM1 carbonToSOM1 -= SOM1co2loss; if(this.Type == LayerType.Surface) { if (carbonToSOM1 > this.Carbon) { string mesg = string.Format("Error: Carbon transfer SOM1surface->SOM1 exceeds C flow. Source={0}, C-transfer={1}, C={2}", this.Name, carbonToSOM1, this.Carbon); throw new ApplicationException(mesg); } this.TransferCarbon(SiteVars.SOM1surface[site], carbonToSOM1); this.TransferNitrogen(SiteVars.SOM1surface[site], carbonToSOM1, litterC, ratioCN, site); } else { if (carbonToSOM1 > this.Carbon) { string mesg = string.Format("Error: Carbon transfer SOM1soil->SOM1 exceeds C flow. Source={0}, C-transfer={1}, C={2}", this.Name, carbonToSOM1, this.Carbon); throw new ApplicationException(mesg); } this.TransferCarbon(SiteVars.SOM1soil[site], carbonToSOM1); this.TransferNitrogen(SiteVars.SOM1soil[site], carbonToSOM1, litterC, ratioCN, site); } } //PlugIn.ModelCore.UI.WriteLine("Decompose2. MineralN={0:0.00}.", SiteVars.MineralN[site]); return; } //--------------------------------------------------------------------- public void DecomposeMetabolic(ActiveSite site) { double litterC = this.Carbon; double anerb = SiteVars.AnaerobicEffect[site]; if (litterC > 0.0000001) { // Determine C/N ratios for flows to SOM1 double ratioCNtoSOM1 = 0.0; double co2loss = 0.0; // Compute ratios for surface metabolic residue if (this.Type == LayerType.Surface) ratioCNtoSOM1 = Layer.AbovegroundDecompositionRatio(this.Nitrogen, litterC); //Compute ratios for soil metabolic residue else ratioCNtoSOM1 = Layer.BelowgroundDecompositionRatio(site, OtherData.MinCNenterSOM1, OtherData.MaxCNenterSOM1, OtherData.MinContentN_SOM1); //Compute total C flow out of metabolic layer double totalCFlow = litterC * SiteVars.DecayFactor[site] * OtherData.LitterParameters[(int) this.Type].DecayRateMetabolicC * OtherData.MonthAdjust; //PlugIn.ModelCore.UI.WriteLine("DecomposeMeta1. MineralN={0:0.00}.", SiteVars.MineralN[site]); //Added impact of soil anerobic conditions if (this.Type == LayerType.Soil) totalCFlow *= anerb; //Make sure metabolic C does not go negative. if (totalCFlow > litterC) totalCFlow = litterC; //If decomposition can occur, if(this.DecomposePossible(ratioCNtoSOM1, SiteVars.MineralN[site])) { //CO2 loss if (this.Type == LayerType.Surface) { co2loss = totalCFlow * OtherData.MetabolicToCO2Surface; //this.Respiration(co2loss, site, true); } else { co2loss = totalCFlow * OtherData.MetabolicToCO2Soil; //this.Respiration(co2loss, site, false); } this.Respiration(co2loss, site, false); //SURFACE DECAY ALSO COUNTED AS SOIL RESPIRATION (Shih-Chieh Chang) //PlugIn.ModelCore.UI.WriteLine("BeforeResp. MineralN={0:0.00}.", SiteVars.MineralN[site]); //PlugIn.ModelCore.UI.WriteLine("AfterResp. MineralN={0:0.00}.", SiteVars.MineralN[site]); //Decompose metabolic into som1 double netCFlow = totalCFlow - co2loss; if (netCFlow > litterC) PlugIn.ModelCore.UI.WriteLine(" ERROR: Decompose Metabolic: netCFlow={0:0.000} > layer.Carbon={0:0.000}.", netCFlow, this.Carbon); // -- CARBON AND NITROGEN --------------------------- // Partition and schedule C flows // Compute and schedule N flows and update mineralization accumulators. if((int) this.Type == (int) LayerType.Surface) { this.TransferCarbon(SiteVars.SOM1surface[site], netCFlow); this.TransferNitrogen(SiteVars.SOM1surface[site], netCFlow, litterC, ratioCNtoSOM1, site); //PlugIn.ModelCore.UI.WriteLine("DecomposeMetabolic. MineralN={0:0.00}.", SiteVars.MineralN[site]); } else { this.TransferCarbon(SiteVars.SOM1soil[site], netCFlow); this.TransferNitrogen(SiteVars.SOM1soil[site], netCFlow, litterC, ratioCNtoSOM1, site); } } } //} } //--------------------------------------------------------------------- public void TransferCarbon(Layer destination, double netCFlow) { if (netCFlow < 0) { //PlugIn.ModelCore.UI.WriteLine("NEGATIVE C FLOW! Source: {0},{1}; Destination: {2},{3}.", this.Name, this.Type, destination.Name, destination.Type); } if (netCFlow > this.Carbon) netCFlow = this.Carbon; //round these to avoid unexpected behavior this.Carbon = this.Carbon - netCFlow; // Math.Round((this.Carbon - netCFlow),2); destination.Carbon = destination.Carbon + netCFlow; // Math.Round((destination.Carbon + netCFlow),2); } public void TransferNitrogen(Layer destination, double CFlow, double totalC, double ratioCNtoDestination, ActiveSite site) { // this is the source. double mineralNFlow = 0.0; //...N flow is proportional to C flow. double NFlow = this.Nitrogen * CFlow / totalC; //...This was added to avoid a 0/0 error on the pc. if (CFlow <= 0.0 || NFlow <= 0.0) { return; } if ((NFlow - this.Nitrogen) > 0.01) { //PlugIn.ModelCore.UI.WriteLine(" Transfer N: N flow > source N."); //PlugIn.ModelCore.UI.WriteLine(" NFlow={0:0.000}, SourceN={1:0.000}", NFlow, this.Nitrogen); //PlugIn.ModelCore.UI.WriteLine(" CFlow={0:0.000}, totalC={1:0.000}", CFlow, totalC); //PlugIn.ModelCore.UI.WriteLine(" this.Name={0}, this.Type={1}", this.Name, this.Type); //PlugIn.ModelCore.UI.WriteLine(" dest.Name ={0}, dest.Type ={1}", destination.Name, destination.Type); //PlugIn.ModelCore.UI.WriteLine(" ratio CN to dest={0}", ratioCNtoDestination); } //...If C/N of Box A > C/N of new material entering Box B if ((CFlow / NFlow) > ratioCNtoDestination) { //...IMMOBILIZATION occurs. //...Compute the amount of N immobilized. // since ratioCNtoDestination = netCFlow / (Nflow + immobileN), // where immobileN is the extra N needed from the mineral pool double immobileN = (CFlow / ratioCNtoDestination) - NFlow; //PlugIn.ModelCore.UI.WriteLine(" CFlow={0:0.000}, totalC={1:0.000}", CFlow, totalC); // PlugIn.ModelCore.UI.WriteLine(" this.Name={0}, this.Type={1}", this.Name, this.Type); //PlugIn.ModelCore.UI.WriteLine(" NFlow={0:0.000}, SourceN={1:0.000},CNdestination={2:0}", NFlow, this.Nitrogen,ratioCNtoDestination); //PlugIn.ModelCore.UI.WriteLine("CalculatingImmobil. MineralN={0:0.00}.", SiteVars.MineralN[site]); //...Schedule flow from Box A to Box B (outofa) //flow(anps,bnps,time,outofa); this.Nitrogen -= NFlow; destination.Nitrogen += NFlow; //PlugIn.ModelCore.UI.WriteLine("NFlow. MineralN={0:0.00}, ImmobileN={1:0.000}.", SiteVars.MineralN[site],immobileN); // Schedule flow from mineral pool to Box B (immobileN) // flow(labile,bnps,time,immflo); //Don't allow mineral N to go to zero or negative.- ML if (immobileN > SiteVars.MineralN[site]) immobileN = SiteVars.MineralN[site] - 0.01; //leave some small amount of mineral N SiteVars.MineralN[site] -= immobileN; //PlugIn.ModelCore.UI.WriteLine("AfterImmobil. MineralN={0:0.00}.", SiteVars.MineralN[site]); destination.Nitrogen += immobileN; //PlugIn.ModelCore.UI.WriteLine("AdjustImmobil. MineralN={0:0.00}.", SiteVars.MineralN[site]); //PlugIn.ModelCore.UI.WriteLine(" TransferN immobileN={0:0.000}, C={1:0.000}, N={2:0.000}, ratioCN={3:0.000}.", immobileN, CFlow, NFlow, ratioCNtoDestination); //PlugIn.ModelCore.UI.WriteLine(" source={0}-{1}, destination={2}-{3}.", this.Name, this.Type, destination.Name, destination.Type); //...Return mineralization value. mineralNFlow = -1 * immobileN; //PlugIn.ModelCore.UI.WriteLine("MineralNflow. MineralN={0:0.00}.", SiteVars.MineralN[site]); } else //...MINERALIZATION occurs //...Schedule flow from Box A to Box B { //PlugIn.ModelCore.UI.WriteLine(" Transfer Nitrogen Min."); double mineralizedN = (CFlow / ratioCNtoDestination); this.Nitrogen -= mineralizedN; destination.Nitrogen += mineralizedN; //...Schedule flow from Box A to mineral pool mineralNFlow = NFlow - mineralizedN; if ((mineralNFlow - this.Nitrogen) > 0.01) { //PlugIn.ModelCore.UI.WriteLine(" Transfer N mineralization: mineralN > source N."); //PlugIn.ModelCore.UI.WriteLine(" MineralNFlow={0:0.000}, SourceN={1:0.000}", mineralNFlow, this.Nitrogen); //PlugIn.ModelCore.UI.WriteLine(" CFlow={0:0.000}, totalC={1:0.000}", CFlow, totalC); //PlugIn.ModelCore.UI.WriteLine(" this.Name={0}, this.Type={1}", this.Name, this.Type); // PlugIn.ModelCore.UI.WriteLine(" dest.Name ={0}, dest.Type ={1}", destination.Name, destination.Type); //PlugIn.ModelCore.UI.WriteLine(" ratio CN to dest={0}", ratioCNtoDestination); } this.Nitrogen -= mineralNFlow; SiteVars.MineralN[site] += mineralNFlow; //PlugIn.ModelCore.UI.WriteLine(" this.Name={0}, this.Type={1}", this.Name, this.Type); //PlugIn.ModelCore.UI.WriteLine("IfMinOccurs. MineralN={0:0.00}.", SiteVars.MineralN[site]); //PlugIn.ModelCore.UI.WriteLine(" TransferN NFlow={0:0.000}, mineralizedN = {1:0.000}, N mineralalization = {1:0.000}", NFlow, mineralizedN, mineralNFlow); //PlugIn.ModelCore.UI.WriteLine(" Source: this.Name={0}, this.Type={1}", this.Name, this.Type); } if (mineralNFlow > 0) SiteVars.GrossMineralization[site] += mineralNFlow; //...Net mineralization this.NetMineralization += mineralNFlow; //PlugIn.ModelCore.UI.WriteLine(" this.Nitrogen={0:0.000}.", this.Nitrogen); //PlugIn.ModelCore.UI.WriteLine("AfterMinOccurs. MineralN={0:0.00}.", SiteVars.MineralN[site]); return; } public void Respiration(double co2loss, ActiveSite site, bool surface) { // Compute flows associated with microbial respiration. // Input: // co2loss = CO2 loss associated with decomposition // Box A. For components with only 1 layer, tcstva will be dimensioned (1). // Transput: //c carbonSourceSink = C source/sink //c grossMineralization = gross mineralization //c netMineralization = net mineralization for layer N //c...Mineralization associated with respiration is proportional to the N fraction. double mineralNFlow = co2loss * this.Nitrogen / this.Carbon; if(mineralNFlow > this.Nitrogen) { //if((mineralNFlow - this.Nitrogen) > 0.01) //{ // PlugIn.ModelCore.UI.WriteLine("RESPIRATION for layer {0} {1}: Mineral N flow exceeds layer Nitrogen.", this.Name, this.Type); // PlugIn.ModelCore.UI.WriteLine(" MineralNFlow={0:0.000}, this.Nitrogen ={0:0.000}", mineralNFlow, this.Nitrogen); // PlugIn.ModelCore.UI.WriteLine(" CO2 loss={0:0.000}, this.Carbon={0:0.000}", co2loss, this.Carbon); // PlugIn.ModelCore.UI.WriteLine(" Site R/C: {0}/{1}.", site.Location.Row, site.Location.Column); //} mineralNFlow = this.Nitrogen; co2loss = this.Carbon; } this.TransferCarbon(SiteVars.SourceSink[site], co2loss); //Add lost CO2 to monthly heterotrophic respiration SiteVars.MonthlyHeteroResp[site][Main.Month] += co2loss; if(!surface) SiteVars.MonthlySoilResp[site][Main.Month] += co2loss; this.Nitrogen -= mineralNFlow; SiteVars.MineralN[site] += mineralNFlow; //PlugIn.ModelCore.UI.WriteLine(" Source: this.Name={0}, this.Type={1}", this.Name, this.Type); //PlugIn.ModelCore.UI.WriteLine(" Respiration.mineralN= {0:0.000}, co2loss={1:00}", mineralNFlow, co2loss); //c...Update gross mineralization // this.GrossMineralization += mineralNFlow; if (mineralNFlow > 0) SiteVars.GrossMineralization[site] += mineralNFlow; //c...Update net mineralization this.NetMineralization += mineralNFlow; return; } public bool DecomposePossible(double ratioCNnew, double mineralN) { //c...Determine if decomposition can occur. bool canDecompose = true; //c...If there is no available mineral N if (mineralN < 0.0000001) { // Compare the C/N of new material to the C/N of the layer if C/N of // the layer > C/N of new material if (this.Carbon / this.Nitrogen > ratioCNnew) { // Immobilization is necessary and the stuff in Box A can't // decompose to Box B. canDecompose = false; } } // If there is some available mineral N, decomposition can // proceed even if mineral N is driven negative in // the next time step. return canDecompose; } public void AdjustLignin(double inputC, double inputFracLignin) { //c...Adjust the fraction of lignin in structural C when new material //c... is added. //c oldc = grams C in structural before new material is added //c frnew = fraction of lignin in new structural material //c addc = grams structural C being added //c fractl comes in as fraction of lignin in structural before new //c material is added; goes out as fraction of lignin in //c structural with old and new combined. //c...oldlig = grams of lignin in existing residue double oldlig = this.FractionLignin * this.Carbon;//totalC; //c...newlig = grams of lignin in new residue double newlig = inputFracLignin * inputC; //c...Compute lignin fraction in combined residue double newFraction = (oldlig + newlig) / (this.Carbon + inputC); this.FractionLignin = newFraction; return; } public void AdjustDecayRate(double inputC, double inputDecayRate) { //c...oldlig = grams of lignin in existing residue double oldDecayRate = this.DecayValue * this.Carbon; //c...newlig = grams of lignin in new residue double newDecayRate = inputDecayRate * inputC; //c...Compute decay rate in combined residue this.DecayValue = (oldDecayRate + newDecayRate) / (inputC + this.Carbon); return; } public static double BelowgroundDecompositionRatio(ActiveSite site, double minCNenter, double maxCNenter, double minContentN) { //Originally from bgdrat.f //BelowGround Decomposition RATio computation. double bgdrat = 0.0; //Determine ratio of C/N of new material entering 'Box B'. //Ratio depends on available N double mineralN = SiteVars.MineralN[site]; if (mineralN <= 0.0) bgdrat = maxCNenter; // Set ratio to maximum allowed (HIGHEST carbon, LOWEST nitrogen) else if (mineralN > minContentN) bgdrat = minCNenter; //Set ratio to minimum allowed else bgdrat = (1.0 - (mineralN / minContentN)) * (maxCNenter - minCNenter) + minCNenter; return bgdrat; } public static double AbovegroundDecompositionRatio(double abovegroundN, double abovegroundC) { //Originally from agdrat.f. double Ncontent, agdrat; double biomassConversion = 2.0; // cemicb = slope of the regression line for C/N of som1 double cemicb = (OtherData.MinCNSurfMicrobes - OtherData.MaxCNSurfMicrobes) / OtherData.MinNContentCNSurfMicrobes; //The C/E ratios for structural and wood can be computed once; //they then remain fixed throughout the run. The ratios for //metabolic and som1 may vary and must be recomputed each time step if ((abovegroundC * biomassConversion) <= 0.00000000001) Ncontent = 0.0; else Ncontent = abovegroundN / (abovegroundC * biomassConversion); //tca is multiplied by biomassConversion to give biomass if (Ncontent > OtherData.MinNContentCNSurfMicrobes) agdrat = OtherData.MinCNSurfMicrobes; else agdrat = OtherData.MaxCNSurfMicrobes + Ncontent * cemicb; return agdrat; } //--------------------------------------------------------------------- /// <summary> /// Reduces the pool's biomass by a specified percentage. /// </summary> public void ReduceMass(double percentageLost) { if (percentageLost < 0.0 || percentageLost > 1.0) throw new ArgumentException("Percentage must be between 0% and 100%"); this.Carbon = this.Carbon * (1.0 - percentageLost); this.Nitrogen = this.Nitrogen * (1.0 - percentageLost); return; } } }
// // DockItemTitleTab.cs // // Author: // Lluis Sanchez Gual <lluis@xamarin.com> // // Copyright (c) 2012 Xamarin Inc. (http://xamarin.com) // Copyright (C) 2007 Novell, Inc (http://www.novell.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 Gtk; using System; using System.Linq; using MonoDevelop.Components; using Mono.Unix; namespace Pinta.Docking { class DockItemTitleTab: Gtk.EventBox { bool active; Gtk.Widget page; ExtendedLabel labelWidget; int labelWidth; DockVisualStyle visualStyle; Gtk.Widget tabIcon; DockFrame frame; string label; ImageButton btnDock; ImageButton btnClose; DockItem item; bool allowPlaceholderDocking; bool mouseOver; static Gdk.Cursor fleurCursor = new Gdk.Cursor (Gdk.CursorType.Fleur); static Gdk.Pixbuf pixClose; static Gdk.Pixbuf pixAutoHide; static Gdk.Pixbuf pixDock; static double PixelScale = GtkWorkarounds.GetPixelScale (); const int TopPadding = 5; const int BottomPadding = 7; const int TopPaddingActive = 5; const int BottomPaddingActive = 7; const int LeftPadding = 11; const int RightPadding = 9; static DockItemTitleTab () { pixClose = GdkExtensions.FromResource ("pad-close-9.png"); pixAutoHide = GdkExtensions.FromResource ("pad-minimize-9.png"); pixDock = GdkExtensions.FromResource ("pad-dock-9.png"); } public DockItemTitleTab (DockItem item, DockFrame frame) { this.item = item; this.frame = frame; this.VisibleWindow = false; UpdateVisualStyle (); NoShowAll = true; Events |= Gdk.EventMask.EnterNotifyMask | Gdk.EventMask.LeaveNotifyMask | Gdk.EventMask.ButtonPressMask | Gdk.EventMask.ButtonReleaseMask | Gdk.EventMask.PointerMotionMask; KeyPressEvent += HeaderKeyPress; KeyReleaseEvent += HeaderKeyRelease; this.SubscribeLeaveEvent (OnLeave); } public DockVisualStyle VisualStyle { get { return visualStyle; } set { visualStyle = value; UpdateVisualStyle (); QueueDraw (); } } void UpdateVisualStyle () { if (labelWidget != null && label != null) { if (visualStyle.UppercaseTitles.Value) labelWidget.Text = label.ToUpper (); else labelWidget.Text = label; labelWidget.UseMarkup = true; if (visualStyle.ExpandedTabs.Value) labelWidget.Xalign = 0.5f; if (!(Parent is TabStrip.TabStripBox)) labelWidget.Xalign = 0; } if (tabIcon != null) tabIcon.Visible = visualStyle.ShowPadTitleIcon.Value; if (IsRealized) { if (labelWidget != null) labelWidget.ModifyFg (StateType.Normal, visualStyle.PadTitleLabelColor.Value); } var r = WidthRequest; WidthRequest = -1; labelWidth = SizeRequest ().Width + 1; WidthRequest = r; if (visualStyle != null) HeightRequest = visualStyle.PadTitleHeight != null ? (int)(visualStyle.PadTitleHeight.Value * PixelScale) : -1; } public void SetLabel (Gtk.Widget page, Gdk.Pixbuf icon, string label) { this.label = label; this.page = page; if (Child != null) { Gtk.Widget oc = Child; Remove (oc); oc.Destroy (); } Gtk.HBox box = new HBox (); box.Spacing = 2; if (icon != null) { tabIcon = new ImageView (icon); tabIcon.Show (); box.PackStart (tabIcon, false, false, 0); } else tabIcon = null; if (!string.IsNullOrEmpty (label)) { labelWidget = new ExtendedLabel (label); labelWidget.DropShadowVisible = true; labelWidget.UseMarkup = true; box.PackStart (labelWidget, true, true, 0); } else { labelWidget = null; } btnDock = new ImageButton (); btnDock.Image = pixAutoHide; btnDock.InactiveImage = pixAutoHide.WithAlpha (.5); btnDock.TooltipText = Catalog.GetString ("Auto Hide"); btnDock.CanFocus = false; // btnDock.WidthRequest = btnDock.HeightRequest = 17; btnDock.Clicked += OnClickDock; btnDock.ButtonPressEvent += (o, args) => args.RetVal = true; btnDock.WidthRequest = btnDock.SizeRequest ().Width; btnClose = new ImageButton (); btnClose.Image = pixClose; btnClose.InactiveImage = pixClose.WithAlpha (.5); btnClose.TooltipText = Catalog.GetString ("Close"); btnClose.CanFocus = false; // btnClose.WidthRequest = btnClose.HeightRequest = 17; btnClose.WidthRequest = btnDock.SizeRequest ().Width; btnClose.Clicked += delegate { item.Visible = false; }; btnClose.ButtonPressEvent += (o, args) => args.RetVal = true; Gtk.Alignment al = new Alignment (0, 0, 1, 1); HBox btnBox = new HBox (false, 3); btnBox.PackStart (btnDock, false, false, 0); btnBox.PackStart (btnClose, false, false, 0); al.Add (btnBox); al.LeftPadding = 3; al.TopPadding = 1; box.PackEnd (al, false, false, 0); Add (box); // Get the required size before setting the ellipsize property, since ellipsized labels // have a width request of 0 box.ShowAll (); Show (); UpdateBehavior (); UpdateVisualStyle (); } void OnClickDock (object s, EventArgs a) { if (item.Status == DockItemStatus.AutoHide || item.Status == DockItemStatus.Floating) item.Status = DockItemStatus.Dockable; else item.Status = DockItemStatus.AutoHide; } public int LabelWidth { get { return labelWidth; } } public bool Active { get { return active; } set { if (active != value) { active = value; this.QueueResize (); QueueDraw (); UpdateBehavior (); } } } public Widget Page { get { return page; } } public void UpdateBehavior () { if (btnClose == null) return; btnClose.Visible = (item.Behavior & DockItemBehavior.CantClose) == 0; btnDock.Visible = (item.Behavior & DockItemBehavior.CantAutoHide) == 0; if (active || mouseOver) { if (btnClose.Image == null) btnClose.Image = pixClose; if (item.Status == DockItemStatus.AutoHide || item.Status == DockItemStatus.Floating) { btnDock.Image = pixDock; btnDock.InactiveImage = pixDock.WithAlpha (.5); btnDock.TooltipText = Catalog.GetString ("Dock"); } else { btnDock.Image = pixAutoHide; btnDock.InactiveImage = pixAutoHide.WithAlpha (.5); btnDock.TooltipText = Catalog.GetString ("Auto Hide"); } } else { btnDock.Image = null; btnClose.Image = null; } } bool tabPressed, tabActivated; double pressX, pressY; protected override bool OnButtonPressEvent (Gdk.EventButton evnt) { if (evnt.TriggersContextMenu ()) { item.ShowDockPopupMenu (evnt.Time); return false; } else if (evnt.Button == 1) { if (evnt.Type == Gdk.EventType.ButtonPress) { tabPressed = true; pressX = evnt.X; pressY = evnt.Y; } else if (evnt.Type == Gdk.EventType.TwoButtonPress) { tabActivated = true; } } return base.OnButtonPressEvent (evnt); } protected override bool OnButtonReleaseEvent (Gdk.EventButton evnt) { if (tabActivated) { tabActivated = false; if (!item.Behavior.HasFlag (DockItemBehavior.CantAutoHide)) { if (item.Status == DockItemStatus.AutoHide) item.Status = DockItemStatus.Dockable; else item.Status = DockItemStatus.AutoHide; } } else if (!evnt.TriggersContextMenu () && evnt.Button == 1) { frame.DockInPlaceholder (item); frame.HidePlaceholder (); if (GdkWindow != null) GdkWindow.Cursor = null; frame.Toplevel.KeyPressEvent -= HeaderKeyPress; frame.Toplevel.KeyReleaseEvent -= HeaderKeyRelease; } tabPressed = false; return base.OnButtonReleaseEvent (evnt); } protected override bool OnMotionNotifyEvent (Gdk.EventMotion evnt) { if (tabPressed && !item.Behavior.HasFlag (DockItemBehavior.NoGrip) && Math.Abs (evnt.X - pressX) > 3 && Math.Abs (evnt.Y - pressY) > 3) { frame.ShowPlaceholder (item); GdkWindow.Cursor = fleurCursor; frame.Toplevel.KeyPressEvent += HeaderKeyPress; frame.Toplevel.KeyReleaseEvent += HeaderKeyRelease; allowPlaceholderDocking = true; tabPressed = false; } frame.UpdatePlaceholder (item, Allocation.Size, allowPlaceholderDocking); return base.OnMotionNotifyEvent (evnt); } protected override bool OnEnterNotifyEvent (Gdk.EventCrossing evnt) { mouseOver = true; UpdateBehavior (); return base.OnEnterNotifyEvent (evnt); } void OnLeave () { mouseOver = false; UpdateBehavior (); } [GLib.ConnectBeforeAttribute] void HeaderKeyPress (object ob, Gtk.KeyPressEventArgs a) { if (a.Event.Key == Gdk.Key.Control_L || a.Event.Key == Gdk.Key.Control_R) { allowPlaceholderDocking = false; frame.UpdatePlaceholder (item, Allocation.Size, false); } if (a.Event.Key == Gdk.Key.Escape) { frame.HidePlaceholder (); frame.Toplevel.KeyPressEvent -= HeaderKeyPress; frame.Toplevel.KeyReleaseEvent -= HeaderKeyRelease; Gdk.Pointer.Ungrab (0); } } [GLib.ConnectBeforeAttribute] void HeaderKeyRelease (object ob, Gtk.KeyReleaseEventArgs a) { if (a.Event.Key == Gdk.Key.Control_L || a.Event.Key == Gdk.Key.Control_R) { allowPlaceholderDocking = true; frame.UpdatePlaceholder (item, Allocation.Size, true); } } protected override void OnRealized () { base.OnRealized (); UpdateVisualStyle (); } protected override void OnSizeRequested (ref Gtk.Requisition req) { if (Child != null) { req = Child.SizeRequest (); req.Width += LeftPadding + RightPadding; if (active) req.Height += TopPaddingActive + BottomPaddingActive; else req.Height += TopPadding + BottomPadding; } } protected override void OnSizeAllocated (Gdk.Rectangle rect) { base.OnSizeAllocated (rect); int leftPadding = LeftPadding; int rightPadding = RightPadding; if (rect.Width < labelWidth) { int red = (labelWidth - rect.Width) / 2; leftPadding -= red; rightPadding -= red; if (leftPadding < 2) leftPadding = 2; if (rightPadding < 2) rightPadding = 2; } rect.X += leftPadding; rect.Width -= leftPadding + rightPadding; if (Child != null) { if (active) { rect.Y += TopPaddingActive; rect.Height = Child.SizeRequest ().Height; } else { rect.Y += TopPadding; rect.Height = Child.SizeRequest ().Height; } Child.SizeAllocate (rect); } } protected override bool OnExposeEvent (Gdk.EventExpose evnt) { if (VisualStyle.TabStyle == DockTabStyle.Normal) DrawAsBrowser (evnt); else DrawNormal (evnt); return base.OnExposeEvent (evnt); } void DrawAsBrowser (Gdk.EventExpose evnt) { var alloc = Allocation; Gdk.GC bgc = new Gdk.GC (GdkWindow); var c = VisualStyle.PadBackgroundColor.Value.ToXwtColor (); c.Light *= 0.7; bgc.RgbFgColor = c.ToGdkColor (); bool first = true; bool last = true; TabStrip tabStrip = null; if (Parent is TabStrip.TabStripBox) { var tsb = (TabStrip.TabStripBox) Parent; var cts = tsb.Children; first = cts[0] == this; last = cts[cts.Length - 1] == this; tabStrip = tsb.TabStrip; } if (Active || (first && last)) { Gdk.GC gc = new Gdk.GC (GdkWindow); gc.RgbFgColor = VisualStyle.PadBackgroundColor.Value; evnt.Window.DrawRectangle (gc, true, alloc); if (!first) evnt.Window.DrawLine (bgc, alloc.X, alloc.Y, alloc.X, alloc.Y + alloc.Height - 1); if (!(last && first) && !(tabStrip != null && tabStrip.VisualStyle.ExpandedTabs.Value && last)) evnt.Window.DrawLine (bgc, alloc.X + alloc.Width - 1, alloc.Y, alloc.X + alloc.Width - 1, alloc.Y + alloc.Height - 1); gc.Dispose (); } else { Gdk.GC gc = new Gdk.GC (GdkWindow); gc.RgbFgColor = tabStrip != null ? tabStrip.VisualStyle.InactivePadBackgroundColor.Value : frame.DefaultVisualStyle.InactivePadBackgroundColor.Value; evnt.Window.DrawRectangle (gc, true, alloc); gc.Dispose (); evnt.Window.DrawLine (bgc, alloc.X, alloc.Y + alloc.Height - 1, alloc.X + alloc.Width - 1, alloc.Y + alloc.Height - 1); } bgc.Dispose (); } void DrawNormal (Gdk.EventExpose evnt) { using (var ctx = Gdk.CairoHelper.Create (GdkWindow)) { var x = Allocation.X; var y = Allocation.Y; ctx.Rectangle (x, y + 1, Allocation.Width, Allocation.Height - 1); using (var g = new Cairo.LinearGradient (x, y + 1, x, y + Allocation.Height - 1)) { g.AddColorStop (0, Styles.DockTabBarGradientStart); g.AddColorStop (1, Styles.DockTabBarGradientEnd); ctx.SetSource (g); ctx.Fill (); } ctx.MoveTo (x + 0.5, y + 0.5); ctx.LineTo (x + Allocation.Width - 0.5d, y + 0.5); ctx.SetSourceColor (Styles.DockTabBarGradientTop); ctx.Stroke (); if (active) { ctx.Rectangle (x, y + 1, Allocation.Width, Allocation.Height - 1); using (var g = new Cairo.LinearGradient (x, y + 1, x, y + Allocation.Height - 1)) { g.AddColorStop (0, new Cairo.Color (0, 0, 0, 0.01)); g.AddColorStop (0.5, new Cairo.Color (0, 0, 0, 0.08)); g.AddColorStop (1, new Cairo.Color (0, 0, 0, 0.01)); ctx.SetSource (g); ctx.Fill (); } /* double offset = Allocation.Height * 0.25; var rect = new Cairo.Rectangle (x - Allocation.Height + offset, y, Allocation.Height, Allocation.Height); var cg = new Cairo.RadialGradient (rect.X + rect.Width / 2, rect.Y + rect.Height / 2, 0, rect.X, rect.Y + rect.Height / 2, rect.Height / 2); cg.AddColorStop (0, Styles.DockTabBarShadowGradientStart); cg.AddColorStop (1, Styles.DockTabBarShadowGradientEnd); ctx.Pattern = cg; ctx.Rectangle (rect); ctx.Fill (); rect = new Cairo.Rectangle (x + Allocation.Width - offset, y, Allocation.Height, Allocation.Height); cg = new Cairo.RadialGradient (rect.X + rect.Width / 2, rect.Y + rect.Height / 2, 0, rect.X, rect.Y + rect.Height / 2, rect.Height / 2); cg.AddColorStop (0, Styles.DockTabBarShadowGradientStart); cg.AddColorStop (1, Styles.DockTabBarShadowGradientEnd); ctx.Pattern = cg; ctx.Rectangle (rect); ctx.Fill ();*/ } } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using NUnit.Framework; using QuantConnect.Data; using QuantConnect.Util; using QuantConnect.Algorithm; using System.Collections.Generic; using QuantConnect.Data.Auxiliary; using QuantConnect.Lean.Engine.DataFeeds; using QuantConnect.Data.UniverseSelection; using QuantConnect.Tests.Engine.DataFeeds; using QuantConnect.Data.Custom.AlphaStreams; using QuantConnect.Lean.Engine.HistoricalData; using QuantConnect.Algorithm.Framework.Alphas; using QuantConnect.Algorithm.Framework.Portfolio; namespace QuantConnect.Tests.Algorithm.Framework.Portfolio { [TestFixture] public class EqualWeightingAlphaStreamsPortfolioConstructionModelTests { private ZipDataCacheProvider _cacheProvider; private DefaultDataProvider _dataProvider; private QCAlgorithm _algorithm; [SetUp] public virtual void SetUp() { _algorithm = new QCAlgorithm(); _dataProvider = new DefaultDataProvider(); var mapFileProvider = new LocalDiskMapFileProvider(); mapFileProvider.Initialize(_dataProvider); var factorFileProvider = new LocalZipFactorFileProvider(); factorFileProvider.Initialize(mapFileProvider, _dataProvider); var historyProvider = new SubscriptionDataReaderHistoryProvider(); _cacheProvider = new ZipDataCacheProvider(_dataProvider); historyProvider.Initialize(new HistoryProviderInitializeParameters(null, null, _dataProvider, _cacheProvider, mapFileProvider, factorFileProvider, null, true, new DataPermissionManager())); _algorithm.SetHistoryProvider(historyProvider); _algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(_algorithm)); _algorithm.Settings.FreePortfolioValue = 0; _algorithm.SetFinishedWarmingUp(); } [TearDown] public virtual void TearDown() { _cacheProvider.DisposeSafely(); _dataProvider.DisposeSafely(); } [TestCase(Language.CSharp)] public void NoTargets(Language language) { SetPortfolioConstruction(language); var targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, Array.Empty<Insight>()).ToList(); Assert.AreEqual(0, targets.Count); } [TestCase(Language.CSharp)] public void IgnoresInsights(Language language) { SetPortfolioConstruction(language); var insight = Insight.Price(Symbols.AAPL, Resolution.Minute, 1, InsightDirection.Down, 1, 1, "AlphaId", 0.5); insight.GeneratedTimeUtc = _algorithm.UtcTime; insight.CloseTimeUtc = _algorithm.UtcTime.Add(insight.Period); var targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, new[] { insight }).ToList(); Assert.AreEqual(0, targets.Count); } [TestCase(Language.CSharp)] public void SingleAlphaSinglePosition(Language language) { SetPortfolioConstruction(language); var alpha = _algorithm.AddData<AlphaStreamsPortfolioState>("9fc8ef73792331b11dbd5429a").Symbol; var data = _algorithm.History<AlphaStreamsPortfolioState>(alpha, TimeSpan.FromDays(2)).Last(); AddSecurities(_algorithm, data); _algorithm.SetCurrentSlice(new Slice(_algorithm.UtcTime, new List<BaseData> { data })); var targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, Array.Empty<Insight>()).ToList(); Assert.AreEqual(1, targets.Count); var position = data.PositionGroups.Single().Positions.Single(); Assert.AreEqual(position.Symbol, targets.Single().Symbol); Assert.AreEqual(position.Quantity, targets.Single().Quantity); } [TestCase(Language.CSharp)] public void SingleAlphaMultiplePositions(Language language) { SetPortfolioConstruction(language); var alpha = _algorithm.AddData<AlphaStreamsPortfolioState>("9fc8ef73792331b11dbd5429a").Symbol; var data = _algorithm.History<AlphaStreamsPortfolioState>(alpha, TimeSpan.FromDays(1)).ToList()[0]; AddSecurities(_algorithm, data); _algorithm.SetCurrentSlice(new Slice(_algorithm.UtcTime, new List<BaseData> { data })); var targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, Array.Empty<Insight>()).ToList(); Assert.AreEqual(2, targets.Count); Assert.AreEqual(600, targets.Single(target => target.Symbol == Symbols.GOOG).Quantity); var option = Symbol.CreateOption(Symbols.GOOG, Market.USA, OptionStyle.American, OptionRight.Call, 750, new DateTime(2016, 6, 17)); Assert.AreEqual(-5, targets.Single(target => target.Symbol == option).Quantity); } [TestCase(Language.CSharp)] public void SingleAlphaPositionRemoval(Language language) { SetPortfolioConstruction(language); var alpha = _algorithm.AddData<AlphaStreamsPortfolioState>("9fc8ef73792331b11dbd5429a").Symbol; var data = _algorithm.History<AlphaStreamsPortfolioState>(alpha, TimeSpan.FromDays(2)).Last(); AddSecurities(_algorithm, data); var position = data.PositionGroups.Single().Positions.Single(); _algorithm.SetCurrentSlice(new Slice(_algorithm.UtcTime, new List<BaseData> { data })); var targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, Array.Empty<Insight>()).ToList(); Assert.AreEqual(1, targets.Count); Assert.AreEqual(position.Symbol, targets.Single().Symbol); Assert.AreEqual(position.Quantity, targets.Single().Quantity); _algorithm.SetCurrentSlice(new Slice(_algorithm.UtcTime, new List<BaseData> { new AlphaStreamsPortfolioState { Symbol = alpha } })); targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, Array.Empty<Insight>()).ToList(); Assert.AreEqual(1, targets.Count); Assert.AreEqual(position.Symbol, targets.Single().Symbol); Assert.AreEqual(0, targets.Single().Quantity); // no new targets targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, Array.Empty<Insight>()).ToList(); Assert.AreEqual(0, targets.Count); } [TestCase(Language.CSharp, 1000000, 10000, 0)] [TestCase(Language.CSharp, 10000, 1000000, 0)] [TestCase(Language.CSharp, 10000, 10000, 0)] [TestCase(Language.CSharp, 100000, 100000, 0)] [TestCase(Language.CSharp, 1000000, 1000000, 0)] [TestCase(Language.CSharp, 1000000, 10000, 5000)] [TestCase(Language.CSharp, 10000, 1000000, 5000)] [TestCase(Language.CSharp, 10000, 10000, 5000)] [TestCase(Language.CSharp, 100000, 100000, 5000)] [TestCase(Language.CSharp, 1000000, 1000000, 5000)] public void MultipleAlphaPositionAggregation(Language language, decimal totalPortfolioValueAlpha1, decimal totalPortfolioValueAlpha2, decimal freePortfolioValue) { SetPortfolioConstruction(language); _algorithm.Settings.FreePortfolioValue = freePortfolioValue; var alpha1 = _algorithm.AddData<AlphaStreamsPortfolioState>("9fc8ef73792331b11dbd5429a"); var alpha2 = _algorithm.AddData<AlphaStreamsPortfolioState>("623b06b231eb1cc1aa3643a46"); _algorithm.OnFrameworkSecuritiesChanged(SecurityChanges.Added(alpha1, alpha2)); var symbol = alpha1.Symbol; var symbol2 = alpha2.Symbol; var data = _algorithm.History<AlphaStreamsPortfolioState>(symbol, TimeSpan.FromDays(1)).Last(); AddSecurities(_algorithm, data); data.TotalPortfolioValue = totalPortfolioValueAlpha1; var position = data.PositionGroups.Single().Positions.Single(); var data2 = (AlphaStreamsPortfolioState)data.Clone(); data2.Symbol = symbol2; data2.TotalPortfolioValue = totalPortfolioValueAlpha2; data2.PositionGroups = new List<PositionGroupState> { new PositionGroupState { Positions = new List<PositionState> { new PositionState { Quantity = position.Quantity * -10, Symbol = position.Symbol, UnitQuantity = 1 } }} }; _algorithm.SetCurrentSlice(new Slice(_algorithm.UtcTime, new List<BaseData> { data, data2 })); var targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, Array.Empty<Insight>()).ToList(); Assert.AreEqual(1, targets.Count); Assert.AreEqual(position.Symbol, targets.Single().Symbol); var tvpPerAlpha = (_algorithm.Portfolio.TotalPortfolioValue - freePortfolioValue) * 0.5m; var alpha1Weight = tvpPerAlpha / data.TotalPortfolioValue; var alpha2Weight = tvpPerAlpha / data2.TotalPortfolioValue; Assert.AreEqual((position.Quantity * alpha1Weight).DiscretelyRoundBy(1, MidpointRounding.ToZero) + (position.Quantity * -10m * alpha2Weight).DiscretelyRoundBy(1, MidpointRounding.ToZero), targets.Single().Quantity); } private void AddSecurities(QCAlgorithm algorithm, AlphaStreamsPortfolioState portfolioState) { foreach (var symbol in portfolioState.PositionGroups?.SelectMany(positionGroup => positionGroup.Positions) .Select(state => state.Symbol) ?? Enumerable.Empty<Symbol>()) { _algorithm.AddSecurity(symbol); } } private void SetUtcTime(DateTime dateTime) => _algorithm.SetDateTime(dateTime.ConvertToUtc(_algorithm.TimeZone)); private void SetPortfolioConstruction(Language language) { _algorithm.SetCurrentSlice(null); IPortfolioConstructionModel model; if (language == Language.CSharp) { model = new EqualWeightingAlphaStreamsPortfolioConstructionModel(); } else { throw new NotImplementedException($"{language} not implemented"); } _algorithm.SetPortfolioConstruction(model); foreach (var kvp in _algorithm.Portfolio) { kvp.Value.SetHoldings(kvp.Value.Price, 0); } _algorithm.Portfolio.SetCash(100000); SetUtcTime(new DateTime(2018, 4, 5)); var changes = SecurityChanges.Added(_algorithm.Securities.Values.ToArray()); _algorithm.PortfolioConstruction.OnSecuritiesChanged(_algorithm, changes); } } }
#region License //----------------------------------------------------------------------- // <copyright> // The MIT License (MIT) // // Copyright (c) 2014 Kirk S Woll // // 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> //----------------------------------------------------------------------- #endregion using System.Reflection; namespace System.Runtime.WootzJs { /// <summary> /// This class contains a suite of methods that are handled specially by the compiler to allow /// you to express Javascript constructs that would either be impossible or more verbose to /// express in plain C#. /// </summary> [Js(Export = false)] public static class Jsni { /// <summary> /// This allows you to create a Javascript regular expression literal. The result of invoking /// this method will be the javascript `/pattern` (or `/pattern/suffix`). /// </summary> public static extern JsRegExp regex(string pattern, string suffix = null); /// <summary> /// Normally when you `new` a class in C#, it will go through several hops, assuming it to be /// a C# class with a constructor. Using `Jsni.new` you can simply generate Javascript that /// will apply the `new` operator to any 'ol expression. The result of /// `Jsni.new(Jsni.reference("Date"))` would be `new Date()`. /// </summary> public static extern JsObject @new(JsObject target, params JsObject[] arguments); /// <summary> /// Returns the special `arguments` "array" that represents the arguments passed to the /// current function. /// </summary> public static extern JsObject arguments(); /// <summary> /// Usually compiles to the same output as `this`. However, for scenarios where there is /// no `this` in the current scope (i.e. static methods) you can use `Jsni.@this()` to /// represent `this` regardless. /// </summary> public static extern JsObject @this(); public static extern JsObject apply(this JsObject target, JsObject thisReference, JsArray arguments); public static extern JsObject call(this JsObject target, JsObject thisReference, params JsObject[] arguments); public static extern JsObject apply<T>(Action<T> method, JsObject thisReference, JsArray arguments); public static extern JsObject call<T>(Action<T> method, JsObject thisReference, params JsObject[] arguments); /// <summary> /// Deletes a property from a Javascript object. Compiles to the Javascript `delete` expression. /// `Jsni.delete(o.foo)` is compiled to `delete o.foo`. It is imperative that the expression /// passed to this method represents a member reference expression (since the `delete` keyword /// makes the same restriction -- it's how it identifies both the property to delete and its /// containing object.) /// </summary> /// <param name="o"></param> public static extern void delete(JsObject o); public static extern JsFunction procedure(Action a); public static extern JsFunction procedure(Action<JsObject> a, string nameOverride1 = null); public static extern JsFunction procedure(Action<JsObject, JsObject> a, string nameOverride1 = null, string nameOverride2 = null); public static extern JsFunction procedure(Action<JsObject, JsObject, JsObject> a, string nameOverride1 = null, string nameOverride2 = null, string nameOverride3 = null); public static extern JsFunction procedure(Action<JsObject, JsObject, JsObject, JsObject> a, string nameOverride1 = null, string nameOverride2 = null, string nameOverride3 = null, string nameOverride4 = null); public static extern JsFunction procedure(Action<JsObject, JsObject, JsObject, JsObject, JsObject> a, string nameOverride1 = null, string nameOverride2 = null, string nameOverride3 = null, string nameOverride4 = null, string nameOverride5 = null); public static extern JsFunction procedure(Action<JsObject, JsObject, JsObject, JsObject, JsObject, JsObject> a, string nameOverride1 = null, string nameOverride2 = null, string nameOverride3 = null, string nameOverride4 = null, string nameOverride5 = null, string nameOverride6 = null); public static extern JsFunction procedure(Action<JsObject, JsObject, JsObject, JsObject, JsObject, JsObject, JsObject> a, string nameOverride1 = null, string nameOverride2 = null, string nameOverride3 = null, string nameOverride4 = null, string nameOverride5 = null, string nameOverride6 = null, string nameOverride7 = null); public static extern JsFunction procedure(Action<JsObject, JsObject, JsObject, JsObject, JsObject, JsObject, JsObject, JsObject> a, string nameOverride1 = null, string nameOverride2 = null, string nameOverride3 = null, string nameOverride4 = null, string nameOverride5 = null, string nameOverride6 = null, string nameOverride7 = null, string nameOverride8 = null); public static extern JsFunction function(Func<JsObject> a); public static extern JsFunction function(Func<JsObject, JsObject> a, string nameOverride1 = null); public static extern JsFunction function(Func<JsObject, JsObject, JsObject> a, string nameOverride1 = null, string nameOverride2 = null); public static extern JsFunction function(Func<JsObject, JsObject, JsObject, JsObject> a, string nameOverride1 = null, string nameOverride2 = null, string nameOverride3 = null); public static extern JsFunction function(Func<JsObject, JsObject, JsObject, JsObject, JsObject> a, string nameOverride1 = null, string nameOverride2 = null, string nameOverride3 = null, string nameOverride4 = null); public static extern JsFunction function(Func<JsObject, JsObject, JsObject, JsObject, JsObject, JsObject> a, string nameOverride1 = null, string nameOverride2 = null, string nameOverride3 = null, string nameOverride4 = null, string nameOverride5 = null); public static extern JsFunction function(Func<JsObject, JsObject, JsObject, JsObject, JsObject, JsObject, JsObject> a, string nameOverride1 = null, string nameOverride2 = null, string nameOverride3 = null, string nameOverride4 = null, string nameOverride5 = null, string nameOverride6 = null); public static extern JsFunction function(Func<JsObject, JsObject, JsObject, JsObject, JsObject, JsObject, JsObject, JsObject> a, string nameOverride1 = null, string nameOverride2 = null, string nameOverride3 = null, string nameOverride4 = null, string nameOverride5 = null, string nameOverride6 = null, string nameOverride7 = null); public static extern JsFunction function(Func<JsObject, JsObject, JsObject, JsObject, JsObject, JsObject, JsObject, JsObject, JsObject> a, string nameOverride1 = null, string nameOverride2 = null, string nameOverride3 = null, string nameOverride4 = null, string nameOverride5 = null, string nameOverride6 = null, string nameOverride7 = null, string nameOverride8 = null); public static extern JsString _typeof(JsObject o); public static extern JsObject member(this JsObject target, string name); public static extern JsObject memberset(this JsObject target, string name, JsObject value); /// <summary> /// Represents Javascript array-literal syntax. For example: /// /// var array = Jsni.Array(new[] { 1, 2, 3, 4 }); /// /// Will get compiled to: /// /// var array = [1, 2, 3, 4]; /// /// Normally array creation will pass through some helper functions to ensure that it /// retains C# type information. /// </summary> /// <param name="elements">The elements of the array</param> /// <returns>The newly created Javascript array literal</returns> public static extern JsArray array(params JsObject[] elements); public static extern JsObject invoke(this JsObject target, params JsObject[] arguments); // ReSharper disable once UnusedTypeParameter public static extern JsTypeFunction type<T>(); public static extern JsTypeFunction type(Type type); /// <summary> /// Used to reference any arbitary Javascript identifier. The specified identifier /// is compiled directly into Javascript as an identifier. The specified string /// MUST be a C# string-literal as the reference must be determined at compile-time. /// </summary> /// <param name="identifier"></param> /// <returns></returns> public static extern JsObject reference(string identifier); /// <summary> /// Standin for the parseInt() global Javascript function. /// </summary> /// <param name="s"></param> /// <param name="radix"></param> /// <returns></returns> public static extern JsNumber parseInt(string s, int radix = 0); /// <summary> /// Standin for the parseFloat() global Javascript function. /// </summary> /// <param name="s"></param> /// <param name="radix"></param> /// <returns></returns> public static extern JsNumber parseFloat(string s, int radix = 0); /// <summary> /// Standin for the isNaN() global Javascript function. /// </summary> /// <param name="number">The number to test whether it's a number</param> /// <returns>True if the specified number is not a number.</returns> public static extern bool isNaN(JsNumber number); /// <summary> /// Allows you to represent a Javascript `instanceof` expression in C#. /// /// Jsni.instanceOf(foo, Foo) /// /// is compiled to: /// /// foo instanceof Foo /// </summary> /// <param name="expression"></param> /// <param name="type"></param> /// <returns></returns> public static extern bool instanceof(JsObject expression, JsObject type); /// <summary> /// Used to create raw Javascript objects. The parameter `o` *must* be a literal /// anonymous type expression (as opposed to either a reference to an existing one, or /// some other object.) /// /// For example, if you call: /// var o = Jsni.object(new { Foo = "bar" }); /// /// The generated Javascript will be: /// var o = { Foo: "bar" }; /// /// This is in contrast to how this would be compiled without the `Jsni.object` wrapper. /// In that (normal) scenario, the anonymous type would be treated as a C# anonymous /// type, which means getters, setters, etc. will be generated for the type. /// /// Using this method can be helpful when interoperating with other Javascript libraries /// that expect ordinary Javascript objects. /// </summary> /// <param name="o">An anonymous type expression that represents the Javascript object /// literal you want to be output.</param> /// <param name="compact">Whether you want the Javascript output to be minified into a /// single line. This can be convenient when you don't want the generated object to /// distract readers of your Javascript from the surrounding code.</param> /// <returns>A JsObject that represents the newly created object.</returns> public static extern JsObject @object(object o, bool compact = false); public static extern string encodeURIComponent(string s); public static extern string decodeURIComponent(string s); // todo: Move this to Window object in WootzJs.Mvc public static extern JsObject getComputedStyle(JsObject element); public static extern void forin(this JsObject obj, Action<JsObject> iteration); public static extern bool @in(this string property, object obj); public static extern JsObject setTimeout(Action callback, int timeout); public static extern JsObject setInterval(Action callback, int interval); public static extern void clearTimeout(JsObject token); public static extern void clearInterval(JsObject token); /// <summary> /// Allows you to inject raw Javascript code at the callsite. /// </summary> /// <param name="code">Raw Javascript code that will be injected in-place. This string MUST be a string literal. One can't statically generate code with an arbitrary value for the injected code.</param> /// <returns>Whatever the raw code returns. The code may return nothing, in which case the Javascript result would be undefined.</returns> public static extern JsObject code(string code); } }
// 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.ServiceModel.Security { using System; using System.ServiceModel; using System.ServiceModel.Description; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using System.Threading; using Microsoft.Xml; using System.IdentityModel.Claims; using System.IdentityModel.Policy; using System.IdentityModel.Tokens; using System.Security.Cryptography.X509Certificates; using System.ServiceModel.Security.Tokens; using System.ServiceModel.Channels; using System.ServiceModel.Security; using System.Runtime.Serialization; using System.ServiceModel.Dispatcher; using KeyIdentifierEntry = WSSecurityTokenSerializer.KeyIdentifierEntry; using KeyIdentifierClauseEntry = WSSecurityTokenSerializer.KeyIdentifierClauseEntry; using TokenEntry = WSSecurityTokenSerializer.TokenEntry; using StrEntry = WSSecurityTokenSerializer.StrEntry; internal class WSTrustFeb2005 : WSTrust { public WSTrustFeb2005(WSSecurityTokenSerializer tokenSerializer) : base(tokenSerializer) { } public override TrustDictionary SerializerDictionary { get { return XD.TrustFeb2005Dictionary; } } public class DriverFeb2005 : Driver { public DriverFeb2005(SecurityStandardsManager standardsManager) : base(standardsManager) { } public override TrustDictionary DriverDictionary { get { return XD.TrustFeb2005Dictionary; } } public override XmlDictionaryString RequestSecurityTokenResponseFinalAction { get { return XD.TrustFeb2005Dictionary.RequestSecurityTokenIssuanceResponse; } } public override bool IsSessionSupported { get { return true; } } public override bool IsIssuedTokensSupported { get { return true; } } public override string IssuedTokensHeaderName { get { return this.DriverDictionary.IssuedTokensHeader.Value; } } public override string IssuedTokensHeaderNamespace { get { return this.DriverDictionary.Namespace.Value; } } public override string RequestTypeRenew { get { return this.DriverDictionary.RequestTypeRenew.Value; } } public override string RequestTypeClose { get { return this.DriverDictionary.RequestTypeClose.Value; } } public override Collection<XmlElement> ProcessUnknownRequestParameters(Collection<XmlElement> unknownRequestParameters, Collection<XmlElement> originalRequestParameters) { return unknownRequestParameters; } protected override void ReadReferences(XmlElement rstrXml, out SecurityKeyIdentifierClause requestedAttachedReference, out SecurityKeyIdentifierClause requestedUnattachedReference) { throw new NotImplementedException(); } protected override bool ReadRequestedTokenClosed(XmlElement rstrXml) { for (int i = 0; i < rstrXml.ChildNodes.Count; ++i) { XmlElement child = (rstrXml.ChildNodes[i] as XmlElement); if (child != null) { if (child.LocalName == this.DriverDictionary.RequestedTokenClosed.Value && child.NamespaceURI == this.DriverDictionary.Namespace.Value) { return true; } } } return false; } protected override void ReadTargets(XmlElement rstXml, out SecurityKeyIdentifierClause renewTarget, out SecurityKeyIdentifierClause closeTarget) { renewTarget = null; closeTarget = null; for (int i = 0; i < rstXml.ChildNodes.Count; ++i) { XmlElement child = (rstXml.ChildNodes[i] as XmlElement); if (child != null) { if (child.LocalName == this.DriverDictionary.RenewTarget.Value && child.NamespaceURI == this.DriverDictionary.Namespace.Value) renewTarget = this.StandardsManager.SecurityTokenSerializer.ReadKeyIdentifierClause(new XmlNodeReader(child.FirstChild)); else if (child.LocalName == this.DriverDictionary.CloseTarget.Value && child.NamespaceURI == this.DriverDictionary.Namespace.Value) closeTarget = this.StandardsManager.SecurityTokenSerializer.ReadKeyIdentifierClause(new XmlNodeReader(child.FirstChild)); } } } protected override void WriteReferences(RequestSecurityTokenResponse rstr, XmlDictionaryWriter writer) { if (rstr.RequestedAttachedReference != null) { writer.WriteStartElement(this.DriverDictionary.Prefix.Value, this.DriverDictionary.RequestedAttachedReference, this.DriverDictionary.Namespace); this.StandardsManager.SecurityTokenSerializer.WriteKeyIdentifierClause(writer, rstr.RequestedAttachedReference); writer.WriteEndElement(); } if (rstr.RequestedUnattachedReference != null) { writer.WriteStartElement(this.DriverDictionary.Prefix.Value, this.DriverDictionary.RequestedUnattachedReference, this.DriverDictionary.Namespace); this.StandardsManager.SecurityTokenSerializer.WriteKeyIdentifierClause(writer, rstr.RequestedUnattachedReference); writer.WriteEndElement(); } } protected override void WriteRequestedTokenClosed(RequestSecurityTokenResponse rstr, XmlDictionaryWriter writer) { if (rstr.IsRequestedTokenClosed) { writer.WriteElementString(this.DriverDictionary.RequestedTokenClosed, this.DriverDictionary.Namespace, String.Empty); } } protected override void WriteTargets(RequestSecurityToken rst, XmlDictionaryWriter writer) { if (rst.RenewTarget != null) { writer.WriteStartElement(this.DriverDictionary.Prefix.Value, this.DriverDictionary.RenewTarget, this.DriverDictionary.Namespace); this.StandardsManager.SecurityTokenSerializer.WriteKeyIdentifierClause(writer, rst.RenewTarget); writer.WriteEndElement(); } if (rst.CloseTarget != null) { writer.WriteStartElement(this.DriverDictionary.Prefix.Value, this.DriverDictionary.CloseTarget, this.DriverDictionary.Namespace); this.StandardsManager.SecurityTokenSerializer.WriteKeyIdentifierClause(writer, rst.CloseTarget); writer.WriteEndElement(); } } // this is now the abstract in WSTrust public override IChannelFactory<IRequestChannel> CreateFederationProxy(EndpointAddress address, Binding binding, KeyedByTypeCollection<IEndpointBehavior> channelBehaviors) { if (channelBehaviors == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channelBehaviors"); ChannelFactory<IWsTrustFeb2005SecurityTokenService> result = new ChannelFactory<IWsTrustFeb2005SecurityTokenService>(binding, address); SetProtectionLevelForFederation(result.Endpoint.Contract.Operations); // remove the default client credentials that gets added to channel factories result.Endpoint.Behaviors.Remove<ClientCredentials>(); for (int i = 0; i < channelBehaviors.Count; ++i) { result.Endpoint.Behaviors.Add(channelBehaviors[i]); } // add a behavior that removes the UI channel initializer added by the client credentials since there should be no UI // initializer popped up as part of obtaining the federation token (the UI should already have been popped up for the main channel) result.Endpoint.Behaviors.Add(new InteractiveInitializersRemovingBehavior()); return new RequestChannelFactory<IWsTrustFeb2005SecurityTokenService>(result); } [ServiceContract] internal interface IWsTrustFeb2005SecurityTokenService { [OperationContract(IsOneWay = false, Action = TrustFeb2005Strings.RequestSecurityTokenIssuance, ReplyAction = TrustFeb2005Strings.RequestSecurityTokenIssuanceResponse)] [FaultContract(typeof(string), Action = "*", ProtectionLevel = System.Net.Security.ProtectionLevel.Sign)] Message RequestToken(Message message); } public class InteractiveInitializersRemovingBehavior : IEndpointBehavior { public void Validate(ServiceEndpoint serviceEndpoint) { } public void AddBindingParameters(ServiceEndpoint serviceEndpoint, BindingParameterCollection bindingParameters) { } public void ApplyDispatchBehavior(ServiceEndpoint serviceEndpoint, EndpointDispatcher endpointDispatcher) { } public void ApplyClientBehavior(ServiceEndpoint serviceEndpoint, ClientRuntime behavior) { // it is very unlikely that InteractiveChannelInitializers will be null, this is defensive in case ClientRuntime every has a // bug. I am OK with this as ApplyingClientBehavior is a one-time channel setup. if (behavior != null && behavior.InteractiveChannelInitializers != null) { // clear away any interactive initializer behavior.InteractiveChannelInitializers.Clear(); } } } public class RequestChannelFactory<TokenService> : ChannelFactoryBase, IChannelFactory<IRequestChannel> { private ChannelFactory<TokenService> _innerChannelFactory; public RequestChannelFactory(ChannelFactory<TokenService> innerChannelFactory) { _innerChannelFactory = innerChannelFactory; } public IRequestChannel CreateChannel(EndpointAddress address) { throw new NotImplementedException(); } public IRequestChannel CreateChannel(EndpointAddress address, Uri via) { throw new NotImplementedException(); } protected override void OnAbort() { _innerChannelFactory.Abort(); } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return _innerChannelFactory.BeginOpen(timeout, callback, state); } protected override void OnEndOpen(IAsyncResult result) { _innerChannelFactory.EndOpen(result); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return _innerChannelFactory.BeginClose(timeout, callback, state); } protected override void OnEndClose(IAsyncResult result) { _innerChannelFactory.EndClose(result); } protected override void OnClose(TimeSpan timeout) { _innerChannelFactory.Close(timeout); } protected override void OnOpen(TimeSpan timeout) { _innerChannelFactory.Open(timeout); } public override T GetProperty<T>() { return _innerChannelFactory.GetProperty<T>(); } } } } }
/* * 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 NUnit.Framework; using SimpleAnalyzer = Lucene.Net.Analysis.SimpleAnalyzer; using Document = Lucene.Net.Documents.Document; using Field = Lucene.Net.Documents.Field; using IndexWriter = Lucene.Net.Index.IndexWriter; using Term = Lucene.Net.Index.Term; using RAMDirectory = Lucene.Net.Store.RAMDirectory; using BooleanClause = Lucene.Net.Search.BooleanClause; using BooleanQuery = Lucene.Net.Search.BooleanQuery; using CheckHits = Lucene.Net.Search.CheckHits; using IndexSearcher = Lucene.Net.Search.IndexSearcher; using PhraseQuery = Lucene.Net.Search.PhraseQuery; using Query = Lucene.Net.Search.Query; using QueryUtils = Lucene.Net.Search.QueryUtils; using TermQuery = Lucene.Net.Search.TermQuery; using English = Lucene.Net.Util.English; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; namespace Lucene.Net.Search.Spans { /// <summary> Tests basic search capabilities. /// /// <p/>Uses a collection of 1000 documents, each the english rendition of their /// document number. For example, the document numbered 333 has text "three /// hundred thirty three". /// /// <p/>Tests are each a single query, and its hits are checked to ensure that /// all and only the correct documents are returned, thus providing end-to-end /// testing of the indexing and search code. /// /// </summary> [TestFixture] public class TestBasics:LuceneTestCase { private IndexSearcher searcher; [SetUp] public override void SetUp() { base.SetUp(); RAMDirectory directory = new RAMDirectory(); IndexWriter writer = new IndexWriter(directory, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); //writer.infoStream = System.out; for (int i = 0; i < 1000; i++) { Document doc = new Document(); doc.Add(new Field("field", English.IntToEnglish(i), Field.Store.YES, Field.Index.ANALYZED)); writer.AddDocument(doc); } writer.Close(); searcher = new IndexSearcher(directory); } [Test] public virtual void TestTerm() { Query query = new TermQuery(new Term("field", "seventy")); CheckHits(query, new int[]{70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 970, 971, 972, 973, 974, 975, 976, 977, 978, 979}); } [Test] public virtual void TestTerm2() { Query query = new TermQuery(new Term("field", "seventish")); CheckHits(query, new int[]{}); } [Test] public virtual void TestPhrase() { PhraseQuery query = new PhraseQuery(); query.Add(new Term("field", "seventy")); query.Add(new Term("field", "seven")); CheckHits(query, new int[]{77, 177, 277, 377, 477, 577, 677, 777, 877, 977}); } [Test] public virtual void TestPhrase2() { PhraseQuery query = new PhraseQuery(); query.Add(new Term("field", "seventish")); query.Add(new Term("field", "sevenon")); CheckHits(query, new int[]{}); } [Test] public virtual void TestBoolean() { BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term("field", "seventy")), BooleanClause.Occur.MUST); query.Add(new TermQuery(new Term("field", "seven")), BooleanClause.Occur.MUST); CheckHits(query, new int[]{77, 777, 177, 277, 377, 477, 577, 677, 770, 771, 772, 773, 774, 775, 776, 778, 779, 877, 977}); } [Test] public virtual void TestBoolean2() { BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term("field", "sevento")), BooleanClause.Occur.MUST); query.Add(new TermQuery(new Term("field", "sevenly")), BooleanClause.Occur.MUST); CheckHits(query, new int[]{}); } [Test] public virtual void TestSpanNearExact() { SpanTermQuery term1 = new SpanTermQuery(new Term("field", "seventy")); SpanTermQuery term2 = new SpanTermQuery(new Term("field", "seven")); SpanNearQuery query = new SpanNearQuery(new SpanQuery[]{term1, term2}, 0, true); CheckHits(query, new int[]{77, 177, 277, 377, 477, 577, 677, 777, 877, 977}); Assert.IsTrue(searcher.Explain(query, 77).GetValue() > 0.0f); Assert.IsTrue(searcher.Explain(query, 977).GetValue() > 0.0f); QueryUtils.Check(term1); QueryUtils.Check(term2); QueryUtils.CheckUnequal(term1, term2); } [Test] public virtual void TestSpanNearUnordered() { SpanTermQuery term1 = new SpanTermQuery(new Term("field", "nine")); SpanTermQuery term2 = new SpanTermQuery(new Term("field", "six")); SpanNearQuery query = new SpanNearQuery(new SpanQuery[]{term1, term2}, 4, false); CheckHits(query, new int[]{609, 629, 639, 649, 659, 669, 679, 689, 699, 906, 926, 936, 946, 956, 966, 976, 986, 996}); } [Test] public virtual void TestSpanNearOrdered() { SpanTermQuery term1 = new SpanTermQuery(new Term("field", "nine")); SpanTermQuery term2 = new SpanTermQuery(new Term("field", "six")); SpanNearQuery query = new SpanNearQuery(new SpanQuery[]{term1, term2}, 4, true); CheckHits(query, new int[]{906, 926, 936, 946, 956, 966, 976, 986, 996}); } [Test] public virtual void TestSpanNot() { SpanTermQuery term1 = new SpanTermQuery(new Term("field", "eight")); SpanTermQuery term2 = new SpanTermQuery(new Term("field", "one")); SpanNearQuery near = new SpanNearQuery(new SpanQuery[]{term1, term2}, 4, true); SpanTermQuery term3 = new SpanTermQuery(new Term("field", "forty")); SpanNotQuery query = new SpanNotQuery(near, term3); CheckHits(query, new int[]{801, 821, 831, 851, 861, 871, 881, 891}); Assert.IsTrue(searcher.Explain(query, 801).GetValue() > 0.0f); Assert.IsTrue(searcher.Explain(query, 891).GetValue() > 0.0f); } [Test] public virtual void TestSpanWithMultipleNotSingle() { SpanTermQuery term1 = new SpanTermQuery(new Term("field", "eight")); SpanTermQuery term2 = new SpanTermQuery(new Term("field", "one")); SpanNearQuery near = new SpanNearQuery(new SpanQuery[]{term1, term2}, 4, true); SpanTermQuery term3 = new SpanTermQuery(new Term("field", "forty")); SpanOrQuery or = new SpanOrQuery(new SpanQuery[]{term3}); SpanNotQuery query = new SpanNotQuery(near, or); CheckHits(query, new int[]{801, 821, 831, 851, 861, 871, 881, 891}); Assert.IsTrue(searcher.Explain(query, 801).GetValue() > 0.0f); Assert.IsTrue(searcher.Explain(query, 891).GetValue() > 0.0f); } [Test] public virtual void TestSpanWithMultipleNotMany() { SpanTermQuery term1 = new SpanTermQuery(new Term("field", "eight")); SpanTermQuery term2 = new SpanTermQuery(new Term("field", "one")); SpanNearQuery near = new SpanNearQuery(new SpanQuery[]{term1, term2}, 4, true); SpanTermQuery term3 = new SpanTermQuery(new Term("field", "forty")); SpanTermQuery term4 = new SpanTermQuery(new Term("field", "sixty")); SpanTermQuery term5 = new SpanTermQuery(new Term("field", "eighty")); SpanOrQuery or = new SpanOrQuery(new SpanQuery[]{term3, term4, term5}); SpanNotQuery query = new SpanNotQuery(near, or); CheckHits(query, new int[]{801, 821, 831, 851, 871, 891}); Assert.IsTrue(searcher.Explain(query, 801).GetValue() > 0.0f); Assert.IsTrue(searcher.Explain(query, 891).GetValue() > 0.0f); } [Test] public virtual void TestNpeInSpanNearWithSpanNot() { SpanTermQuery term1 = new SpanTermQuery(new Term("field", "eight")); SpanTermQuery term2 = new SpanTermQuery(new Term("field", "one")); SpanNearQuery near = new SpanNearQuery(new SpanQuery[]{term1, term2}, 4, true); SpanTermQuery hun = new SpanTermQuery(new Term("field", "hundred")); SpanTermQuery term3 = new SpanTermQuery(new Term("field", "forty")); SpanNearQuery exclude = new SpanNearQuery(new SpanQuery[]{hun, term3}, 1, true); SpanNotQuery query = new SpanNotQuery(near, exclude); CheckHits(query, new int[]{801, 821, 831, 851, 861, 871, 881, 891}); Assert.IsTrue(searcher.Explain(query, 801).GetValue() > 0.0f); Assert.IsTrue(searcher.Explain(query, 891).GetValue() > 0.0f); } [Test] public virtual void TestNpeInSpanNearInSpanFirstInSpanNot() { int n = 5; SpanTermQuery hun = new SpanTermQuery(new Term("field", "hundred")); SpanTermQuery term40 = new SpanTermQuery(new Term("field", "forty")); SpanTermQuery term40c = (SpanTermQuery) term40.Clone(); SpanFirstQuery include = new SpanFirstQuery(term40, n); SpanNearQuery near = new SpanNearQuery(new SpanQuery[]{hun, term40c}, n - 1, true); SpanFirstQuery exclude = new SpanFirstQuery(near, n - 1); SpanNotQuery q = new SpanNotQuery(include, exclude); CheckHits(q, new int[]{40, 41, 42, 43, 44, 45, 46, 47, 48, 49}); } [Test] public virtual void TestSpanFirst() { SpanTermQuery term1 = new SpanTermQuery(new Term("field", "five")); SpanFirstQuery query = new SpanFirstQuery(term1, 1); CheckHits(query, new int[]{5, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599}); Assert.IsTrue(searcher.Explain(query, 5).GetValue() > 0.0f); Assert.IsTrue(searcher.Explain(query, 599).GetValue() > 0.0f); } [Test] public virtual void TestSpanOr() { SpanTermQuery term1 = new SpanTermQuery(new Term("field", "thirty")); SpanTermQuery term2 = new SpanTermQuery(new Term("field", "three")); SpanNearQuery near1 = new SpanNearQuery(new SpanQuery[]{term1, term2}, 0, true); SpanTermQuery term3 = new SpanTermQuery(new Term("field", "forty")); SpanTermQuery term4 = new SpanTermQuery(new Term("field", "seven")); SpanNearQuery near2 = new SpanNearQuery(new SpanQuery[]{term3, term4}, 0, true); SpanOrQuery query = new SpanOrQuery(new SpanQuery[]{near1, near2}); CheckHits(query, new int[]{33, 47, 133, 147, 233, 247, 333, 347, 433, 447, 533, 547, 633, 647, 733, 747, 833, 847, 933, 947}); Assert.IsTrue(searcher.Explain(query, 33).GetValue() > 0.0f); Assert.IsTrue(searcher.Explain(query, 947).GetValue() > 0.0f); } [Test] public virtual void TestSpanExactNested() { SpanTermQuery term1 = new SpanTermQuery(new Term("field", "three")); SpanTermQuery term2 = new SpanTermQuery(new Term("field", "hundred")); SpanNearQuery near1 = new SpanNearQuery(new SpanQuery[]{term1, term2}, 0, true); SpanTermQuery term3 = new SpanTermQuery(new Term("field", "thirty")); SpanTermQuery term4 = new SpanTermQuery(new Term("field", "three")); SpanNearQuery near2 = new SpanNearQuery(new SpanQuery[]{term3, term4}, 0, true); SpanNearQuery query = new SpanNearQuery(new SpanQuery[]{near1, near2}, 0, true); CheckHits(query, new int[]{333}); Assert.IsTrue(searcher.Explain(query, 333).GetValue() > 0.0f); } [Test] public virtual void TestSpanNearOr() { SpanTermQuery t1 = new SpanTermQuery(new Term("field", "six")); SpanTermQuery t3 = new SpanTermQuery(new Term("field", "seven")); SpanTermQuery t5 = new SpanTermQuery(new Term("field", "seven")); SpanTermQuery t6 = new SpanTermQuery(new Term("field", "six")); SpanOrQuery to1 = new SpanOrQuery(new SpanQuery[]{t1, t3}); SpanOrQuery to2 = new SpanOrQuery(new SpanQuery[]{t5, t6}); SpanNearQuery query = new SpanNearQuery(new SpanQuery[]{to1, to2}, 10, true); CheckHits(query, new int[]{606, 607, 626, 627, 636, 637, 646, 647, 656, 657, 666, 667, 676, 677, 686, 687, 696, 697, 706, 707, 726, 727, 736, 737, 746, 747, 756, 757, 766, 767, 776, 777, 786, 787, 796, 797}); } [Test] public virtual void TestSpanComplex1() { SpanTermQuery t1 = new SpanTermQuery(new Term("field", "six")); SpanTermQuery t2 = new SpanTermQuery(new Term("field", "hundred")); SpanNearQuery tt1 = new SpanNearQuery(new SpanQuery[]{t1, t2}, 0, true); SpanTermQuery t3 = new SpanTermQuery(new Term("field", "seven")); SpanTermQuery t4 = new SpanTermQuery(new Term("field", "hundred")); SpanNearQuery tt2 = new SpanNearQuery(new SpanQuery[]{t3, t4}, 0, true); SpanTermQuery t5 = new SpanTermQuery(new Term("field", "seven")); SpanTermQuery t6 = new SpanTermQuery(new Term("field", "six")); SpanOrQuery to1 = new SpanOrQuery(new SpanQuery[]{tt1, tt2}); SpanOrQuery to2 = new SpanOrQuery(new SpanQuery[]{t5, t6}); SpanNearQuery query = new SpanNearQuery(new SpanQuery[]{to1, to2}, 100, true); CheckHits(query, new int[]{606, 607, 626, 627, 636, 637, 646, 647, 656, 657, 666, 667, 676, 677, 686, 687, 696, 697, 706, 707, 726, 727, 736, 737, 746, 747, 756, 757, 766, 767, 776, 777, 786, 787, 796, 797}); } [Test] public virtual void TestSpansSkipTo() { SpanTermQuery t1 = new SpanTermQuery(new Term("field", "seventy")); SpanTermQuery t2 = new SpanTermQuery(new Term("field", "seventy")); Spans s1 = t1.GetSpans(searcher.GetIndexReader()); Spans s2 = t2.GetSpans(searcher.GetIndexReader()); Assert.IsTrue(s1.Next()); Assert.IsTrue(s2.Next()); bool hasMore = true; do { hasMore = SkipToAccoringToJavaDocs(s1, s1.Doc()); Assert.AreEqual(hasMore, s2.SkipTo(s2.Doc())); Assert.AreEqual(s1.Doc(), s2.Doc()); } while (hasMore); } /// <summary>Skips to the first match beyond the current, whose document number is /// greater than or equal to <i>target</i>. <p/>Returns true iff there is such /// a match. <p/>Behaves as if written: <pre> /// boolean skipTo(int target) { /// do { /// if (!next()) /// return false; /// } while (target > doc()); /// return true; /// } /// </pre> /// </summary> private bool SkipToAccoringToJavaDocs(Spans s, int target) { do { if (!s.Next()) return false; } while (target > s.Doc()); return true; } private void CheckHits(Query query, int[] results) { Lucene.Net.Search.CheckHits.CheckHits_Renamed_Method(query, "field", searcher, results); } } }
// NoteDataXML_RichText.cs // // Copyright (c) 2013-2014 Brent Knowles (http://www.brentknowles.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. // // Review documentation at http://www.yourothermind.com for updated implementation notes, license updates // or other general information/ // // Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW // Full source code: https://github.com/BrentKnowles/YourOtherMind //### using System; using System.Windows.Forms; using CoreUtilities; using System.Xml.Serialization; using System.Drawing; using System.Reflection; namespace Layout { public class NoteDataXML_RichText : NoteDataXML { public enum FormatText {BOLD, STRIKETHRU, ZOOM, LINE, BULLET, BULLETNUMBER, DEFAULTFONT, DATE, UNDERLINE, ITALIC}; // if this is the value set on the dropdown then we use the defined default in OPTIONS const string defaultmarkup = "Default"; #region XML string markuplanguage="Default"; public string Markuplanguage { get { return markuplanguage; } set { markuplanguage = value; } } #endregion #region formcontrols protected RichTextExtended richBox ; protected ToolStripComboBox MarkupCombo; // right -click toggles protected NoteNavigation bookMarkView = null; protected TabNavigation tabView = null; protected ToolStripComboBox extraItemsToShow = null; #endregion public ExtraItemsToShow extraItemsToShow_value = ExtraItemsToShow.NONE; public enum ExtraItemsToShow {NONE, OUTLINE, HEADING_TABS, BOTH}; // mutex to prevent markup list from calling update when loading private bool loadingcombo = false; public override bool IsLinkable { get { return true; }} protected override void CommonConstructorBehavior () { base.CommonConstructorBehavior (); Caption = Loc.Instance.Cat.GetString("Text Note"); } public void TestEnter () { // for testing only richBox.Focus (); richBox.Text = "boo who"; Layout.Focus(); Layout.TestForceError(); } public NoteDataXML_RichText () : base() { } protected override string GetIcon () { return @"%*book.png"; } private iMarkupLanguage SelectedMarkup { get { iMarkupLanguage returnvalue = null; if (Markuplanguage != defaultmarkup) { // we need to create this once but LayoutDetails will store it inot until it changes again so // this won't be a slow operatin, just done on load and if changed returnvalue = LayoutDetails.Instance.GetMarkupMatch (Markuplanguage); } else { // we revert to none if plugin has been removed and we store this value too returnvalue = new MarkupLanguageNone (); } return returnvalue; } } public override void CopyNote (NoteDataInterface Note) { base.CopyNote (Note); // I moved the data1 copying into NoteDataXML for more flexibility } public NoteDataXML_RichText(NoteDataInterface Note) : base(Note) { } public NoteDataXML_RichText(int height, int width) : base(height, width) { //Caption = Loc.Instance.Cat.GetString("Text Note"); } private void UpdateMarkupSelection () { if (MarkupCombo.SelectedItem != null ){ if (MarkupCombo.Text == defaultmarkup) Markuplanguage = defaultmarkup; else { Markuplanguage = MarkupCombo.SelectedItem.GetType ().AssemblyQualifiedName.ToString (); richBox.MarkupOverride = (iMarkupLanguage)MarkupCombo.SelectedItem; } } } public override void Save () { base.Save (); // I made the decision to suppress Errors (hence not required CreateParent, for the purpose of MOVING notes // This violated an earlier decision I had made and I had to disable the TryToSaveWithoutCreating a Parent Exception if (richBox != null) { this.Data1 = richBox.Rtf; } if (MarkupCombo != null && MarkupCombo.Tag != null) { //MarkupTag is used to determine whether user has changed the data or not to avoid unnecessary slowness in save if (((bool)(MarkupCombo.Tag)) == true) { UpdateMarkupSelection (); } } } public RichTextExtended GetRichTextBox () { return richBox; } /// <summary> /// returns the text as text /// </summary> /// <returns> /// The as text. /// </returns> public string GetAsText () { if (richBox != null) { return richBox.Text; } return ""; } public string[] Lines() { return richBox.Lines; } /// <summary> /// Overwrites the with RTF file. /// </summary> /// <param name='file'> /// File. /// </param> public void DoOverwriteWithRTFFile (string file) { richBox.LoadFile(file); } /// <summary> /// Checks to see if the richtext is empty /// </summary> /// <returns> /// <c>true</c>, if text blank was riched, <c>false</c> otherwise. /// </returns> public bool GetIsRichTextBlank () { if (richBox.Text == Constants.BLANK) { return true; } return false; } protected override void DoChildAppearance (AppearanceClass app) { base.DoChildAppearance(app); richBox.BackColor = app.mainBackground; richBox.ForeColor = app.secondaryForeground; } protected override void DoBuildChildren (LayoutPanelBase Layout) { base.DoBuildChildren (Layout); CaptionLabel.Dock = DockStyle.Top; richBox = new RichTextExtended (); richBox.ContextMenuStrip = Layout.GetLayoutTextEditContextStrip (); richBox.Enter += HandleRichBoxEnter; richBox.Parent = ParentNotePanel; richBox.Dock = DockStyle.Fill; richBox.BringToFront (); richBox.Rtf = this.Data1; richBox.SelectionChanged += HandleRichTextSelectionChanged; richBox.TextChanged += HandleTextChanged; richBox.ReadOnly = this.ReadOnly; richBox.HideSelection = false; // must be able to see focus form other controls captionLabel.MouseDown += HandleMouseDownOnCaptionLabel; //CaptionLabel.MouseHover += HandleCaptionMouseHover; MarkupCombo = new ToolStripComboBox (); MarkupCombo.ToolTipText = Loc.Instance.GetString ("AddIns allow text notes to format text. A global option controls the default markup to use on notes but this may be overridden here."); // LayoutDetails.Instance.BuildMarkupComboBox (MarkupCombo); BuildDropDownList (); properties.DropDownItems.Add (new ToolStripSeparator()); ToolStripButton fullScreen = new ToolStripButton(); fullScreen.Text = Loc.GetStr("Fullscreen"); fullScreen.Click+= HandleFullScreenClick; properties.DropDown.Items.Add (fullScreen); properties.DropDownItems.Add (MarkupCombo); MarkupCombo.SelectedIndexChanged += HandleSelectedIndexChanged; MarkupCombo.DropDownStyle = ComboBoxStyle.DropDownList; MarkupCombo.DropDown += HandleDropDown; loadingcombo = true; // just show default if we have not overridden this if (Markuplanguage == defaultmarkup) { MarkupCombo.Text = defaultmarkup; } else if (SelectedMarkup != null) { for (int i = 0; i < MarkupCombo.Items.Count; i++) { if (MarkupCombo.Items [i].GetType () == SelectedMarkup.GetType ()) { MarkupCombo.SelectedIndex = i; break; } } richBox.MarkupOverride = (iMarkupLanguage)MarkupCombo.SelectedItem; } extraItemsToShow = new ToolStripComboBox (); extraItemsToShow.Items.AddRange (Enum.GetNames (typeof(ExtraItemsToShow))); extraItemsToShow.DropDownStyle = ComboBoxStyle.DropDownList; properties.DropDownItems.Add (extraItemsToShow); extraItemsToShow.SelectedIndex = (int)extraItemsToShow_value; extraItemsToShow.ToolTipText = Loc.Instance.GetString ("Reselect this to refresh after editing text."); extraItemsToShow.SelectedIndexChanged += (object sender, EventArgs e) => { extraItemsToShow_value = (ExtraItemsToShow)extraItemsToShow.SelectedIndex; SetSaveRequired (true); UpdateExtraView (); }; // we use markup tag to indicate whether the data on the markup combo has changed to avoid slowness in save MarkupCombo.Tag = false; loadingcombo = false; tabView = new TabNavigation (richBox); tabView.Visible = false; tabView.Parent = ParentNotePanel; tabView.Dock = DockStyle.Top; //tabView.SendToBack(); tabView.BringToFront (); if (null == bookMarkView) { bookMarkView = new NoteNavigation (this); } bookMarkView.Visible = false; AddBookmarkView (); UpdateExtraView(); richBox.BringToFront(); //CaptionLabel.BringToFront(); } void HandleFullScreenClick (object sender, EventArgs e) { FullScreenEditor editor = new FullScreenEditor (this); // we don't care how it closes; there is no cancel // we force an OK result if (editor.ShowDialog() != DialogResult.Retry ) { this.richBox.Rtf = editor.GetRTF(); this.Save (); } } /// <summary> /// Updates the extra view. /// /// Decides which extra elements to show, depending on user set options /// </summary> private void UpdateExtraView () { switch (extraItemsToShow_value) { case ExtraItemsToShow.NONE: tabView.Visible = false; bookMarkView.Visible = false; break; case ExtraItemsToShow.HEADING_TABS: tabView.Visible = true; bookMarkView.Visible = false; tabView.UpdateView (); break; case ExtraItemsToShow.OUTLINE: tabView.Visible = false; bookMarkView.Visible = true; AddBookmarkView (); break; case ExtraItemsToShow.BOTH: tabView.Visible = true; bookMarkView.Visible = true; tabView.UpdateView (); AddBookmarkView (); break; } // if (bookMarkView.Visible == true) { // //NewMessage.Show ("true"); // bookMarkView.BringToFront(); // } //else NewMessage.Show ("false"); } private void AddBookmarkView () { bool NeedToAdd = false; if (null == bookMarkView) { bookMarkView = new NoteNavigation (this); NeedToAdd = true; } bookMarkView.Location = new Point (richBox.Location.X, richBox.Location.Y); bookMarkView.Height = richBox.Height; bookMarkView.Width = ((int)richBox.Width / 2); if (bookMarkView.Width > bookMarkView.MAX_NAVIGATION_WIDTH) bookMarkView.Width = bookMarkView.MAX_NAVIGATION_WIDTH; bookMarkView.Dock = DockStyle.Left; if (NeedToAdd || bookMarkView.Parent == null) { ParentNotePanel.Controls.Add (bookMarkView); } if (true == bookMarkView.Visible) { bookMarkView.UpdateListOfBookmarks (); } } void HandleMouseDownOnCaptionLabel (object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { if (ParentNotePanel != null) { if (null == bookMarkView || bookMarkView.Visible == false) { // if (null != bookMarkView) // { // ParentNotePanel.Controls.Remove(bookMarkView); // } // 13/06/2014 - to make widen work we need to keep the control around AddBookmarkView(); // we do call this in buildchildren now bookMarkView.Visible = true; bookMarkView.UpdateListOfBookmarks (); } else { bookMarkView.Visible = false; } } } } void HandleRichTextSelectionChanged (object sender, EventArgs e) { if (LayoutDetails.Instance.CurrentLayout != null) { LayoutDetails.Instance.CurrentLayout.NeedsTextBoxUpdate = true; } // moving this to a timer // if (Layout.GetFindbar () != null) { // Layout.GetFindbar ().UpdateSelection (richBox.SelectedText, false); // } } void HandleSelectedIndexChanged (object sender, EventArgs e) { if (false == loadingcombo) { // if we ever have the default then we nerf the override richBox.MarkupOverride = null; // made a change. Need to save. MarkupCombo.Tag = true; UpdateMarkupSelection (); richBox.Invalidate(); } } void BuildDropDownList() { // always rebuild lsit if expanded in case AddIn added new MarkupCombo.Items.Clear (); LayoutDetails.Instance.BuildMarkupComboBox (MarkupCombo); // we add default as an option MarkupCombo.Items.Add(defaultmarkup); } void HandleDropDown (object sender, EventArgs e) { BuildDropDownList(); } protected void SetThisTextNoteAsActive() { Layout.CurrentTextNote = (NoteDataXML_RichText)this; if (Layout.GetFindbar() != null) Layout.GetFindbar().ResetSearch(); } /// <summary> /// Handles the rich box enter. Sets the active richtext box /// </summary> /// <param name='sender'> /// Sender. /// </param> /// <param name='e'> /// E. /// </param> void HandleRichBoxEnter (object sender, EventArgs e) { lg.Instance.Line("NoteDataXML_RichText", ProblemType.MESSAGE, String.Format ("{0} has been set as CurrentTextNote for Layout {1}", this.Caption, Layout.GUID)); SetThisTextNoteAsActive(); BringToFrontAndShow(); } void HandleTextChanged (object sender, EventArgs e) { this.SetSaveRequired(true); } /// <summary> /// Registers the type. /// </summary> public override string RegisterType() { return Loc.Instance.Cat.GetString("Text"); } protected override void RespondToReadOnlyChange() { this.richBox.ReadOnly = this.ReadOnly; } /// <summary> /// RichText Accessors /// </summary> /// <value> /// The selected text. /// </value> [XmlIgnore] public string SelectedText { get { if (richBox != null) { return richBox.SelectedText; } return Constants.BLANK; } set { richBox.SelectedText = value;} } [XmlIgnore] public int SelectionStart { get { return richBox.SelectionStart;} set { richBox.SelectionStart = value;} } [XmlIgnore] public int SelectionLength { get { return richBox.SelectionLength;} set { richBox.SelectionLength = value;} } public void Bold() { // richBox.SelectionFont = new System.Drawing.Font(richBox.SelectionFont.FontFamily, richBox.SelectionFont.Size, System.Drawing.FontStyle.Bold); General.FormatRichText(richBox, FontStyle.Bold); } public void Italic() { // richBox.SelectionFont = new System.Drawing.Font(richBox.SelectionFont.FontFamily, richBox.SelectionFont.Size, System.Drawing.FontStyle.Bold); General.FormatRichText(richBox, FontStyle.Italic); } public void Underline() { // richBox.SelectionFont = new System.Drawing.Font(richBox.SelectionFont.FontFamily, richBox.SelectionFont.Size, System.Drawing.FontStyle.Bold); General.FormatRichText(richBox, FontStyle.Underline); } public void Strike() { General.FormatRichText(richBox, FontStyle.Strikeout); } /// <summary> /// Will adjust the zoom of a richtext /// </summary> /// <param name="nCurrent"></param> public void ZoomToggle () { float nCurrent = richBox.ZoomFactor; if (nCurrent == 1.0f) { richBox.ZoomFactor = 1.25f; } else if (nCurrent == 1.25f) { richBox.ZoomFactor = 1.50f; } else if (nCurrent == 1.50f) { richBox.ZoomFactor = 1.75f; } else if (nCurrent == 1.75f) { richBox.ZoomFactor = 2.0f; } else if (nCurrent == 2.0f) { richBox.ZoomFactor = 1.0f; } else { // if any other value (i.e., by mouse zoom) we reset richBox.ZoomFactor = 1.0f; } } public override string ToString () { return this.Data1; // if (richBox != null) { // return richBox.Text; // } else { // return "no rich text box load"; // } } public override string GetStoryboardPreview { get { return this.Data1; } } // For link notes public override string GetLinkData () { return this.Data1; } public void SaveAsExternalFile (string sFile) { richBox.SaveFile (sFile, RichTextBoxStreamType.RichText); } public void ScrollToNearPosition () { if (richBox != null) { richBox.ScrollNearPosition(richBox.SelectionStart); } } } }
using Csla; using System.ComponentModel.DataAnnotations; using System; using System.ComponentModel; using Csla.Rules; namespace ProjectTracker.Library { [Serializable] public class ProjectResourceEdit : BusinessBase<ProjectResourceEdit> { public static readonly PropertyInfo<byte[]> TimeStampProperty = RegisterProperty<byte[]>(c => c.TimeStamp); [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public byte[] TimeStamp { get { return GetProperty(TimeStampProperty); } set { SetProperty(TimeStampProperty, value); } } public static readonly PropertyInfo<int> ResourceIdProperty = RegisterProperty<int>(c => c.ResourceId); [Display(Name = "Resource id")] public int ResourceId { get { return GetProperty(ResourceIdProperty); } private set { LoadProperty(ResourceIdProperty, value); } } public static readonly PropertyInfo<string> FirstNameProperty = RegisterProperty<string>(c => c.FirstName); [Display(Name = "First name")] public string FirstName { get { return GetProperty(FirstNameProperty); } private set { LoadProperty(FirstNameProperty, value); } } public static readonly PropertyInfo<string> LastNameProperty = RegisterProperty<string>(c => c.LastName); [Display(Name = "Last name")] public string LastName { get { return GetProperty(LastNameProperty); } private set { LoadProperty(LastNameProperty, value); } } [Display(Name = "Full name")] public string FullName { get { return string.Format("{0}, {1}", LastName, FirstName); } } public static readonly PropertyInfo<DateTime> AssignedProperty = RegisterProperty<DateTime>(c => c.Assigned); [Display(Name = "Date assigned")] public DateTime Assigned { get { return GetProperty(AssignedProperty); } private set { LoadProperty(AssignedProperty, value); } } public static readonly PropertyInfo<int> RoleProperty = RegisterProperty<int>(c => c.Role); [Display(Name = "Role assigned")] public int Role { get { return GetProperty(RoleProperty); } set { SetProperty(RoleProperty, value); } } [Display(Name = "Role")] public string RoleName { get { var result = "none"; if (RoleList.GetCachedList().ContainsKey(Role)) result = RoleList.GetCachedList().GetItemByKey(Role).Value; return result; } } public override string ToString() { return ResourceId.ToString(); } protected override void AddBusinessRules() { base.AddBusinessRules(); BusinessRules.AddRule(new ValidRole(RoleProperty)); BusinessRules.AddRule(new NotifyRoleNameChanged(RoleProperty)); BusinessRules.AddRule( new Csla.Rules.CommonRules.IsInRole( Csla.Rules.AuthorizationActions.WriteProperty, RoleProperty, Security.Roles.ProjectManager)); } private class NotifyRoleNameChanged : BusinessRule { public NotifyRoleNameChanged(Csla.Core.IPropertyInfo primaryProperty) : base(primaryProperty) { } protected override void Execute(IRuleContext context) { ((ProjectResourceEdit)context.Target).OnPropertyChanged(nameof(RoleName)); } } private void Child_Create(int resourceId) { using (BypassPropertyChecks) { ResourceId = resourceId; RoleList.CacheList(); Role = RoleList.DefaultRole(); LoadProperty(AssignedProperty, DateTime.Today); using (var ctx = ProjectTracker.Dal.DalFactory.GetManager()) { var dal = ctx.GetProvider<ProjectTracker.Dal.IResourceDal>(); var person = dal.Fetch(resourceId); FirstName = person.FirstName; LastName = person.LastName; } } base.Child_Create(); } private void Child_Fetch(int projectId, int resourceId) { using (var ctx = ProjectTracker.Dal.DalFactory.GetManager()) { var dal = ctx.GetProvider<ProjectTracker.Dal.IAssignmentDal>(); var data = dal.Fetch(projectId, resourceId); Child_Fetch(data); } } private void Child_Fetch(ProjectTracker.Dal.AssignmentDto data) { using (BypassPropertyChecks) { ResourceId = data.ResourceId; Role = data.RoleId; LoadProperty(AssignedProperty, data.Assigned); TimeStamp = data.LastChanged; using (var ctx = ProjectTracker.Dal.DalFactory.GetManager()) { var dal = ctx.GetProvider<ProjectTracker.Dal.IResourceDal>(); var person = dal.Fetch(data.ResourceId); FirstName = person.FirstName; LastName = person.LastName; } } } private void Child_Insert(ProjectEdit project) { Child_Insert(project.Id); } private void Child_Insert(int projectId) { using (var ctx = ProjectTracker.Dal.DalFactory.GetManager()) { var dal = ctx.GetProvider<ProjectTracker.Dal.IAssignmentDal>(); using (BypassPropertyChecks) { var item = new ProjectTracker.Dal.AssignmentDto { ProjectId = projectId, ResourceId = this.ResourceId, Assigned = ReadProperty(AssignedProperty), RoleId = this.Role }; dal.Insert(item); TimeStamp = item.LastChanged; } } } private void Child_Update(ProjectEdit project) { Child_Update(project.Id); } private void Child_Update(int projectId) { using (var ctx = ProjectTracker.Dal.DalFactory.GetManager()) { var dal = ctx.GetProvider<ProjectTracker.Dal.IAssignmentDal>(); using (BypassPropertyChecks) { var item = dal.Fetch(projectId, ResourceId); item.Assigned = ReadProperty(AssignedProperty); item.RoleId = Role; item.LastChanged = TimeStamp; dal.Update(item); TimeStamp = item.LastChanged; } } } private void Child_DeleteSelf(ProjectEdit project) { using (var ctx = ProjectTracker.Dal.DalFactory.GetManager()) { var dal = ctx.GetProvider<ProjectTracker.Dal.IAssignmentDal>(); using (BypassPropertyChecks) { dal.Delete(project.Id, ResourceId); } } } } }
// 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; using System.Runtime; using System.ServiceModel.Channels; namespace System.ServiceModel.Dispatcher { internal class ImmutableClientRuntime { private int _correlationCount; private bool _addTransactionFlowProperties; private IInteractiveChannelInitializer[] _interactiveChannelInitializers; private IClientOperationSelector _operationSelector; private IChannelInitializer[] _channelInitializers; private IClientMessageInspector[] _messageInspectors; private Dictionary<string, ProxyOperationRuntime> _operations; private ProxyOperationRuntime _unhandled; private bool _useSynchronizationContext; private bool _validateMustUnderstand; internal ImmutableClientRuntime(ClientRuntime behavior) { _channelInitializers = EmptyArray<IChannelInitializer>.ToArray(behavior.ChannelInitializers); _interactiveChannelInitializers = EmptyArray<IInteractiveChannelInitializer>.ToArray(behavior.InteractiveChannelInitializers); _messageInspectors = EmptyArray<IClientMessageInspector>.ToArray(behavior.MessageInspectors); _operationSelector = behavior.OperationSelector; _useSynchronizationContext = behavior.UseSynchronizationContext; _validateMustUnderstand = behavior.ValidateMustUnderstand; _unhandled = new ProxyOperationRuntime(behavior.UnhandledClientOperation, this); _addTransactionFlowProperties = behavior.AddTransactionFlowProperties; _operations = new Dictionary<string, ProxyOperationRuntime>(); for (int i = 0; i < behavior.Operations.Count; i++) { ClientOperation operation = behavior.Operations[i]; ProxyOperationRuntime operationRuntime = new ProxyOperationRuntime(operation, this); _operations.Add(operation.Name, operationRuntime); } _correlationCount = _messageInspectors.Length + behavior.MaxParameterInspectors; } internal int MessageInspectorCorrelationOffset { get { return 0; } } internal int ParameterInspectorCorrelationOffset { get { return _messageInspectors.Length; } } internal int CorrelationCount { get { return _correlationCount; } } internal IClientOperationSelector OperationSelector { get { return _operationSelector; } } internal ProxyOperationRuntime UnhandledProxyOperation { get { return _unhandled; } } internal bool UseSynchronizationContext { get { return _useSynchronizationContext; } } internal bool ValidateMustUnderstand { get { return _validateMustUnderstand; } set { _validateMustUnderstand = value; } } internal void AfterReceiveReply(ref ProxyRpc rpc) { int offset = this.MessageInspectorCorrelationOffset; try { for (int i = 0; i < _messageInspectors.Length; i++) { _messageInspectors[i].AfterReceiveReply(ref rpc.Reply, rpc.Correlation[offset + i]); if (WcfEventSource.Instance.ClientMessageInspectorAfterReceiveInvokedIsEnabled()) { WcfEventSource.Instance.ClientMessageInspectorAfterReceiveInvoked(rpc.EventTraceActivity, _messageInspectors[i].GetType().FullName); } } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (ErrorBehavior.ShouldRethrowClientSideExceptionAsIs(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } } internal void BeforeSendRequest(ref ProxyRpc rpc) { int offset = this.MessageInspectorCorrelationOffset; try { for (int i = 0; i < _messageInspectors.Length; i++) { ServiceChannel clientChannel = ServiceChannelFactory.GetServiceChannel(rpc.Channel.Proxy); rpc.Correlation[offset + i] = _messageInspectors[i].BeforeSendRequest(ref rpc.Request, clientChannel); if (WcfEventSource.Instance.ClientMessageInspectorBeforeSendInvokedIsEnabled()) { WcfEventSource.Instance.ClientMessageInspectorBeforeSendInvoked(rpc.EventTraceActivity, _messageInspectors[i].GetType().FullName); } } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (ErrorBehavior.ShouldRethrowClientSideExceptionAsIs(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } } internal void DisplayInitializationUI(ServiceChannel channel) { EndDisplayInitializationUI(BeginDisplayInitializationUI(channel, null, null)); } internal IAsyncResult BeginDisplayInitializationUI(ServiceChannel channel, AsyncCallback callback, object state) { return new DisplayInitializationUIAsyncResult(channel, _interactiveChannelInitializers, callback, state); } internal void EndDisplayInitializationUI(IAsyncResult result) { DisplayInitializationUIAsyncResult.End(result); } internal void InitializeChannel(IClientChannel channel) { try { for (int i = 0; i < _channelInitializers.Length; ++i) { _channelInitializers[i].Initialize(channel); } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (ErrorBehavior.ShouldRethrowClientSideExceptionAsIs(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } } internal ProxyOperationRuntime GetOperation(MethodBase methodBase, object[] args, out bool canCacheResult) { if (_operationSelector == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException (SR.Format(SR.SFxNeedProxyBehaviorOperationSelector2, methodBase.Name, methodBase.DeclaringType.Name))); } try { if (_operationSelector.AreParametersRequiredForSelection) { canCacheResult = false; } else { args = null; canCacheResult = true; } string operationName = _operationSelector.SelectOperation(methodBase, args); ProxyOperationRuntime operation; if ((operationName != null) && _operations.TryGetValue(operationName, out operation)) { return operation; } else { // did not find the right operation, will not know how // to invoke the method. return null; } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (ErrorBehavior.ShouldRethrowClientSideExceptionAsIs(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } } internal ProxyOperationRuntime GetOperationByName(string operationName) { ProxyOperationRuntime operation = null; if (_operations.TryGetValue(operationName, out operation)) return operation; else return null; } internal class DisplayInitializationUIAsyncResult : System.Runtime.AsyncResult { private ServiceChannel _channel; private int _index = -1; private IInteractiveChannelInitializer[] _initializers; private IClientChannel _proxy; private static AsyncCallback s_callback = Fx.ThunkCallback(new AsyncCallback(DisplayInitializationUIAsyncResult.Callback)); internal DisplayInitializationUIAsyncResult(ServiceChannel channel, IInteractiveChannelInitializer[] initializers, AsyncCallback callback, object state) : base(callback, state) { _channel = channel; _initializers = initializers; _proxy = ServiceChannelFactory.GetServiceChannel(channel.Proxy); this.CallBegin(true); } private void CallBegin(bool completedSynchronously) { while (++_index < _initializers.Length) { IAsyncResult result = null; Exception exception = null; try { result = _initializers[_index].BeginDisplayInitializationUI( _proxy, DisplayInitializationUIAsyncResult.s_callback, this ); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } exception = e; } if (exception == null) { if (!result.CompletedSynchronously) { return; } this.CallEnd(result, out exception); } if (exception != null) { this.CallComplete(completedSynchronously, exception); return; } } this.CallComplete(completedSynchronously, null); } private static void Callback(IAsyncResult result) { if (result.CompletedSynchronously) { return; } DisplayInitializationUIAsyncResult outer = (DisplayInitializationUIAsyncResult)result.AsyncState; Exception exception = null; outer.CallEnd(result, out exception); if (exception != null) { outer.CallComplete(false, exception); return; } outer.CallBegin(false); } private void CallEnd(IAsyncResult result, out Exception exception) { try { _initializers[_index].EndDisplayInitializationUI(result); exception = null; } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } exception = e; } } private void CallComplete(bool completedSynchronously, Exception exception) { this.Complete(completedSynchronously, exception); } internal static void End(IAsyncResult result) { System.Runtime.AsyncResult.End<DisplayInitializationUIAsyncResult>(result); } } } }
// Copyright (c) 2015, Outercurve Foundation. // 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 Outercurve Foundation 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.Text; using System.Web.UI.WebControls; using WebsitePanel.EnterpriseServer; using WebsitePanel.EnterpriseServer.Base.HostedSolution; using WebsitePanel.Providers.Common; using WebsitePanel.Providers.HostedSolution; using WebsitePanel.Providers.OS; using WebsitePanel.WebPortal; namespace WebsitePanel.Portal.ExchangeServer { public partial class EnterpriseStorageFolders : WebsitePanelModuleBase { #region Constants private const int OneGb = 1024; #endregion protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (ES.Services.EnterpriseStorage.CheckUsersDomainExists(PanelRequest.ItemID)) { BindEnterpriseStorageStats(); RegisterStatusScript(); hdnItemId.Value = PanelRequest.ItemID.ToString(); gvFolders.DataBound -= OnDataBound; gvFolders.DataBound += OnDataBound; } else { btnAddFolder.Enabled = false; messageBox.ShowWarningMessage("WEB_SITE_IS_NOT_CREATED"); } } } private void RegisterStatusScript() { if (!Page.ClientScript.IsClientScriptBlockRegistered("ESAjaxQuery")) { var builder = new StringBuilder(); builder.AppendLine("function getFolderData() {"); builder.AppendFormat("var hidden = document.getElementById('{0}').value;", hdnGridState.ClientID); builder.AppendFormat("var grid = document.getElementById('{0}');", gvFolders.ClientID); builder.AppendFormat("var itemId = document.getElementById('{0}').value;", hdnItemId.ClientID); builder.AppendLine("if (hidden === 'True'){"); builder.AppendFormat("$('#{0}').val('false');", hdnGridState.ClientID); builder.AppendLine("for (i = 1; i < grid.rows.length; i++) {"); builder.AppendLine("var folderName = grid.rows[i].cells[0].children[0].value;"); builder.AppendLine("$.ajax({"); builder.AppendLine("type: 'post',"); builder.AppendLine("dataType: 'json',"); builder.AppendLine("data: { folderName: folderName, itemIndex: i, itemId: itemId },"); builder.AppendLine("url: 'EnterpriseFolderDataHandler.ashx',"); builder.AppendLine("success: function (data) {"); builder.AppendLine("var array = data.split(':');"); builder.AppendLine("var usage = array[0];"); builder.AppendLine("var index = array[1];"); builder.AppendLine("var driveLetter = array[2];"); builder.AppendLine("grid.rows[index].cells[3].childNodes[0].data = usage;"); builder.AppendLine("var driveImage = grid.rows[index].cells[5].children[0];"); builder.AppendLine("driveImage.style.display = driveLetter.length < 3 ? 'inline' : 'none';"); builder.AppendLine("grid.rows[index].cells[5].childNodes[2].data = ' ' + driveLetter +':';"); builder.AppendLine("}"); builder.AppendLine("}"); builder.AppendLine(")}"); builder.AppendLine("}"); builder.AppendLine("}"); Page.ClientScript.RegisterClientScriptInclude("jquery", ResolveUrl("~/JavaScript/jquery-1.4.4.min.js")); Page.ClientScript.RegisterClientScriptBlock(typeof(EnterpriseStorageFolders), "ESAjaxQuery", builder.ToString(), true); } } private void OnDataBound(object sender, EventArgs e) { if (gvFolders.Rows.Count > 0) { hdnGridState.Value = true.ToString(); } } public string GetFolderEditUrl(string folderName) { return EditUrl("SpaceID", PanelSecurity.PackageId.ToString(), "enterprisestorage_folder_settings", "FolderID=" + folderName, "ItemID=" + PanelRequest.ItemID); } public static decimal ConvertMBytesToGB(object size) { return Math.Round(Convert.ToDecimal(size) / OneGb, 2); } protected void BindEnterpriseStorageStats() { btnAddFolder.Enabled = true; OrganizationStatistics organizationStats = ES.Services.EnterpriseStorage.GetStatisticsByOrganization(PanelRequest.ItemID); foldersQuota.QuotaUsedValue = organizationStats.CreatedEnterpriseStorageFolders; foldersQuota.QuotaValue = organizationStats.AllocatedEnterpriseStorageFolders; spaceAvailableQuota.QuotaUsedValue = organizationStats.UsedEnterpriseStorageSpace; spaceAvailableQuota.QuotaValue = organizationStats.AllocatedEnterpriseStorageSpace; spaceQuota.QuotaValue = (int)Math.Round(ConvertMBytesToGB(organizationStats.UsedEnterpriseStorageSpace), 0); if (organizationStats.AllocatedEnterpriseStorageFolders != -1) { int folderAvailable = foldersQuota.QuotaAvailable = organizationStats.AllocatedEnterpriseStorageFolders - organizationStats.CreatedEnterpriseStorageFolders; if (folderAvailable <= 0) { btnAddFolder.Enabled = false; } } if (organizationStats.AllocatedEnterpriseStorageSpace != -1) { int spaceAvailable = spaceAvailableQuota.QuotaAvailable = organizationStats.AllocatedEnterpriseStorageSpace - organizationStats.UsedEnterpriseStorageSpace; if (spaceAvailable <= 0) { btnAddFolder.Enabled = false; } } } protected void btnAddFolder_Click(object sender, EventArgs e) { Response.Redirect(EditUrl("ItemID", PanelRequest.ItemID.ToString(), "create_enterprisestorage_folder", "SpaceID=" + PanelSecurity.PackageId)); } protected void gvFolders_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "DeleteItem") { // delete folder string folderName = e.CommandArgument.ToString(); try { ResultObject result = ES.Services.EnterpriseStorage.DeleteEnterpriseFolder(PanelRequest.ItemID, folderName); if (!result.IsSuccess) { messageBox.ShowMessage(result, "ENTERPRISE_STORAGE_FOLDER", "EnterpriseStorage"); return; } gvFolders.DataBind(); BindEnterpriseStorageStats(); } catch (Exception ex) { ShowErrorMessage("ENTERPRISE_STORAGE_DELETE_FOLDER", ex); } } } protected void odsSecurityGroupsPaged_Selected(object sender, ObjectDataSourceStatusEventArgs e) { if (e.Exception != null) { messageBox.ShowErrorMessage("ORGANIZATION_GET_SECURITY_GROUP", e.Exception); e.ExceptionHandled = true; } } protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e) { gvFolders.PageSize = Convert.ToInt16(ddlPageSize.SelectedValue); gvFolders.DataBind(); } protected string GetDriveImage() { return String.Concat("~/", DefaultPage.THEMES_FOLDER, "/", Page.Theme, "/", "Images/Exchange", "/", "net_drive16.png"); } } }
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using AttributeInfo = GlTF_VertexLayout.AttributeInfo; // TODO: merge GLTF_VertexLayout and TiltBrush.GeometryPool.VertexLayout // (which to keep is up in the air) and figure out what to do about UVSemantic using Semantic = TiltBrush.GeometryPool.Semantic; public sealed class GlTF_Attributes { public readonly GlTF_VertexLayout m_layout; public readonly GlTF_Accessor normalAccessor; public readonly GlTF_Accessor colorAccessor; public readonly GlTF_Accessor tangentAccessor; public readonly GlTF_Accessor positionAccessor; public readonly GlTF_Accessor texCoord0Accessor; public readonly GlTF_Accessor texCoord1Accessor; public readonly GlTF_Accessor texCoord2Accessor; public readonly GlTF_Accessor texCoord3Accessor; private readonly Dictionary<string, GlTF_Accessor> m_accessors = new Dictionary<string, GlTF_Accessor>(); public GlTF_Attributes( GlTF_Globals G, ObjectName meshName, GlTF_VertexLayout layout) { // This prefix should be used with possibly-nonconforming gltf data: // - texcoords that are not 2-element or that don't contain texture coordinates // - made-up / mythical semantics like VERTEXID string nonconformingPrefix = (G.GltfCompatibilityMode) ? "_TB_UNITY_" : ""; m_layout = layout; { AttributeInfo positionInfo = layout.PositionInfo; positionAccessor = G.CreateAccessor( GlTF_Accessor.GetNameFromObject(meshName, "position"), positionInfo.accessorType, positionInfo.accessorComponentType); m_accessors.Add("POSITION", positionAccessor); } {if (layout.NormalInfo is AttributeInfo normalInfo) { normalAccessor = G.CreateAccessor( GlTF_Accessor.GetNameFromObject(meshName, "normal"), normalInfo.accessorType, normalInfo.accessorComponentType); // Genius particles put things that don't look like normals into the normal attribute. bool isNonconforming = (layout.m_tbLayout.normalSemantic == Semantic.Position); string prefix = isNonconforming ? nonconformingPrefix : ""; m_accessors.Add(prefix+"NORMAL", normalAccessor); }} {if (layout.ColorInfo is AttributeInfo cInfo) { colorAccessor = G.CreateAccessor( GlTF_Accessor.GetNameFromObject(meshName, "color"), cInfo.accessorType, cInfo.accessorComponentType, normalized: true); m_accessors.Add(G.Gltf2 ? "COLOR_0" : "COLOR", colorAccessor); }} {if (layout.TangentInfo is AttributeInfo tangentInfo) { tangentAccessor = G.CreateAccessor( GlTF_Accessor.GetNameFromObject(meshName, "tangent"), tangentInfo.accessorType, tangentInfo.accessorComponentType); m_accessors.Add("TANGENT", tangentAccessor); }} if (layout.PackVertexIdIntoTexcoord1W) { // The vertexid hack modifies the gl layout to extend texcoord1 so the vertexid // can be stuffed into it Debug.Assert(layout.m_tbLayout.GetTexcoordInfo(1).size == 3); Debug.Assert(layout.GetTexcoordSize(1) == 4); } GlTF_Accessor MakeAccessorFor(int texcoord) { var txcInfo = layout.GetTexcoordInfo(texcoord); if (txcInfo == null) { return null; } Semantic tbSemantic = layout.m_tbLayout.GetTexcoordInfo(texcoord).semantic; string attrName = $"{nonconformingPrefix}TEXCOORD_{texcoord}"; // Timestamps are tunneled into us via a texcoord because there's not really a better way // due to GeometryPool limitations. But that's an internal implementation detail. I'd like // them to have a better attribute name in the gltf. if (tbSemantic == Semantic.Timestamp) { // For b/141876882; Poly doesn't like _TB_TIMESTAMP if (! G.Gltf2) { return null; } attrName = "_TB_TIMESTAMP"; } var ret = G.CreateAccessor( GlTF_Accessor.GetNameFromObject(meshName, $"uv{texcoord}"), txcInfo.Value.accessorType, txcInfo.Value.accessorComponentType); m_accessors.Add(attrName, ret); return ret; } texCoord0Accessor = MakeAccessorFor(0); texCoord1Accessor = MakeAccessorFor(1); texCoord2Accessor = MakeAccessorFor(2); texCoord3Accessor = MakeAccessorFor(3); if (G.GltfCompatibilityMode) { TiltBrush.GeometryPool.VertexLayout tbLayout = layout.m_tbLayout; switch (tbLayout.texcoord0.semantic) { case Semantic.Unspecified when tbLayout.texcoord0.size == 2: case Semantic.XyIsUv: case Semantic.XyIsUvZIsDistance: { GlTF_Accessor accessor = GlTF_Accessor.CloneWithDifferentType( G, texCoord0Accessor, GlTF_Accessor.Type.VEC2); m_accessors.Add("TEXCOORD_0", accessor); break; } } // No need to check the other texcoords because TB only ever puts texture coordinates // in texcoord0 } } private void PopulateUv( int channel, TiltBrush.GeometryPool pool, GlTF_Accessor accessor, Semantic semantic) { bool packVertId = m_layout.PackVertexIdIntoTexcoord1W && channel == 1; if (packVertId) { // Guaranteed by GlTF_VertexLayout Debug.Assert(m_layout.m_tbLayout.GetTexcoordInfo(channel).size == 3); Debug.Assert(m_layout.GetTexcoordSize(channel) == 4); } if (accessor == null) { return; } if (channel < 0 || channel > 3) { throw new ArgumentException("Invalid channel"); } TiltBrush.GeometryPool.TexcoordData texcoordData = pool.GetTexcoordData(channel); if (semantic == Semantic.XyIsUvZIsDistance && accessor.type != GlTF_Accessor.Type.VEC3) { throw new ArgumentException("XyIsUvZIsDistance semantic can only be applied to VEC3"); } bool flipY; if (semantic == Semantic.Unspecified && channel == 0 && accessor.type == GlTF_Accessor.Type.VEC2) { Debug.LogWarning("Assuming Semantic.XyIsUv"); semantic = Semantic.XyIsUv; } switch (semantic) { case Semantic.Position: case Semantic.Vector: case Semantic.Timestamp: flipY = false; break; case Semantic.XyIsUvZIsDistance: case Semantic.XyIsUv: flipY = true; break; default: throw new ArgumentException("semantic"); } switch (accessor.type) { case GlTF_Accessor.Type.SCALAR: throw new NotImplementedException(); case GlTF_Accessor.Type.VEC2: accessor.Populate(texcoordData.v2, flipY: flipY, calculateMinMax: false); break; case GlTF_Accessor.Type.VEC3: accessor.Populate(texcoordData.v3, flipY: flipY, calculateMinMax: false); break; case GlTF_Accessor.Type.VEC4: if (packVertId) { // In the vertexId case, we actually have a vec3, which needs to be augmented to a vec4. // TODO: this should happen at some higher level. int i = 0; var v4 = texcoordData.v3.ConvertAll<Vector4>((v => new Vector4(v.x, v.y, v.z, i++))); accessor.Populate(v4, flipY: flipY, calculateMinMax: false); } else { accessor.Populate(texcoordData.v4, flipY: flipY, calculateMinMax: false); } break; default: throw new ArgumentException("Unexpected accessor.type"); } } public void Populate(TiltBrush.GeometryPool pool) { positionAccessor.Populate(pool.m_Vertices, flipY: false, calculateMinMax: true); if (normalAccessor != null) { normalAccessor.Populate(pool.m_Normals, flipY: false, calculateMinMax: false); } if (colorAccessor != null) { colorAccessor.Populate(pool.m_Colors); } if (tangentAccessor != null) { tangentAccessor.Populate(pool.m_Tangents, flipY: false, calculateMinMax: false); } // UVs may be 1, 2, 3 or 4 element tuples, which the following helper method resolves. // In the case of zero UVs, the texCoord accessor will be null and will not be populated. Debug.Assert(TiltBrush.GeometryPool.kNumTexcoords == 3); Debug.Assert(texCoord3Accessor == null); var layout = pool.Layout; PopulateUv(0, pool, texCoord0Accessor, layout.texcoord0.semantic); PopulateUv(1, pool, texCoord1Accessor, layout.texcoord1.semantic); PopulateUv(2, pool, texCoord2Accessor, layout.texcoord2.semantic); PopulateUv(3, pool, texCoord3Accessor, Semantic.Unspecified); } public void WriteAsNamedJObject(GlTF_Globals G, string name) { // Recreates the ordering of the old code, for easier diffing. G.WriteKeyAndIndentIn(name, "{"); // Recreate ordering of the old code for easier diffing. int OldOrder(string attribute) { switch (attribute) { case "POSITION": return 0; case "NORMAL": return 1; case "COLOR_0": case "COLOR": return 2; case "TANGENT": return 3; case "VERTEXID": return 4; default: return 5; } } // Sort dictionary to make output deterministic. foreach (var keyValue in m_accessors.OrderBy(kvp => (OldOrder(kvp.Key), kvp.Key))) { G.CNI.WriteNamedReference(keyValue.Key, keyValue.Value); } G.NewlineAndIndentOut("}"); } public IEnumerable<GlTF_ReferencedObject> IterReferences(GlTF_Globals G) { return m_accessors.Select(keyValue => keyValue.Value); } }
using System; using System.Collections.Generic; using System.Linq.Expressions; using Baseline.Reflection; using Oakton; using Oakton.Help; using Oakton.Parsing; using Shouldly; using Xunit; namespace Tests { public class InputParserTester { private readonly InputModel theInput = new InputModel(); private ITokenHandler handlerFor(Expression<Func<InputModel, object>> expression) { var property = expression.ToAccessor().InnerProperty; return InputParser.BuildHandler(property); } private bool handle(Expression<Func<InputModel, object>> expression, params string[] args) { var queue = new Queue<string>(args); var handler = handlerFor(expression); return handler.Handle(theInput, queue); } [Fact] public void the_handler_for_a_normal_property_not_marked_as_flag() { handlerFor(x => x.File).ShouldBeOfType<Argument>(); } [Fact] public void the_handler_for_an_enumeration_property_marked_as_flag() { handlerFor(x => x.ColorFlag).ShouldBeOfType<Flag>(); } [Fact] public void the_handler_for_an_enumeration_property_not_marked_as_flag() { handlerFor(x => x.Color).ShouldBeOfType<Argument>(); } [Fact] public void the_handler_for_a_property_suffixed_by_flag() { handlerFor(x => x.OrderFlag).ShouldBeOfType<Flag>(); } [Fact] public void the_handler_for_a_boolean_flag() { handlerFor(x => x.TrueFalseFlag).ShouldBeOfType<BooleanFlag>(); } [Fact] public void handler_for_an_array() { handlerFor(x => x.Ages).ShouldBeOfType<EnumerableArgument>(); } [Fact] public void get_the_long_flag_name_for_a_property() { var property = ReflectionHelper.GetProperty<InputModel>(x => x.OrderFlag); InputParser.ToFlagAliases(property).LongForm.ShouldBe("--order"); } [Fact] public void the_long_name_should_allow_for_dashes() { var property = ReflectionHelper.GetProperty<InputModel>(x => x.TrueOrFalseFlag); InputParser.ToFlagAliases(property).LongForm.ShouldBe("--true-or-false"); } [Fact] public void the_long_name_should_allow_overriding() { var property = ReflectionHelper.GetProperty<InputModel>(x => x.MakeSuckModeFlag); InputParser.ToFlagAliases(property).LongForm.ShouldBe("--makesuckmode"); } [Fact] public void get_the_short_flag_name_for_a_property() { var property = ReflectionHelper.GetProperty<InputModel>(x => x.OrderFlag); InputParser.ToFlagAliases(property).ShortForm.ShouldBe("-o"); } [Fact] public void get_the_long_flag_name_for_a_property_with_an_alias() { var property = ReflectionHelper.GetProperty<InputModel>(x => x.AliasedFlag); InputParser.ToFlagAliases(property).LongForm.ShouldBe("--aliased"); } [Fact] public void get_the_long_flag_name_for_property_named_flag() { var property = ReflectionHelper.GetProperty<InputModel>(x => x.Flag); InputParser.ToFlagAliases(property).LongForm.ShouldBe("--flag"); } [Fact] public void get_the_short_name_for_property_named_flag() { var property = ReflectionHelper.GetProperty<InputModel>(x => x.Flag); InputParser.ToFlagAliases(property).ShortForm.ShouldBe("-f"); } [Fact] public void get_the_short_flag_name_for_a_property_with_an_alias() { var property = ReflectionHelper.GetProperty<InputModel>(x => x.AliasedFlag); InputParser.ToFlagAliases(property).ShortForm.ShouldBe("-a"); } [Fact] public void boolean_flag_does_not_catch() { handle(x => x.TrueFalseFlag, "nottherightthing").ShouldBeFalse(); theInput.TrueFalseFlag.ShouldBeFalse(); } [Fact] public void boolean_flag_long_form_should_be_case_insensitive() { handle(x => x.TrueFalseFlag, "--True-False").ShouldBeTrue(); theInput.TrueFalseFlag.ShouldBeTrue(); } [Fact] public void boolean_flag_does_catch_2() { handle(x => x.TrueFalseFlag, "--true-false").ShouldBeTrue(); theInput.TrueFalseFlag.ShouldBeTrue(); } [Fact] public void enumerable_argument() { handle(x => x.Ages, "1", "2", "3").ShouldBeTrue(); theInput.Ages.ShouldHaveTheSameElementsAs(1, 2, 3); } [Fact] public void enumeration_argument() { handle(x => x.Color, "red").ShouldBeTrue(); theInput.Color.ShouldBe(Color.red); } [Fact] public void enumeration_argument_2() { handle(x => x.Color, "green").ShouldBeTrue(); theInput.Color.ShouldBe(Color.green); } [Fact] public void enumeration_flag_negative() { handle(x => x.ColorFlag, "green").ShouldBeFalse(); } [Fact] public void enumeration_flag_positive() { handle(x => x.ColorFlag, "--color", "blue").ShouldBeTrue(); theInput.ColorFlag.ShouldBe(Color.blue); } [Fact] public void string_argument() { handle(x => x.File, "the file").ShouldBeTrue(); theInput.File.ShouldBe("the file"); } [Fact] public void int_flag_does_not_catch() { handle(x => x.OrderFlag, "not order flag").ShouldBeFalse(); theInput.OrderFlag.ShouldBe(0); } [Fact] public void int_flag_catches() { handle(x => x.OrderFlag, "--order", "23").ShouldBeTrue(); theInput.OrderFlag.ShouldBe(23); } private InputModel build(params string[] tokens) { var queue = new Queue<string>(tokens); var graph = new InputCommand().Usages; var creator = new ActivatorCommandCreator(); return (InputModel) graph.BuildInput(queue, creator); } [Fact] public void integrated_test_arguments_only() { var input = build("file1", "red"); input.File.ShouldBe("file1"); input.Color.ShouldBe(Color.red); // default is not touched input.OrderFlag.ShouldBe(0); } [Fact] public void integrated_test_with_mix_of_flags() { var input = build("file1", "--color", "green", "blue", "--order", "12"); input.File.ShouldBe("file1"); input.Color.ShouldBe(Color.blue); input.ColorFlag.ShouldBe(Color.green); input.OrderFlag.ShouldBe(12); } [Fact] public void integrated_test_with_a_boolean_flag() { var input = build("file1", "blue", "--true-false"); input.TrueFalseFlag.ShouldBeTrue(); build("file1", "blue").TrueFalseFlag.ShouldBeFalse(); } [Fact] public void long_flag_with_dashes_should_pass() { var input = build("file1", "blue", "--herp-derp"); input.HerpDerpFlag.ShouldBeTrue(); build("file1", "blue").HerpDerpFlag.ShouldBeFalse(); } [Fact] public void isflag_should_match_on_double_hyphen() { InputParser.IsFlag("--f").ShouldBeTrue(); } [Fact] public void isflag_should_not_match_without_double_hyphen() { InputParser.IsFlag("f").ShouldBeFalse(); } [Fact] public void boolean_short_flag_does_not_catch() { handle(x => x.TrueFalseFlag, "-f").ShouldBeFalse(); theInput.TrueFalseFlag.ShouldBeFalse(); } [Fact] public void boolean_short_flag_does_catch() { handle(x => x.TrueFalseFlag, "-t").ShouldBeTrue(); theInput.TrueFalseFlag.ShouldBeTrue(); } [Fact] public void boolean_short_flag_case_uppercase() { var input = build("file1", "blue", "-T"); input.TrueFalseFlag.ShouldBeFalse(); input.TrueOrFalseFlag.ShouldBeTrue(); } [Fact] public void boolean_short_flag_case_lowercase() { var input = build("file1", "blue", "-t"); input.TrueFalseFlag.ShouldBeTrue(); input.TrueOrFalseFlag.ShouldBeFalse(); } [Fact] public void boolean_short_flag_case_both() { var input = build("file1", "blue", "-t", "-T"); input.TrueFalseFlag.ShouldBeTrue(); input.TrueOrFalseFlag.ShouldBeTrue(); } [Fact] public void integration_test_with_enumerable_flags() { var input = build("file1", "blue", "-t", "-s", "suck", "fail", "-T"); input.TrueFalseFlag.ShouldBeTrue(); input.TrueOrFalseFlag.ShouldBeTrue(); input.SillyFlag.ShouldHaveTheSameElementsAs("suck","fail"); } [Fact] public void enumeration_short_flag_negative() { handle(x => x.ColorFlag, "green").ShouldBeFalse(); } [Fact] public void enumeration_short_flag_positive() { handle(x => x.ColorFlag, "-c", "blue").ShouldBeTrue(); theInput.ColorFlag.ShouldBe(Color.blue); } [Fact] public void IsFlag_should_match_for_short_flag() { InputParser.IsFlag("-x").ShouldBeTrue(); } [Fact] public void IsFlag_should_match_for_long_flag() { InputParser.IsFlag("--xerces").ShouldBeTrue(); } [Fact] public void IsFlag_negative() { InputParser.IsFlag("x").ShouldBeFalse(); } [Fact] public void IsFlag_negative_2() { InputParser.IsFlag("---x").ShouldBeFalse(); } [Fact] public void IsShortFlag_should_match_for_short_flag() { InputParser.IsShortFlag("-x").ShouldBeTrue(); } [Fact] public void IsShortFlag_should_not_match_for_long_flag() { InputParser.IsShortFlag("--xerces").ShouldBeFalse(); } [Fact] public void IsLongFlag_should_not_match_for_short_flag() { InputParser.IsLongFlag("-x").ShouldBeFalse(); } [Fact] public void IsLongFlag_should_match_for_long_flag() { InputParser.IsLongFlag("--xerces").ShouldBeTrue(); } [Fact] public void IsLongFlag_with_dashes_should_match_for_long_flag() { InputParser.IsLongFlag("--herp-derp").ShouldBeTrue(); } [Fact] public void IsLongFlag_should_not_match_for_triple_long_flag() { InputParser.IsLongFlag("---xerces").ShouldBeFalse(); } [Fact] public void RemoveFlagSuffix_should_remove_suffix() { InputParser.RemoveFlagSuffix("FlagFlag").ShouldBe("Flag"); } [Fact] public void RemoveFlagSuffix_should_stay_same_if_is_suffix() { InputParser.RemoveFlagSuffix("Flag").ShouldBe("Flag"); } [Fact] public void complex_usage_smoketest() { new UsageGraph(typeof(InputCommand)).WriteUsages("fubu"); } [Fact] public void use_dictionary_flag_for_dict() { handlerFor(x => x.PropsFlag).ShouldBeOfType<DictionaryFlag>(); } } public enum Color { red, green, blue } public class InputModel { public string File { get; set; } public Color ColorFlag { get; set; } public Color Color { get; set; } public int OrderFlag { get; set; } public bool TrueFalseFlag { get; set; } [FlagAlias('T')] public bool TrueOrFalseFlag { get; set; } public IEnumerable<string> SillyFlag { get; set; } public bool HerpDerpFlag { get; set; } [FlagAlias("makesuckmode")] public bool MakeSuckModeFlag { get; set; } public IEnumerable<int> Ages { get; set; } [FlagAlias("aliased", 'a')] public string AliasedFlag { get; set; } public Dictionary<string, string> PropsFlag { get; set; } = new Dictionary<string, string>(); public string Flag { get; set; } } public class InputCommand : OaktonCommand<InputModel> { public InputCommand() { Usage("default").Arguments(x => x.File, x => x.Color); Usage("ages").Arguments(x => x.File, x => x.Color, x => x.Ages); } public override bool Execute(InputModel input) { throw new NotImplementedException(); } } }
/* * Copyright (c) 2010-2011, Achim 'ahzf' Friedland <achim@graph-database.org> * This file is part of Balder <http://www.github.com/Vanaheimr/Balder> * * 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. */ #region Usings using System; using System.Collections.Generic; using NUnit.Framework; using de.ahzf.Vanaheimr.Styx; using de.ahzf.Illias.Commons; using de.ahzf.Illias.Commons.Collections; using de.ahzf.Vanaheimr.Blueprints.UnitTests; using de.ahzf.Vanaheimr.Blueprints; #endregion namespace de.ahzf.Vanaheimr.Balder.UnitTests.FilterPipes { [TestFixture] public class OrFilterPipeTest { #region testOrPipeBasic() [Test] public void testOrPipeBasic() { var _Names = new List<String>() { "marko", "povel", "peter", "povel", "marko" }; var _Pipe1 = new ObjectFilterPipe<String>("marko", ComparisonFilter.NOT_EQUAL); var _Pipe2 = new ObjectFilterPipe<String>("povel", ComparisonFilter.NOT_EQUAL); var _ORFilterPipe = new OrFilterPipe<String>(new HasNextPipe<String>(_Pipe1), new HasNextPipe<String>(_Pipe2)); _ORFilterPipe.SetSourceCollection(_Names); int _Counter = 0; while (_ORFilterPipe.MoveNext()) { var name = _ORFilterPipe.Current; Assert.IsTrue(name.Equals("marko") || name.Equals("povel")); _Counter++; } Assert.AreEqual(4, _Counter); } #endregion #region testOrPipeGraph() [Test] public void testOrPipeGraph() { // ./outE[@label='created' or @weight > 0.5] var _Graph = TinkerGraphFactory.CreateTinkerGraph(); var _Marko = _Graph.VertexById(1); var _Peter = _Graph.VertexById(6); var _Pipe0 = new OutEdgesPipe<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>(); var _Pipe1 = new EdgeLabelFilterPipe<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>(v => v != "created"); var _Pipe2 = new EdgePropertyFilterPipe<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>("weight", v => (0.5).Equals(v)); var _ORFilterPipe = new OrFilterPipe<IGenericPropertyEdge<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>( new HasNextPipe<IGenericPropertyEdge<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>(_Pipe1), new HasNextPipe<IGenericPropertyEdge<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>(_Pipe2)); var _Pipeline = new Pipeline<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>, IGenericPropertyEdge<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>(_Pipe0, _ORFilterPipe); _Pipeline.SetSourceCollection(new List<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>() { _Marko, _Peter, _Marko }); var _Counter = 0; while (_Pipeline.MoveNext()) { var _Edge = _Pipeline.Current; Assert.IsTrue(_Edge.Id.Equals(8) || _Edge.Id.Equals(9) || _Edge.Id.Equals(12)); Assert.IsTrue(((Double)_Edge.GetProperty("weight")) > 0.5f || _Edge.Label.Equals("created")); _Counter++; } Assert.AreEqual(5, _Counter); } #endregion #region testAndOrPipeGraph() [Test] public void testAndOrPipeGraph() { // ./outE[@label='created' or (@label='knows' and @weight > 0.5)] var _Graph = TinkerGraphFactory.CreateTinkerGraph(); var _Marko = _Graph.VertexById(1); var _Pipe1 = new OutEdgesPipe <UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>(); var _PipeA = new EdgeLabelFilterPipe<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>(v => v != "created"); var _PipeB = new EdgeLabelFilterPipe<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>(v => v != "knows"); var _PipeC = new EdgePropertyFilterPipe<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>("weight", v => (0.5).Equals(v)); var _PipeD = new AndFilterPipe<IGenericPropertyEdge<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>( new HasNextPipe<IGenericPropertyEdge<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>(_PipeB), new HasNextPipe<IGenericPropertyEdge<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>(_PipeC)); var _Pipe2 = new OrFilterPipe<IGenericPropertyEdge<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>( new HasNextPipe<IGenericPropertyEdge<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>(_PipeA), new HasNextPipe<IGenericPropertyEdge<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>(_PipeD)); var _Pipeline = new Pipeline<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>, IGenericPropertyEdge<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>(_Pipe1, _Pipe2); _Pipeline.SetSourceCollection(new List<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>() { _Marko }); int _Counter = 0; while (_Pipeline.MoveNext()) { var _Edge = _Pipeline.Current; Assert.IsTrue(_Edge.Id.Equals(8) || _Edge.Id.Equals(9)); Assert.IsTrue(_Edge.Label.Equals("created") || (((Double)_Edge.GetProperty("weight")) > 0.5 && _Edge.Label.Equals("knows"))); _Counter++; } Assert.AreEqual(2, _Counter); } #endregion #region testFutureFilter() [Test] public void testFutureFilter() { var _Names = new List<String>() { "marko", "peter", "josh", "marko", "jake", "marko", "marko" }; var _PipeA = new CharacterCountPipe(); var _PipeB = new ObjectFilterPipe<UInt64>(4, ComparisonFilter.EQUAL); var _Pipe1 = new OrFilterPipe<String>(new HasNextPipe<String>(new Pipeline<String, UInt64>(_PipeA, _PipeB))); var _Pipeline = new Pipeline<String, String>(_Pipe1); _Pipeline.SetSourceCollection(_Names); int _Counter = 0; while (_Pipeline.MoveNext()) { var name = _Pipeline.Current; _Counter++; Assert.IsTrue((name.Equals("marko") || name.Equals("peter")) && !name.Equals("josh") && !name.Equals("jake")); } Assert.AreEqual(5, _Counter); } #endregion #region testFutureFilterGraph() [Test] public void testFutureFilterGraph() { // ./outE[@label='created']/inV[@name='lop']/../../@name var _Graph = TinkerGraphFactory.CreateTinkerGraph(); var _Marko = _Graph.VertexById(1); var _PipeA = new OutEdgesPipe <UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>(); var _PipeB = new EdgeLabelFilterPipe<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>(v => v != "created"); var _PipeC = new InVertexPipe <UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>(); var _PipeD = new VertexPropertyFilterPipe<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>("name", v => v == "lop"); var _Pipe1 = new AndFilterPipe<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>( new HasNextPipe<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>( new Pipeline<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>, IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>(_PipeA, _PipeB, _PipeC, _PipeD))); var _Pipe2 = new PropertyPipe<String, Object>(Keys: "name"); var _Pipeline = new Pipeline<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>, String>(_Pipe1, _Pipe2); _Pipeline.SetSourceCollection(new List<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>() { _Marko }); var _Counter = 0; while (_Pipeline.MoveNext()) { var name = _Pipeline.Current; Assert.AreEqual("marko", name); _Counter++; } Assert.AreEqual(1, _Counter); } #endregion #region testComplexFutureFilterGraph() [Test] public void testComplexFutureFilterGraph() { // ./outE[@weight > 0.5]/inV/../../outE/inV/@name var _Graph = TinkerGraphFactory.CreateTinkerGraph(); var _Marko = _Graph.VertexById(1); var _PipeA = new OutEdgesPipe<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>(); var _PipeB = new EdgePropertyFilterPipe<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>("weight", v => (0.5).Equals(v)); var _PipeC = new InVertexPipe<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>(); var _Pipe1 = new AndFilterPipe<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>( new HasNextPipe<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>( new Pipeline<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>, IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>(_PipeA, _PipeB, _PipeC))); var _Pipe2 = new OutEdgesPipe<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>(); var _Pipe3 = new InVertexPipe<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>(); var _Pipe4 = new PropertyPipe<String, Object>(Keys: "name"); var _Pipeline = new Pipeline<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>, String>(_Pipe1, _Pipe2, _Pipe3, _Pipe4); _Pipeline.SetSourceCollection(new List<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>() { _Marko }); var _Counter = 0; while (_Pipeline.MoveNext()) { var _Name = _Pipeline.Current; Assert.IsTrue(_Name.Equals("vadas") || _Name.Equals("lop") || _Name.Equals("josh")); _Counter++; } Assert.AreEqual(3, _Counter); } #endregion #region testComplexTwoFutureFilterGraph() [Test] public void testComplexTwoFutureFilterGraph() { // ./outE/inV/../../outE/../outE/inV/@name var _Graph = TinkerGraphFactory.CreateTinkerGraph(); var _Marko = _Graph.VertexById(1); var _PipeA = new OutEdgesPipe<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>(); var _PipeB = new InVertexPipe<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>(); var _Pipe1 = new OrFilterPipe<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>( new HasNextPipe<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>( new Pipeline<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>, IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>(_PipeA, _PipeB))); var _PipeC = new OutEdgesPipe<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>(); var _Pipe2 = new OrFilterPipe<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>( new HasNextPipe<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>(_PipeC)); var _Pipe3 = new OutEdgesPipe<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>(); var _Pipe4 = new InVertexPipe<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>(); var _Pipe5 = new PropertyPipe<String, Object>(Keys: "name"); var _Pipeline = new Pipeline<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>, String>(_Pipe1, _Pipe2, _Pipe3, _Pipe4, _Pipe5); _Pipeline.SetSourceCollection(new List<IGenericPropertyVertex<UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object, UInt64, Int64, String, String, Object>>() { _Marko }); var _Counter = 0; while (_Pipeline.MoveNext()) { var _Name = _Pipeline.Current; Assert.IsTrue(_Name.Equals("vadas") || _Name.Equals("lop") || _Name.Equals("josh")); _Counter++; } Assert.AreEqual(3, _Counter); } #endregion } }
//----------------------------------------------------------------------- // <copyright file="StreamLayout.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Runtime.Serialization; using Akka.Pattern; using Akka.Streams.Dsl; using Akka.Streams.Implementation.Fusing; using Akka.Streams.Util; using Akka.Util; using Akka.Util.Internal; using Reactive.Streams; namespace Akka.Streams.Implementation { public static class StreamLayout { //TODO: Materialization order //TODO: Special case linear composites //TODO: Cycles public static readonly bool IsDebug = false; #region Materialized Value Node types public interface IMaterializedValueNode { } public sealed class Combine : IMaterializedValueNode { public readonly Func<object, object, object> Combinator; public readonly IMaterializedValueNode Left; public readonly IMaterializedValueNode Right; public Combine(Func<object, object, object> combinator, IMaterializedValueNode left, IMaterializedValueNode right) { Combinator = combinator; Left = left; Right = right; } public override string ToString() => $"Combine({Left}, {Right})"; } public sealed class Atomic : IMaterializedValueNode { public readonly IModule Module; public Atomic(IModule module) { Module = module; } public override string ToString() => $"Atomic({Module.Attributes.GetNameOrDefault(Module.GetType().Name)}[{Module.GetHashCode()}])"; } public sealed class Transform : IMaterializedValueNode { public readonly Func<object, object> Transformator; public readonly IMaterializedValueNode Node; public Transform(Func<object, object> transformator, IMaterializedValueNode node) { Transformator = transformator; Node = node; } public override string ToString() => $"Transform({Node})"; } public sealed class Ignore : IMaterializedValueNode { public static readonly Ignore Instance = new Ignore(); private Ignore() { } public override string ToString() => "Ignore"; } #endregion public static void Validate(IModule module, int level = 0, bool shouldPrint = false, IDictionary<object, int> idMap = null) { idMap = idMap ?? new Dictionary<object, int>(); var currentId = 1; Func<int> ids = () => currentId++; Func<object, int> id = obj => { int x; if (!idMap.TryGetValue(obj, out x)) { x = ids(); idMap.Add(obj, x); } return x; }; Func<InPort, string> inPort = i => $"{i}@{id(i)}"; Func<OutPort, string> outPort = o => $"{o}@{id(o)}"; Func<IEnumerable<InPort>, string> ins = i => $"In[{string.Join(",", i.Select(inPort))}]"; Func<IEnumerable<OutPort>, string> outs = o => $"Out[{string.Join(",", o.Select(outPort))}]"; Func<OutPort, InPort, string> pair = (o, i) => $"{inPort(i)}->{outPort(o)}"; Func<IEnumerable<KeyValuePair<OutPort, InPort>>, string> pairs = i => $"[{string.Join(",", i.Select(p => pair(p.Key, p.Value)))}]"; var shape = module.Shape; var inset = shape.Inlets.ToImmutableHashSet(); var outset = shape.Outlets.ToImmutableHashSet(); var inPorts = module.InPorts.Cast<Inlet>().ToImmutableHashSet(); var outPorts = module.OutPorts.Cast<Outlet>().ToImmutableHashSet(); var problems = new List<string>(); if (inset.Count != shape.Inlets.Count()) problems.Add("shape has duplicate inlets " + ins(shape.Inlets)); if (!inset.SetEquals(inPorts)) problems.Add($"shape has extra {ins(inset.Except(inPorts))}, module has extra {ins(inPorts.Except(inset))}"); var connectedInlets = inset.Intersect(module.Upstreams.Keys).ToArray(); if (connectedInlets.Any()) problems.Add("found connected inlets " + ins(connectedInlets)); if (outset.Count != shape.Outlets.Count()) problems.Add("shape has duplicate outlets " + outs(shape.Outlets)); if (!outset.SetEquals(outPorts)) problems.Add($"shape has extra {outs(outset.Except(outPorts))}, module has extra {outs(outPorts.Except(outset))}"); var connectedOutlets = outset.Intersect(module.Downstreams.Keys).ToArray(); if (connectedOutlets.Any()) problems.Add("found connected outlets " + outs(connectedOutlets)); var ups = module.Upstreams.ToImmutableHashSet(); var ups2 = ups.Select(x => new KeyValuePair<OutPort, InPort>(x.Value, x.Key)).ToImmutableHashSet(); var downs = module.Downstreams.ToImmutableHashSet(); var inter = ups2.Intersect(downs); if (!downs.SetEquals(ups2)) problems.Add($"inconsistent maps: ups {pairs(ups2.Except(inter))} downs {pairs(downs.Except(inter))}"); var allInBuilder = ImmutableHashSet<InPort>.Empty.ToBuilder(); var duplicateInBuilder = ImmutableHashSet<InPort>.Empty.ToBuilder(); var allOutBuilder = ImmutableHashSet<OutPort>.Empty.ToBuilder(); var duplicateOutBuilder = ImmutableHashSet<OutPort>.Empty.ToBuilder(); foreach (var subModule in module.SubModules) { // check for duplicates before adding current module's ports duplicateInBuilder.UnionWith(allInBuilder.Intersect(subModule.InPorts)); allInBuilder.UnionWith(subModule.InPorts); // check for duplicates before adding current module's ports duplicateOutBuilder.UnionWith(allOutBuilder.Intersect(subModule.OutPorts)); allOutBuilder.UnionWith(subModule.OutPorts); } var allIn = allInBuilder.ToImmutable(); var duplicateIn = duplicateInBuilder.ToImmutable(); var allOut = allOutBuilder.ToImmutable(); var duplicateOut = duplicateOutBuilder.ToImmutable(); if (!duplicateIn.IsEmpty) problems.Add("duplicate ports in submodules " + ins(duplicateIn)); if (!duplicateOut.IsEmpty) problems.Add("duplicate ports in submodules " + outs(duplicateOut)); if (!module.IsSealed && inset.Except(allIn).Any()) problems.Add("foreign inlets " + ins(inset.Except(allIn))); if (!module.IsSealed && outset.Except(allOut).Any()) problems.Add("foreign outlets " + outs(outset.Except(allOut))); var unIn = allIn.Except(inset).Except(module.Upstreams.Keys); if (unIn.Any() && !module.IsCopied) problems.Add("unconnected inlets " + ins(unIn)); var unOut = allOut.Except(outset).Except(module.Downstreams.Keys); if (unOut.Any() && !module.IsCopied) problems.Add("unconnected outlets " + outs(unOut)); var atomics = Atomics(module.MaterializedValueComputation); var graphValues = module.SubModules.SelectMany(m => m is GraphModule ? ((GraphModule)m).MaterializedValueIds : Enumerable.Empty<IModule>()); var nonExistent = atomics.Except(module.SubModules).Except(graphValues).Except(new[] { module }); if (nonExistent.Any()) problems.Add("computation refers to non-existent modules " + string.Join(", ", nonExistent)); var print = shouldPrint || problems.Any(); if (print) { var indent = string.Empty.PadLeft(level * 2); Console.Out.WriteLine("{0}{1}({2}): {3} {4}", indent, typeof(StreamLayout).Name, shape, ins(inPorts), outs(outPorts)); foreach (var downstream in module.Downstreams) Console.Out.WriteLine("{0} {1} -> {2}", indent, outPort(downstream.Key), inPort(downstream.Value)); foreach (var problem in problems) Console.Out.WriteLine("{0} -!- {1}", indent, problem); } foreach (var subModule in module.SubModules) Validate(subModule, level + 1, print, idMap); if (problems.Any() && !shouldPrint) throw new IllegalStateException( $"module inconsistent, found {problems.Count} problems:\n - {string.Join("\n - ", problems)}"); } private static ImmutableHashSet<IModule> Atomics(IMaterializedValueNode node) { if (node is Ignore) return ImmutableHashSet<IModule>.Empty; if (node is Transform) return Atomics(((Transform)node).Node); if (node is Atomic) return ImmutableHashSet.Create(((Atomic)node).Module); Combine c; if ((c = node as Combine) != null) return Atomics(c.Left).Union(Atomics(c.Right)); throw new ArgumentException("Couldn't extract atomics for node " + node.GetType()); } } public interface IModule : IComparable<IModule> { Shape Shape { get; } /// <summary> /// Verify that the given Shape has the same ports and return a new module with that shape. /// Concrete implementations may throw UnsupportedOperationException where applicable. /// </summary> IModule ReplaceShape(Shape shape); IImmutableSet<InPort> InPorts { get; } IImmutableSet<OutPort> OutPorts { get; } bool IsRunnable { get; } bool IsSink { get; } bool IsSource { get; } bool IsFlow { get; } bool IsBidiFlow { get; } bool IsAtomic { get; } bool IsCopied { get; } /// <summary> /// Fuses this Module to <paramref name="that"/> Module by wiring together <paramref name="from"/> and <paramref name="to"/>, /// retaining the materialized value of `this` in the result /// </summary> /// <param name="that">A module to fuse with</param> /// <param name="from">The data source to wire</param> /// <param name="to">The data sink to wire</param> /// <returns>A module representing fusion of `this` and <paramref name="that"/></returns> IModule Fuse(IModule that, OutPort from, InPort to); /// <summary> /// Fuses this Module to <paramref name="that"/> Module by wiring together <paramref name="from"/> and <paramref name="to"/>, /// retaining the materialized value of `this` in the result, using the provided function <paramref name="matFunc"/>. /// </summary> /// <param name="that">A module to fuse with</param> /// <param name="from">The data source to wire</param> /// <param name="to">The data sink to wire</param> /// <param name="matFunc">The function to apply to the materialized values</param> /// <returns>A module representing fusion of `this` and <paramref name="that"/></returns> IModule Fuse<T1, T2, T3>(IModule that, OutPort from, InPort to, Func<T1, T2, T3> matFunc); /// <summary> /// Creates a new Module based on the current Module but with the given OutPort wired to the given InPort. /// </summary> /// <param name="from">The OutPort to wire.</param> /// <param name="to">The InPort to wire.</param> /// <returns>A new Module with the ports wired</returns> IModule Wire(OutPort from, InPort to); IModule TransformMaterializedValue<TMat, TMat2>(Func<TMat, TMat2> mapFunc); /// <summary> /// Creates a new Module which is this Module composed with <paramref name="that"/> Module. /// </summary> /// <param name="that">A Module to be composed with (cannot be itself)</param> /// <returns>A Module that represents the composition of this and <paramref name="that"/></returns> IModule Compose(IModule that); /// <summary> /// Creates a new Module which is this Module composed with <paramref name="that"/> Module, /// using the given function <paramref name="matFunc"/> to compose the materialized value of `this` with /// the materialized value of <paramref name="that"/>. /// </summary> /// <param name="that">A Module to be composed with (cannot be itself)</param> /// <param name="matFunc">A function which combines the materialized values</param> /// <typeparam name="T1">The type of the materialized value of this</typeparam> /// <typeparam name="T2">The type of the materialized value of <paramref name="that"/></typeparam> /// <typeparam name="T3">The type of the materialized value of the returned Module</typeparam> /// <returns>A Module that represents the composition of this and <paramref name="that"/></returns> IModule Compose<T1, T2, T3>(IModule that, Func<T1, T2, T3> matFunc); /// <summary> /// Creates a new Module which is this Module composed with <paramref name="that"/> Module. /// /// The difference to compose(that) is that this version completely ignores the materialized value /// computation of <paramref name="that"/> while the normal version executes the computation and discards its result. /// This means that this version must not be used for user-provided <paramref name="that"/> modules because users may /// transform materialized values only to achieve some side-effect; it can only be /// used where we know that there is no meaningful computation to be done (like for /// MaterializedValueSource). /// </summary> /// <param name="that">a Module to be composed with (cannot be itself)</param> /// <returns>a Module that represents the composition of this and <paramref name="that"/></returns> IModule ComposeNoMaterialized(IModule that); /// <summary> /// Creates a new Module which contains this Module /// </summary> IModule Nest(); // this cannot be set, since sets are changing ordering of modules // which must be kept for fusing to work ImmutableArray<IModule> SubModules { get; } bool IsSealed { get; } IImmutableDictionary<OutPort, InPort> Downstreams { get; } IImmutableDictionary<InPort, OutPort> Upstreams { get; } StreamLayout.IMaterializedValueNode MaterializedValueComputation { get; } IModule CarbonCopy(); Attributes Attributes { get; } IModule WithAttributes(Attributes attributes); } public abstract class Module : IModule { private readonly Lazy<IImmutableSet<InPort>> _inports; private readonly Lazy<IImmutableSet<OutPort>> _outports; protected Module() { _inports = new Lazy<IImmutableSet<InPort>>(() => ImmutableHashSet.CreateRange(Shape.Inlets.Cast<InPort>())); _outports = new Lazy<IImmutableSet<OutPort>>(() => ImmutableHashSet.CreateRange(Shape.Outlets.Cast<OutPort>())); } public IImmutableSet<InPort> InPorts => _inports.Value; public IImmutableSet<OutPort> OutPorts => _outports.Value; public virtual bool IsRunnable => InPorts.Count == 0 && OutPorts.Count == 0; public virtual bool IsSink => InPorts.Count == 1 && OutPorts.Count == 0; public virtual bool IsSource => InPorts.Count == 0 && OutPorts.Count == 1; public virtual bool IsFlow => InPorts.Count == 1 && OutPorts.Count == 1; public virtual bool IsBidiFlow => InPorts.Count == 2 && OutPorts.Count == 2; public virtual bool IsAtomic => !SubModules.Any(); public virtual bool IsCopied => false; public virtual bool IsFused => false; public virtual IModule Fuse(IModule other, OutPort @from, InPort to) => Fuse<object, object, object>(other, @from, to, Keep.Left); public virtual IModule Fuse<T1, T2, T3>(IModule other, OutPort @from, InPort to, Func<T1, T2, T3> matFunc) => Compose(other, matFunc).Wire(@from, to); public virtual IModule Wire(OutPort @from, InPort to) { if (StreamLayout.IsDebug) StreamLayout.Validate(this); if (!OutPorts.Contains(from)) { var message = Downstreams.ContainsKey(from) ? $"The output port [{@from}] is already connected" : $"The output port [{@from}] is not part of underlying graph"; throw new ArgumentException(message); } if (!InPorts.Contains(to)) { var message = Upstreams.ContainsKey(to) ? $"The input port [{to}] is already connected" : $"The input port [{to}] is not part of underlying graph"; throw new ArgumentException(message); } return new CompositeModule( subModules: SubModules, shape: new AmorphousShape( Shape.Inlets.Where(i => !i.Equals(to)).ToImmutableArray(), Shape.Outlets.Where(o => !o.Equals(from)).ToImmutableArray()), downstreams: Downstreams.SetItem(from, to), upstreams: Upstreams.SetItem(to, from), materializedValueComputation: MaterializedValueComputation, attributes: Attributes); } public virtual IModule TransformMaterializedValue<TMat, TMat2>(Func<TMat, TMat2> mapFunc) { if (StreamLayout.IsDebug) StreamLayout.Validate(this); return new CompositeModule( subModules: IsSealed ? ImmutableArray.Create(this as IModule) : SubModules, shape: Shape, downstreams: Downstreams, upstreams: Upstreams, materializedValueComputation: new StreamLayout.Transform(x => mapFunc((TMat)x), IsSealed ? new StreamLayout.Atomic(this) : MaterializedValueComputation), attributes: Attributes); } public virtual IModule Compose(IModule other) => Compose<object, object, object>(other, Keep.Left); public virtual IModule Compose<T1, T2, T3>(IModule other, Func<T1, T2, T3> matFunc) { if (StreamLayout.IsDebug) StreamLayout.Validate(this); if (Equals(other, this)) throw new ArgumentException("A module cannot be added to itself. You should pass a separate instance to compose()."); if (SubModules.Contains(other)) throw new ArgumentException("An existing submodule cannot be added again. All contained modules must be unique."); var modules1 = IsSealed ? ImmutableArray.Create<IModule>(this) : SubModules; var modules2 = other.IsSealed ? ImmutableArray.Create(other) : other.SubModules; var matComputationLeft = IsSealed ? new StreamLayout.Atomic(this) : MaterializedValueComputation; var matComputationRight = other.IsSealed ? new StreamLayout.Atomic(other) : other.MaterializedValueComputation; StreamLayout.IMaterializedValueNode comp; // TODO this optimization makes to GraphMatValueSpec tests fail, investigate and un-comment // if (IsKeepLeft(matFunc) && IsIgnorable(matComputationRight)) comp = matComputationLeft; // else if (IsKeepRight(matFunc) && IsIgnorable(matComputationLeft)) comp = matComputationRight; // else comp = new StreamLayout.Combine((x, y) => matFunc((T1)x, (T2)y), matComputationLeft, matComputationRight); comp = new StreamLayout.Combine((x, y) => matFunc((T1)x, (T2)y), matComputationLeft, matComputationRight); return new CompositeModule( subModules: modules1.Concat(modules2).ToImmutableArray(), shape: new AmorphousShape( Shape.Inlets.Concat(other.Shape.Inlets).ToImmutableArray(), Shape.Outlets.Concat(other.Shape.Outlets).ToImmutableArray()), downstreams: Downstreams.AddRange(other.Downstreams), upstreams: Upstreams.AddRange(other.Upstreams), materializedValueComputation: comp, attributes: Attributes.None); } /* // Commented out, part of the optimization mentioned above private static readonly RuntimeMethodHandle KeepRightMethodhandle = typeof (Keep).GetMethod(nameof(Keep.Right)).MethodHandle; private bool IsKeepRight<T1, T2, T3>(Func<T1, T2, T3> fn) { return fn.Method.IsGenericMethod && fn.Method.GetGenericMethodDefinition().MethodHandle.Value == KeepRightMethodhandle.Value; } private static readonly RuntimeMethodHandle KeepLeftMethodhandle = typeof(Keep).GetMethod(nameof(Keep.Left)).MethodHandle; private bool IsKeepLeft<T1, T2, T3>(Func<T1, T2, T3> fn) { return fn.Method.IsGenericMethod && fn.Method.GetGenericMethodDefinition().MethodHandle.Value == KeepLeftMethodhandle.Value; } private bool IsIgnorable(StreamLayout.IMaterializedValueNode computation) { if (computation is StreamLayout.Atomic) return IsIgnorable(((StreamLayout.Atomic) computation).Module); return (computation is StreamLayout.Combine || computation is StreamLayout.Transform) || !(computation is StreamLayout.Ignore); } private bool IsIgnorable(IModule module) { if (module is AtomicModule || module is EmptyModule) return true; if (module is CopiedModule) return IsIgnorable(((CopiedModule) module).CopyOf); if (module is CompositeModule) return IsIgnorable(((CompositeModule) module).MaterializedValueComputation); if (module is FusedModule) return IsIgnorable(((FusedModule) module).MaterializedValueComputation); throw new NotSupportedException($"Module of type {module.GetType()} is not supported by this method"); }*/ public IModule ComposeNoMaterialized(IModule that) { if (StreamLayout.IsDebug) StreamLayout.Validate(this); if (ReferenceEquals(this, that)) throw new ArgumentException("A module cannot be added to itself. You should pass a separate instance to Compose()."); if (SubModules.Contains(that)) throw new ArgumentException("An existing submodule cannot be added again. All contained modules must be unique."); var module1 = IsSealed ? ImmutableArray.Create<IModule>(this) : SubModules; var module2 = that.IsSealed ? ImmutableArray.Create(that) : that.SubModules; var matComputation = IsSealed ? new StreamLayout.Atomic(this) : MaterializedValueComputation; return new CompositeModule( subModules: module1.Concat(module2).ToImmutableArray(), shape: new AmorphousShape( Shape.Inlets.Concat(that.Shape.Inlets).ToImmutableArray(), Shape.Outlets.Concat(that.Shape.Outlets).ToImmutableArray()), downstreams: Downstreams.AddRange(that.Downstreams), upstreams: Upstreams.AddRange(that.Upstreams), materializedValueComputation: matComputation, attributes: Attributes.None); } public virtual IModule Nest() { return new CompositeModule( subModules: ImmutableArray.Create(this as IModule), shape: Shape, /* * Composite modules always maintain the flattened upstreams/downstreams map (i.e. they contain all the * layout information of all the nested modules). Copied modules break the nesting, scoping them to the * copied module. The MaterializerSession will take care of propagating the necessary Publishers and Subscribers * from the enclosed scope to the outer scope. */ downstreams: Downstreams, upstreams: Upstreams, /* * Wrapping like this shields the outer module from the details of the * materialized value computation of its submodules. */ materializedValueComputation: new StreamLayout.Atomic(this), attributes: Attributes.None); } public bool IsSealed => IsAtomic || IsCopied || IsFused || Attributes.AttributeList.Count() != 0; public virtual IImmutableDictionary<OutPort, InPort> Downstreams => ImmutableDictionary<OutPort, InPort>.Empty; public virtual IImmutableDictionary<InPort, OutPort> Upstreams => ImmutableDictionary<InPort, OutPort>.Empty; public virtual StreamLayout.IMaterializedValueNode MaterializedValueComputation => new StreamLayout.Atomic(this); public abstract Shape Shape { get; } public abstract IModule ReplaceShape(Shape shape); public abstract ImmutableArray<IModule> SubModules { get; } public abstract IModule CarbonCopy(); public abstract Attributes Attributes { get; } public abstract IModule WithAttributes(Attributes attributes); public int CompareTo(IModule other) => GetHashCode().CompareTo(other.GetHashCode()); } public sealed class EmptyModule : Module { public static readonly EmptyModule Instance = new EmptyModule(); private EmptyModule() { } public override Shape Shape => ClosedShape.Instance; public override bool IsAtomic => false; public override bool IsRunnable => false; public override StreamLayout.IMaterializedValueNode MaterializedValueComputation => StreamLayout.Ignore.Instance; public override IModule ReplaceShape(Shape shape) { if (shape is ClosedShape) return this; throw new NotSupportedException("Cannot replace the shape of empty module"); } public override IModule Compose(IModule other) => other; public override IModule Compose<T1, T2, T3>(IModule other, Func<T1, T2, T3> matFunc) { throw new NotSupportedException("It is invalid to combine materialized value with EmptyModule"); } public override IModule Nest() => this; public override ImmutableArray<IModule> SubModules { get; } = ImmutableArray<IModule>.Empty; public override IModule CarbonCopy() => this; public override Attributes Attributes => Attributes.None; public override IModule WithAttributes(Attributes attributes) { throw new NotSupportedException("EmptyModule cannot carry attributes"); } } public sealed class CopiedModule : Module { public CopiedModule(Shape shape, Attributes attributes, IModule copyOf) { Shape = shape; Attributes = attributes; CopyOf = copyOf; SubModules = ImmutableArray.Create(copyOf); } public override ImmutableArray<IModule> SubModules { get; } public override Attributes Attributes { get; } public IModule CopyOf { get; } public override Shape Shape { get; } public override bool IsCopied => true; public override StreamLayout.IMaterializedValueNode MaterializedValueComputation => new StreamLayout.Atomic(CopyOf); public override IModule ReplaceShape(Shape shape) { if (!ReferenceEquals(shape, Shape)) { if (!Shape.HasSamePortsAs(shape)) throw new ArgumentException("CopiedModule requires shape with same ports to replace", nameof(shape)); return CompositeModule.Create(this, shape); } return this; } public override IModule CarbonCopy() => new CopiedModule(Shape.DeepCopy(), Attributes, CopyOf); public override IModule WithAttributes(Attributes attributes) { if (!ReferenceEquals(attributes, Attributes)) return new CopiedModule(Shape, attributes, CopyOf); return this; } public override string ToString() => $"Copy({CopyOf})"; } public sealed class CompositeModule : Module { public CompositeModule(ImmutableArray<IModule> subModules, Shape shape, IImmutableDictionary<OutPort, InPort> downstreams, IImmutableDictionary<InPort, OutPort> upstreams, StreamLayout.IMaterializedValueNode materializedValueComputation, Attributes attributes) { SubModules = subModules; Shape = shape; Downstreams = downstreams; Upstreams = upstreams; MaterializedValueComputation = materializedValueComputation; Attributes = attributes; } public override IImmutableDictionary<InPort, OutPort> Upstreams { get; } public override IImmutableDictionary<OutPort, InPort> Downstreams { get; } public override Shape Shape { get; } public override Attributes Attributes { get; } public override ImmutableArray<IModule> SubModules { get; } public override StreamLayout.IMaterializedValueNode MaterializedValueComputation { get; } public override IModule ReplaceShape(Shape shape) { if (!ReferenceEquals(shape, Shape)) { if (!Shape.HasSamePortsAs(shape)) throw new ArgumentException("CombinedModule requires shape with same ports to replace", nameof(shape)); return new CompositeModule(SubModules, shape, Downstreams, Upstreams, MaterializedValueComputation, Attributes); } return this; } public override IModule CarbonCopy() => new CopiedModule(Shape.DeepCopy(), Attributes, this); public override IModule WithAttributes(Attributes attributes) => new CompositeModule(SubModules, Shape, Downstreams, Upstreams, MaterializedValueComputation, attributes); public static CompositeModule Create(Module module, Shape shape) { return new CompositeModule( new IModule[] {module}.ToImmutableArray(), shape, ImmutableDictionary<OutPort, InPort>.Empty, ImmutableDictionary<InPort, OutPort>.Empty, new StreamLayout.Atomic(module), Attributes.None ); } public override string ToString() { return $"\n Name: {Attributes.GetNameOrDefault("unnamed")}" + "\n Modules:" + $"\n {string.Join("\n ", SubModules.Select(m => m.Attributes.GetNameLifted() ?? m.ToString().Replace("\n", "\n ")))}" + $"\n Downstreams: {string.Join("", Downstreams.Select(kvp => $"\n {kvp.Key} -> {kvp.Value}"))}" + $"\n Upstreams: {string.Join("", Upstreams.Select(kvp => $"\n {kvp.Key} -> {kvp.Value}"))}"; } } public sealed class FusedModule : Module { public readonly Streams.Fusing.StructuralInfo Info; public FusedModule( ImmutableArray<IModule> subModules, Shape shape, IImmutableDictionary<OutPort, InPort> downstreams, IImmutableDictionary<InPort, OutPort> upstreams, StreamLayout.IMaterializedValueNode materializedValueComputation, Attributes attributes, Streams.Fusing.StructuralInfo info) { SubModules = subModules; Shape = shape; Downstreams = downstreams; Upstreams = upstreams; MaterializedValueComputation = materializedValueComputation; Attributes = attributes; Info = info; } public override bool IsFused => true; public override IImmutableDictionary<OutPort, InPort> Downstreams { get; } public override IImmutableDictionary<InPort, OutPort> Upstreams { get; } public override StreamLayout.IMaterializedValueNode MaterializedValueComputation { get; } public override Shape Shape { get; } public override ImmutableArray<IModule> SubModules { get; } public override Attributes Attributes { get; } public override IModule ReplaceShape(Shape shape) { if (!ReferenceEquals(shape, Shape)) { if (!shape.HasSamePortsAndShapeAs(Shape)) throw new ArgumentException("FusedModule requires shape with the same ports as existing one", nameof(shape)); return new FusedModule(SubModules, shape, Downstreams, Upstreams, MaterializedValueComputation, Attributes, Info); } return this; } public override IModule CarbonCopy() => new CopiedModule(Shape.DeepCopy(), Attributes, this); public override IModule WithAttributes(Attributes attributes) => new FusedModule(SubModules, Shape, Downstreams, Upstreams, MaterializedValueComputation, attributes, Info); public override string ToString() { return $"\n Name: {Attributes.GetNameOrDefault("unnamed")}" + "\n Modules:" + $"\n {string.Join("\n ", SubModules.Select(m => m.Attributes.GetNameLifted() ?? m.ToString().Replace("\n", "\n ")))}" + $"\n Downstreams: {string.Join("", Downstreams.Select(kvp => $"\n {kvp.Key} -> {kvp.Value}"))}" + $"\n Upstreams: {string.Join("", Upstreams.Select(kvp => $"\n {kvp.Key} -> {kvp.Value}"))}"; } } /// <summary> /// This is the only extension point for the sealed type hierarchy: composition /// (i.e. the module tree) is managed strictly within this file, only leaf nodes /// may be declared elsewhere. /// </summary> public abstract class AtomicModule : Module { public sealed override ImmutableArray<IModule> SubModules => ImmutableArray<IModule>.Empty; public sealed override IImmutableDictionary<OutPort, InPort> Downstreams => base.Downstreams; public sealed override IImmutableDictionary<InPort, OutPort> Upstreams => base.Upstreams; } public sealed class VirtualProcessor<T> : IProcessor<T, T> { #region internal classes internal interface ITermination { } internal struct Allowed : ITermination { public static readonly Allowed Instance = new Allowed(); } internal struct Completed : ITermination { public static readonly Completed Instance = new Completed(); } internal struct Failed : ITermination { public readonly Exception Reason; public Failed(Exception reason) : this() { Reason = reason; } } private sealed class Sub : AtomicCounterLong, ISubscription { private readonly ISubscription _subscription; private readonly AtomicReference<object> _subscriptionStatus; public Sub(ISubscription subscription, AtomicReference<object> subscriptionStatus) { _subscription = subscription; _subscriptionStatus = subscriptionStatus; } public void Request(long n) { var current = Current; while (true) { if (current < 0) _subscription.Request(n); else if (CompareAndSet(current, current + n)) ; else continue; break; } } public void Cancel() { _subscriptionStatus.Value = InnertSubscriber; _subscription.Cancel(); } public void CloseLatch() { var requested = GetAndSet(-1); if (requested > 0) _subscription.Request(requested); } } #endregion private static readonly CancellingSubscriber<T> InnertSubscriber = new CancellingSubscriber<T>(); private readonly AtomicReference<object> _subscriptionStatus = new AtomicReference<object>(); private readonly AtomicReference<ITermination> _terminationStatus = new AtomicReference<ITermination>(); public void Subscribe(ISubscriber<T> subscriber) { ReactiveStreamsCompliance.RequireNonNullSubscriber(subscriber); if (_subscriptionStatus.CompareAndSet(null, subscriber)) { /* wait for OnSubscribe */ } else { var status = _subscriptionStatus.Value; if (status is ISubscriber<T>) ReactiveStreamsCompliance.RejectAdditionalSubscriber(subscriber, "VirtualProcessor"); else if (status is Sub) { var sub = (Sub)status; try { _subscriptionStatus.Value = subscriber; ReactiveStreamsCompliance.TryOnSubscribe(subscriber, sub); sub.CloseLatch(); // allow onNext only now var terminationStatus = _terminationStatus.GetAndSet(Allowed.Instance); if (terminationStatus is Completed) ReactiveStreamsCompliance.TryOnComplete(subscriber); else if (terminationStatus is Failed) ReactiveStreamsCompliance.TryOnError(subscriber, ((Failed)terminationStatus).Reason); } catch (Exception) { sub.Cancel(); } } } } public void OnSubscribe(ISubscription subscription) { ReactiveStreamsCompliance.RequireNonNullSubscription(subscription); var wrapped = new Sub(subscription, _subscriptionStatus); if (_subscriptionStatus.CompareAndSet(null, wrapped)) { /* wait for subscriber */ } else { var value = _subscriptionStatus.Value; if (value is ISubscriber<T>) { var sub = (ISubscriber<T>)value; var terminationStatus = _terminationStatus.Value; if (terminationStatus is Allowed) { /* * There is a race condition here: if this thread reads the subscriptionStatus after * set set() in subscribe() but then sees the terminationStatus before the getAndSet() * is published then we will rely upon the downstream Subscriber for cancelling this * Subscription. I only mention this because the TCK requires that we handle this here * (since the manualSubscriber used there does not expose this behavior). */ subscription.Cancel(); } else { ReactiveStreamsCompliance.TryOnSubscribe(sub, wrapped); wrapped.CloseLatch(); // allow OnNext only now _terminationStatus.Value = Allowed.Instance; } } else if (value is ISubscription) subscription.Cancel(); // reject further Subscriptions } } public void OnNext(T element) { ReactiveStreamsCompliance.RequireNonNullElement(element); ReactiveStreamsCompliance.TryOnNext(_subscriptionStatus.Value as ISubscriber<T>, element); } public void OnError(Exception cause) { ReactiveStreamsCompliance.RequireNonNullException(cause); if (_terminationStatus.CompareAndSet(null, new Failed(cause))) { //let it be picked up by Subscribe() } else ReactiveStreamsCompliance.TryOnError(_subscriptionStatus.Value as ISubscriber<T>, cause); } public void OnComplete() { if (_terminationStatus.CompareAndSet(null, Completed.Instance)) { //let it be picked up by Subscribe() } else ReactiveStreamsCompliance.TryOnComplete(_subscriptionStatus.Value as ISubscriber<T>); } } internal abstract class MaterializerSession { public static readonly bool IsDebug = false; public class MaterializationPanicException : Exception { public MaterializationPanicException(Exception innerException) : base("Materialization aborted.", innerException) { } protected MaterializationPanicException(SerializationInfo info, StreamingContext context) : base(info, context) { } } protected readonly IModule TopLevel; protected readonly Attributes InitialAttributes; private readonly LinkedList<IDictionary<InPort, IUntypedSubscriber>> _subscribersStack = new LinkedList<IDictionary<InPort, IUntypedSubscriber>>(); private readonly LinkedList<IDictionary<OutPort, IUntypedPublisher>> _publishersStack = new LinkedList<IDictionary<OutPort, IUntypedPublisher>>(); private readonly IDictionary<StreamLayout.IMaterializedValueNode, LinkedList<IMaterializedValueSource>> _materializedValueSources = new Dictionary<StreamLayout.IMaterializedValueNode, LinkedList<IMaterializedValueSource>>(); /// <summary> /// Please note that this stack keeps track of the scoped modules wrapped in CopiedModule but not the CopiedModule /// itself. The reason is that the CopiedModule itself is only needed for the enterScope and exitScope methods but /// not elsewhere. For this reason they are just simply passed as parameters to those methods. /// /// The reason why the encapsulated (copied) modules are stored as mutable state to save subclasses of this class /// from passing the current scope around or even knowing about it. /// </summary> private readonly LinkedList<IModule> _moduleStack = new LinkedList<IModule>(); protected MaterializerSession(IModule topLevel, Attributes initialAttributes) { TopLevel = topLevel; InitialAttributes = initialAttributes; _subscribersStack.AddFirst(new Dictionary<InPort, IUntypedSubscriber>()); _publishersStack.AddFirst(new Dictionary<OutPort, IUntypedPublisher>()); _moduleStack.AddFirst(TopLevel); } private IDictionary<InPort, IUntypedSubscriber> Subscribers => _subscribersStack.First.Value; private IDictionary<OutPort, IUntypedPublisher> Publishers => _publishersStack.First.Value; private IModule CurrentLayout => _moduleStack.First.Value; ///<summary> /// Enters a copied module and establishes a scope that prevents internals to leak out and interfere with copies /// of the same module. /// We don't store the enclosing CopiedModule itself as state since we don't use it anywhere else than exit and enter /// </summary> private void EnterScope(CopiedModule enclosing) { _subscribersStack.AddFirst(new Dictionary<InPort, IUntypedSubscriber>()); _publishersStack.AddFirst(new Dictionary<OutPort, IUntypedPublisher>()); _moduleStack.AddFirst(enclosing.CopyOf); } /// <summary> /// Exits the scope of the copied module and propagates Publishers/Subscribers to the enclosing scope assigning /// them to the copied ports instead of the original ones (since there might be multiple copies of the same module /// leading to port identity collisions) /// We don't store the enclosing CopiedModule itself as state since we don't use it anywhere else than exit and enter /// </summary> private void ExitScope(CopiedModule enclosing) { var scopeSubscribers = Subscribers; var scopePublishers = Publishers; _subscribersStack.RemoveFirst(); _publishersStack.RemoveFirst(); _moduleStack.RemoveFirst(); // When we exit the scope of a copied module, pick up the Subscribers/Publishers belonging to exposed ports of // the original module and assign them to the copy ports in the outer scope that we will return to var inZip = enclosing.CopyOf.Shape.Inlets.Zip(enclosing.Shape.Inlets, (original, exposed) => new KeyValuePair<Inlet, Inlet>(original, exposed)); foreach (var kv in inZip) AssignPort(kv.Value, scopeSubscribers[kv.Key]); var outZip = enclosing.CopyOf.Shape.Outlets.Zip(enclosing.Shape.Outlets, (original, exposed) => new KeyValuePair<Outlet, Outlet>(original, exposed)); foreach (var kv in outZip) AssignPort(kv.Value, scopePublishers[kv.Key]); } public object Materialize() { if (TopLevel is EmptyModule) throw new InvalidOperationException("An empty module cannot be materialized (EmptyModule was given)"); if (!TopLevel.IsRunnable) throw new InvalidOperationException("The top level module cannot be materialized because it has unconnected ports"); try { return MaterializeModule(TopLevel, InitialAttributes.And(TopLevel.Attributes)); } catch (Exception cause) { // PANIC!!! THE END OF THE MATERIALIZATION IS NEAR! // Cancels all intermediate Publishers and fails all intermediate Subscribers. // (This is an attempt to clean up after an exception during materialization) var ex = new MaterializationPanicException(cause); foreach (var subMap in _subscribersStack) foreach (var subscriber in subMap.Values) { var subscribedType = UntypedSubscriber.ToTyped(subscriber).GetType().GetSubscribedType(); var publisher = typeof(ErrorPublisher<>).Instantiate(subscribedType, ex, string.Empty); UntypedPublisher.FromTyped(publisher).Subscribe(subscriber); } foreach (var pubMap in _publishersStack) foreach (var publisher in pubMap.Values) { var publishedType = UntypedPublisher.ToTyped(publisher).GetType().GetPublishedType(); var subscriber = typeof(CancellingSubscriber<>).Instantiate(publishedType); publisher.Subscribe(UntypedSubscriber.FromTyped(subscriber)); } throw; } } protected virtual Attributes MergeAttributes(Attributes parent, Attributes current) => parent.And(current); protected void RegisterSource(IMaterializedValueSource materializedSource) { if (IsDebug) Console.WriteLine($"Registering source {materializedSource}"); LinkedList<IMaterializedValueSource> sources; if (_materializedValueSources.TryGetValue(materializedSource.Computation, out sources)) sources.AddFirst(materializedSource); else _materializedValueSources.Add(materializedSource.Computation, new LinkedList<IMaterializedValueSource>(new[] { materializedSource })); } protected object MaterializeModule(IModule module, Attributes effectiveAttributes) { var materializedValues = new Dictionary<IModule, object>(); foreach (var submodule in module.SubModules) { var subEffectiveAttributes = MergeAttributes(effectiveAttributes, submodule.Attributes); GraphStageModule graphStageModule; Type stageType; if (((graphStageModule = submodule as GraphStageModule) != null) && (stageType = graphStageModule.Stage.GetType()).IsGenericType && stageType.GetGenericTypeDefinition() == typeof(MaterializedValueSource<>)) { var copy = new MaterializedValueSource<object>(graphStageModule.MaterializedValueComputation).CopySource(); RegisterSource(copy); MaterializeAtomic(copy.Module, subEffectiveAttributes, materializedValues); } else if (submodule.IsAtomic) MaterializeAtomic(submodule, subEffectiveAttributes, materializedValues); else if (submodule is CopiedModule) { var copied = submodule as CopiedModule; EnterScope(copied); materializedValues.Add(copied, MaterializeModule(copied, subEffectiveAttributes)); ExitScope(copied); } else materializedValues.Add(submodule, MaterializeComposite(submodule, subEffectiveAttributes)); } if (IsDebug) { Console.WriteLine("RESOLVING"); Console.WriteLine($" module = {module}"); Console.WriteLine($" computation = {module.MaterializedValueComputation}"); Console.WriteLine($" matValSrc = {_materializedValueSources}"); Console.WriteLine($" matVals = {materializedValues}"); } return ResolveMaterialized(module.MaterializedValueComputation, materializedValues, " "); } protected virtual object MaterializeComposite(IModule composite, Attributes effectiveAttributes) => MaterializeModule(composite, effectiveAttributes); protected abstract object MaterializeAtomic(IModule atomic, Attributes effectiveAttributes, IDictionary<IModule, object> materializedValues); private object ResolveMaterialized(StreamLayout.IMaterializedValueNode node, IDictionary<IModule, object> values, string indent) { if (IsDebug) Console.WriteLine($"{indent}{node}"); object result; if (node is StreamLayout.Atomic) { var atomic = (StreamLayout.Atomic) node; values.TryGetValue(atomic.Module, out result); } else if (node is StreamLayout.Combine) { var combine = (StreamLayout.Combine) node; result = combine.Combinator(ResolveMaterialized(combine.Left, values, indent + " "), ResolveMaterialized(combine.Right, values, indent + " ")); } else if (node is StreamLayout.Transform) { var transform = (StreamLayout.Transform) node; result = transform.Transformator(ResolveMaterialized(transform.Node, values, indent + " ")); } else result = null; if (IsDebug) Console.WriteLine($"{indent}result = {result}"); LinkedList<IMaterializedValueSource> sources; if (_materializedValueSources.TryGetValue(node, out sources)) { if (IsDebug) Console.WriteLine($"{indent}triggering sources {sources}"); _materializedValueSources.Remove(node); foreach (var source in sources) source.SetValue(result); } return result; } protected void AssignPort(InPort inPort, IUntypedSubscriber subscriber) { Subscribers[inPort] = subscriber; // Interface (unconnected) ports of the current scope will be wired when exiting the scope if (!CurrentLayout.InPorts.Contains(inPort)) { IUntypedPublisher publisher; if (Publishers.TryGetValue(CurrentLayout.Upstreams[inPort], out publisher)) publisher.Subscribe(subscriber); } } protected void AssignPort(OutPort outPort, IUntypedPublisher publisher) { Publishers[outPort] = publisher; // Interface (unconnected) ports of the current scope will be wired when exiting the scope if (!CurrentLayout.OutPorts.Contains(outPort)) { IUntypedSubscriber subscriber; if (Subscribers.TryGetValue(CurrentLayout.Downstreams[outPort], out subscriber)) publisher.Subscribe(subscriber); } } } }
// 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. //---------------------------------------------------------------------------------------- // // Description: // this internal class handles cache for xaml files which // want to reference local types. // //--------------------------------------------------------------------------------------- using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; using Microsoft.Build.Tasks.Windows; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using MS.Utility; namespace MS.Internal.Tasks { // <summary> // LocalReferenceFile // This class keeps xaml file path and whether it is localizable. // </summary> internal class LocalReferenceFile { private bool _localizable; private string _filePath; private string _linkAlias; private string _logicalName; private static LocalReferenceFile _empty = new LocalReferenceFile(String.Empty, false, String.Empty, String.Empty); private const char trueChar = 'T'; private const char falseChar = 'F'; private const char semiColonChar = ';'; internal LocalReferenceFile(string filepath, bool localizable, string linkAlias, string logicalName) { _localizable = localizable; _filePath = filepath; _linkAlias = linkAlias; _logicalName = logicalName; } internal bool Localizable { get { return _localizable; } } internal string FilePath { get { return _filePath; } } internal string LinkAlias { get { return _linkAlias; } } internal string LogicalName { get { return _logicalName; } } internal static LocalReferenceFile Empty { get { return _empty; } } // // Serialize the instance to a string so that it can saved into a cache file. // internal string Serialize() { string cacheText = String.Empty; if (!String.IsNullOrEmpty(FilePath)) { StringBuilder sb = new StringBuilder(); if (Localizable) { sb.Append(trueChar); } else { sb.Append(falseChar); } sb.Append(FilePath); sb.Append(semiColonChar); sb.Append(LinkAlias); sb.Append(semiColonChar); sb.Append(LogicalName); cacheText = sb.ToString(); } return cacheText; } // // Create instance from a cache text string. // internal static LocalReferenceFile Deserialize(string cacheInfo) { // cachInfo string must follow pattern like Localizable + FilePath. // Localizable contains one character. LocalReferenceFile lrf = null; if (!String.IsNullOrEmpty(cacheInfo)) { bool localizable; string filePath; string linkAlias; string logicalName; string[] subStrs = cacheInfo.Split(semiColonChar); filePath = subStrs[0]; linkAlias = subStrs[1]; logicalName = subStrs[2]; localizable = (filePath[0] == trueChar) ? true : false; filePath = filePath.Substring(1); lrf = new LocalReferenceFile(filePath, localizable, linkAlias, logicalName); } return lrf; } } // <summary> // CompilerLocalReference // </summary> internal class CompilerLocalReference { // <summary> // ctor of CompilerLocalReference // </summary> internal CompilerLocalReference(string localCacheFile, ITaskFileService taskFileService) { _localCacheFile = localCacheFile; _taskFileService = taskFileService; } #region internal methods // <summary> // Detect whether the local cache file exists or not. // </summary> // <returns></returns> internal bool CacheFileExists() { return _taskFileService.Exists(_localCacheFile); } // // Clean up the state file. // internal void CleanupCache() { if (CacheFileExists()) { _taskFileService.Delete(_localCacheFile); } } // // Save the local reference related information from MarkupCompilePass1 task to cache file. // internal bool SaveCacheInformation(MarkupCompilePass1 mcPass1) { Debug.Assert(String.IsNullOrEmpty(_localCacheFile) != true, "_localCacheFile must not be empty."); Debug.Assert(mcPass1 != null, "A valid instance of MarkupCompilePass1 must be passed to method SaveCacheInformation."); bool bSuccess = false; // Transfer the cache related information from mcPass1 to this instance. LocalApplicationFile = mcPass1.LocalApplicationFile; LocalMarkupPages = mcPass1.LocalMarkupPages; // Save the cache information to the cache file. MemoryStream memStream = new MemoryStream(); // using Disposes the StreamWriter when it ends. Disposing the StreamWriter // also closes the underlying MemoryStream. Furthermore, don't add BOM here // since TaskFileService.WriteFile adds it. using (StreamWriter sw = new StreamWriter(memStream, new UTF8Encoding(false))) { // Write InternalTypeHelperFile only when Pass1 asks Pass2 to do further check. if (mcPass1.FurtherCheckInternalTypeHelper) { sw.WriteLine(mcPass1.InternalTypeHelperFile); } else { sw.WriteLine(String.Empty); } // Write the ApplicationFile for Pass2 compilation. if (LocalApplicationFile == null) { sw.WriteLine(String.Empty); } else { sw.WriteLine(LocalApplicationFile.Serialize()); } if (LocalMarkupPages != null && LocalMarkupPages.Length > 0) { for (int i = 0; i < LocalMarkupPages.Length; i++) { sw.WriteLine(LocalMarkupPages[i].Serialize( )); } } sw.Flush(); _taskFileService.WriteFile(memStream.ToArray(), _localCacheFile); bSuccess = true; } return bSuccess; } // // Read the Local Reference cache file, load the cached information // to the corresponding data fields in this class. // internal bool LoadCacheFile() { Debug.Assert(String.IsNullOrEmpty(_localCacheFile) != true, "_localCacheFile must not be empty."); bool loadSuccess = false; Stream stream = _taskFileService.GetContent(_localCacheFile); // using Disposes the StreamReader when it ends. Disposing the StreamReader // also closes the underlying MemoryStream. Don't look for BOM at the beginning // of the stream, since we don't add it when writing. TaskFileService takes care // of this. using (StreamReader srCache = new StreamReader(stream, false)) { // The first line must be for InternalTypeHelperFile. // The second line is for Local Application Defintion file. // For Library, the second line is an empty line. InternalTypeHelperFile = srCache.ReadLine(); string lineText; lineText = srCache.ReadLine(); LocalApplicationFile = LocalReferenceFile.Deserialize(lineText); ArrayList alMarkupPages = new ArrayList(); while (srCache.EndOfStream != true) { lineText = srCache.ReadLine(); LocalReferenceFile lrf = LocalReferenceFile.Deserialize(lineText); if (lrf != null) { alMarkupPages.Add(lrf); } } if (alMarkupPages.Count > 0) { LocalMarkupPages = (LocalReferenceFile []) alMarkupPages.ToArray(typeof(LocalReferenceFile)); } loadSuccess = true; } return loadSuccess; } #endregion #region internal properties internal string CacheFilePath { get { return _localCacheFile; } } internal LocalReferenceFile LocalApplicationFile { get { return _localApplicationFile; } set { _localApplicationFile = value; } } internal LocalReferenceFile[] LocalMarkupPages { get { return _localMarkupPages; } set { _localMarkupPages = value; } } // // InternalTypeHelper file path. // // Since Pass2 task doesn't know the code language, it could not generate the real // InternalTypeHelper code file path on the fly. // The real file path would be passed from Pass1 task to Pass2 through the cache file. // // If this file path is set in the cache file, it means Pass1 asks Passs2 to do the further // check for this file to see if it is really required, if this file is required for the assembly, // Pass2 then adds it to the appropriate output Item, otherwise, Pass2 just deletes this file. // // If the path is empty, this means Pass1 has already known how to handle the file correctly, // no further check is required in Pass2. // internal string InternalTypeHelperFile { get { return _internalTypeHelperFile; } set { _internalTypeHelperFile = value; } } #endregion #region private data private LocalReferenceFile _localApplicationFile; private LocalReferenceFile[] _localMarkupPages; private string _localCacheFile; private string _internalTypeHelperFile = String.Empty; private ITaskFileService _taskFileService = null; #endregion } }
/* * 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 OfficeOpenXml; using s2industries.ZUGFeRD; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace ZUGFeRDToExcel { public class InvoiceConverter { internal class PosColumns { public static readonly string DESCRIPTION = "A"; public static readonly string SELLER_ASSIGNED_ID = "B"; public static readonly string NET_UNIT_PRICE = "C"; public static readonly string GROSS_UNIT_PRICE = "D"; public static readonly string QUANTITY = "E"; public static readonly string LINE_TOTAL_AMOUNT = "F"; public static readonly string TRADE_ALLOWANCE_CHARGE_0 = "G"; public static readonly string TRADE_ALLOWANCE_CHARGE_1 = "H"; public static readonly string TRADE_ALLOWANCE_CHARGE_2 = "I"; public static readonly string TRADE_ALLOWANCE_CHARGE_TOTAL = "J"; public static readonly string ADDITIONAL_REFERENCE = "K"; } internal class HeadColumns { public static readonly string DESCRIPTION = "A"; public static readonly string VALUE = "B"; public static readonly string ANALYSIS = "C"; public static readonly string EXPLANATION = "D"; } public static void ConvertZUGFeRDToExcel(string inputPath, string outputPath) { InvoiceDescriptor desc = InvoiceDescriptor.Load(inputPath); ConvertZUGFeRDToExcel(desc, outputPath); } // !ConvertZUGFeRDToExcel() public static void ConvertZUGFeRDToExcel(InvoiceDescriptor descriptor, string outputPath) { // create/ open Excel file ExcelPackage pck = new ExcelPackage(new FileInfo(outputPath)); // make sure that our Excel file is clean for (int j = 1; j <= pck.Workbook.Worksheets.Count;) { if (pck.Workbook.Worksheets[j].Name.Equals("Positions")) { pck.Workbook.Worksheets.Delete(j); } else if (pck.Workbook.Worksheets[j].Name.Equals("Head")) { pck.Workbook.Worksheets.Delete(j); } else { j++; } } ExcelWorksheet positionWorksheet = pck.Workbook.Worksheets.Add("Positions"); new ExcelCell(positionWorksheet, PosColumns.DESCRIPTION, 1).setText("Name").setBold().setBorderBottom(); new ExcelCell(positionWorksheet, PosColumns.SELLER_ASSIGNED_ID, 1).setText("Seller assigned Id").setBold().setBorderBottom(); new ExcelCell(positionWorksheet, PosColumns.NET_UNIT_PRICE, 1).setText("Net Unit Price").setBold().setBorderBottom(); new ExcelCell(positionWorksheet, PosColumns.GROSS_UNIT_PRICE, 1).setText("Gross Unit Price").setBold().setBorderBottom(); new ExcelCell(positionWorksheet, PosColumns.QUANTITY, 1).setText("Billed Quantity").setBold().setBorderBottom(); new ExcelCell(positionWorksheet, PosColumns.LINE_TOTAL_AMOUNT, 1).setText("Line Total Amount").setBold().setBorderBottom(); new ExcelCell(positionWorksheet, PosColumns.TRADE_ALLOWANCE_CHARGE_0, 1).setText("Trade Allowance Charge per Unit (0)").setBold().setBorderBottom(); new ExcelCell(positionWorksheet, PosColumns.TRADE_ALLOWANCE_CHARGE_1, 1).setText("Trade Allowance Charge per Unit (1)").setBold().setBorderBottom(); new ExcelCell(positionWorksheet, PosColumns.TRADE_ALLOWANCE_CHARGE_2, 1).setText("Trade Allowance Charge per Unit (2)").setBold().setBorderBottom(); new ExcelCell(positionWorksheet, PosColumns.TRADE_ALLOWANCE_CHARGE_TOTAL, 1).setText("Trade Allowance Charge Total").setBold().setBorderBottom(); new ExcelCell(positionWorksheet, PosColumns.ADDITIONAL_REFERENCE, 1).setText("Reference").setBold().setBorderBottom(); string cellForLineTotal = ""; int i = 2; foreach (TradeLineItem lineItem in descriptor.TradeLineItems) { if (!String.IsNullOrEmpty(lineItem.Name)) { new ExcelCell(positionWorksheet, PosColumns.DESCRIPTION, i).setText(lineItem.Name); } else if ((lineItem.AssociatedDocument != null) && (lineItem.AssociatedDocument.Notes.Count > 0)) { new ExcelCell(positionWorksheet, PosColumns.DESCRIPTION, i).setText(lineItem.AssociatedDocument.Notes[0].Content); } new ExcelCell(positionWorksheet, PosColumns.SELLER_ASSIGNED_ID, i).setText(lineItem.SellerAssignedID); new ExcelCell(positionWorksheet, PosColumns.NET_UNIT_PRICE, i).setValue(lineItem.NetUnitPrice, "0.00"); new ExcelCell(positionWorksheet, PosColumns.GROSS_UNIT_PRICE, i).setValue(lineItem.GrossUnitPrice, "0.00"); new ExcelCell(positionWorksheet, PosColumns.QUANTITY, i).setValue(lineItem.BilledQuantity, "0.00"); if (lineItem.LineTotalAmount.HasValue) { new ExcelCell(positionWorksheet, PosColumns.LINE_TOTAL_AMOUNT, i).setValue(lineItem.LineTotalAmount.Value, "0.00"); } foreach (AdditionalReferencedDocument ard in lineItem.AdditionalReferencedDocuments) { if (ard.ReferenceTypeCode == ReferenceTypeCodes.IV) { new ExcelCell(positionWorksheet, PosColumns.ADDITIONAL_REFERENCE, i).setText(ard.ID); } } new ExcelCell(positionWorksheet, PosColumns.TRADE_ALLOWANCE_CHARGE_0, i).setValue(0m, "0.00").formatWithDecimals(); new ExcelCell(positionWorksheet, PosColumns.TRADE_ALLOWANCE_CHARGE_1, i).setValue(0m, "0.00").formatWithDecimals(); new ExcelCell(positionWorksheet, PosColumns.TRADE_ALLOWANCE_CHARGE_2, i).setValue(0m, "0.00").formatWithDecimals(); for (int j = 0; j < lineItem.TradeAllowanceCharges.Count; j++) { TradeAllowanceCharge tac = lineItem.TradeAllowanceCharges[j]; string column = PosColumns.TRADE_ALLOWANCE_CHARGE_0; if (j == 1) { column = PosColumns.TRADE_ALLOWANCE_CHARGE_1; } else if (j == 2) { column = PosColumns.TRADE_ALLOWANCE_CHARGE_2; } if (tac.ChargeIndicator == false) // Allowance { new ExcelCell(positionWorksheet, column, i).setValue(-tac.ActualAmount, "0.00"); } else { new ExcelCell(positionWorksheet, column, i).setValue(tac.ActualAmount, "0.00"); } } new ExcelCell(positionWorksheet, PosColumns.TRADE_ALLOWANCE_CHARGE_TOTAL, i).setFormula(String.Format("=SUM({0}{3}:{1}{3})*{2}{3}", PosColumns.TRADE_ALLOWANCE_CHARGE_0, PosColumns.TRADE_ALLOWANCE_CHARGE_2, PosColumns.QUANTITY, i)) .formatWithDecimals() .setColor(ExcelColors.Green); i += 1; } i += 2; ExcelCell cell = new ExcelCell(positionWorksheet, PosColumns.LINE_TOTAL_AMOUNT, i).setFormula(String.Format("=sum({0}2:{0}{1})", PosColumns.LINE_TOTAL_AMOUNT, i - 3)).setColor(ExcelColors.Green).formatWithDecimals(); cellForLineTotal = cell.getCellAddress(); new ExcelCell(positionWorksheet, PosColumns.TRADE_ALLOWANCE_CHARGE_TOTAL, i + 2).setFormula(String.Format("=sum({0}{1}:{0}{2})", PosColumns.TRADE_ALLOWANCE_CHARGE_TOTAL, 2, i)).setColor(ExcelColors.Green).formatWithDecimals(); positionWorksheet.Cells[positionWorksheet.Dimension.Address].AutoFilter = true; positionWorksheet.View.FreezePanes(2, 1); positionWorksheet.Cells[positionWorksheet.Dimension.Address].AutoFitColumns(); // ---- head area ---- ExcelWorksheet headWorksheet = pck.Workbook.Worksheets.Add("Head"); i = 1; // output allowance charges List<string> cellsForAllowanceChargesPerVAT = new List<string>(); string cellForAllowanceAnalysis = ""; new ExcelCell(headWorksheet, HeadColumns.DESCRIPTION, i).setText("Allowances and charges").setBold().joinColumns("B").setAlignCenter(); i += 1; foreach (TradeAllowanceCharge tac in descriptor.TradeAllowanceCharges) { new ExcelCell(headWorksheet, HeadColumns.DESCRIPTION, i).setText("Base amount"); new ExcelCell(headWorksheet, HeadColumns.VALUE, i).setValue(tac.BasisAmount, "0.00"); i += 1; if (tac.ChargeIndicator == false) { new ExcelCell(headWorksheet, HeadColumns.DESCRIPTION, i).setText("Allowance amount"); new ExcelCell(headWorksheet, HeadColumns.VALUE, i).setValue(-tac.ActualAmount, "0.00"); } else { new ExcelCell(headWorksheet, HeadColumns.DESCRIPTION, i).setText("Charge amount"); new ExcelCell(headWorksheet, HeadColumns.VALUE, i).setValue(tac.ActualAmount, "0.00"); } new ExcelCell(headWorksheet, HeadColumns.EXPLANATION, i).setText("Negative value indicates allowance (discount), position value indicates (sur)charge").setItalic(); cellForAllowanceAnalysis = String.Format("{0}{1}", HeadColumns.ANALYSIS, i); // placeholder for later cellsForAllowanceChargesPerVAT.Add(String.Format("{0}{1}", HeadColumns.VALUE, i)); i += 1; new ExcelCell(headWorksheet, HeadColumns.DESCRIPTION, i).setText("Tax percent"); new ExcelCell(headWorksheet, HeadColumns.VALUE, i).setValue(tac.Tax.Percent, "0.00"); i += 1; } // analysis of allowance charges string _calculation = "="; foreach(string _cell in cellsForAllowanceChargesPerVAT) { _calculation += _cell + "+"; } _calculation = _calculation.Substring(0, _calculation.Length - 1); new ExcelCell(headWorksheet, cellForAllowanceAnalysis).setFormula(_calculation).formatWithDecimals().setColor(ExcelColors.Green); i += 1; // output taxes List<string> cellsForTaxes = new List<string>(); string cellForTaxAnalysis = ""; new ExcelCell(headWorksheet, HeadColumns.DESCRIPTION, i).setText("Tax").setBold().joinColumns("B").setAlignCenter(); i += 1; foreach (Tax tax in descriptor.Taxes) { new ExcelCell(headWorksheet, HeadColumns.DESCRIPTION, i).setText("Base Amount"); new ExcelCell(headWorksheet, HeadColumns.VALUE, i).setValue(tax.BasisAmount, "0.00"); i += 1; new ExcelCell(headWorksheet, HeadColumns.DESCRIPTION, i).setText("Tax percent"); new ExcelCell(headWorksheet, HeadColumns.VALUE, i).setValue(tax.Percent, "0.00"); i += 1; new ExcelCell(headWorksheet, HeadColumns.DESCRIPTION, i).setText("Tax amount"); new ExcelCell(headWorksheet, HeadColumns.VALUE, i).setValue(tax.TaxAmount, "0.00"); cellsForTaxes.Add(String.Format("{0}{1}", HeadColumns.VALUE, i)); cellForTaxAnalysis = String.Format("{0}{1}", HeadColumns.ANALYSIS, i); i += 1; } // analysis of taxes _calculation = "="; foreach(string _cell in cellsForTaxes) { _calculation += _cell + "+"; } _calculation = _calculation.Substring(0, _calculation.Length - 1); new ExcelCell(headWorksheet, cellForTaxAnalysis).setFormula(_calculation).formatWithDecimals().setColor(ExcelColors.Green); i += 1; new ExcelCell(headWorksheet, HeadColumns.DESCRIPTION, i).setText("Totals").setBold().joinColumns("B").setAlignCenter(); i += 1; new ExcelCell(headWorksheet, HeadColumns.DESCRIPTION, i).setText("Line total amount"); new ExcelCell(headWorksheet, HeadColumns.VALUE, i).setValue(descriptor.LineTotalAmount, "0.00"); string cellForLineTotalAmount = new ExcelCell(headWorksheet, HeadColumns.ANALYSIS, i).setFormula(String.Format("={0}", cellForLineTotal)).formatWithDecimals().setColor(ExcelColors.Green).getCellAddress(); i += 1; new ExcelCell(headWorksheet, HeadColumns.DESCRIPTION, i).setText("Charge total amount"); new ExcelCell(headWorksheet, HeadColumns.VALUE, i).setValue(descriptor.ChargeTotalAmount.Value, "0.00"); i += 1; new ExcelCell(headWorksheet, HeadColumns.DESCRIPTION, i).setText("Allowance total amount"); new ExcelCell(headWorksheet, HeadColumns.VALUE, i).setValue(descriptor.AllowanceTotalAmount.Value, "0.00"); string cellForAllowanceTotal = new ExcelCell(headWorksheet, HeadColumns.ANALYSIS, i).setFormula(String.Format("={0}", cellForAllowanceAnalysis)).formatWithDecimals().setColor(ExcelColors.Green).getCellAddress(); i += 1; new ExcelCell(headWorksheet, HeadColumns.DESCRIPTION, i).setText("Tax basis amount"); new ExcelCell(headWorksheet, HeadColumns.VALUE, i).setValue(descriptor.TaxBasisAmount.Value, "0.00"); string cellForTaxBasisAmount = new ExcelCell(headWorksheet, HeadColumns.ANALYSIS, i).setFormula(String.Format("={0}+{1}", cellForLineTotalAmount, cellForAllowanceTotal)).formatWithDecimals().setColor(ExcelColors.Green).getCellAddress(); i += 1; new ExcelCell(headWorksheet, HeadColumns.DESCRIPTION, i).setText("Tax total amount"); new ExcelCell(headWorksheet, HeadColumns.VALUE, i).setValue(descriptor.TaxTotalAmount, "0.00"); string cellForTaxTotalAmount = new ExcelCell(headWorksheet, HeadColumns.ANALYSIS, i).setFormula(String.Format("={0}", cellForTaxAnalysis)).formatWithDecimals().setColor(ExcelColors.Green).getCellAddress(); i += 1; new ExcelCell(headWorksheet, HeadColumns.DESCRIPTION, i).setText("Grand total amount"); new ExcelCell(headWorksheet, HeadColumns.VALUE, i).setValue(descriptor.GrandTotalAmount, "0.00"); new ExcelCell(headWorksheet, HeadColumns.ANALYSIS, i).setFormula(String.Format("={0}+{1}", cellForTaxBasisAmount, cellForTaxTotalAmount)).formatWithDecimals().setColor(ExcelColors.Green).getCellAddress(); headWorksheet.Cells[headWorksheet.Dimension.Address].AutoFitColumns(); pck.Save(); } // !ConvertZUGFeRDToExcel() } }
namespace ResXManager.Translators { using System; using System.Collections.Generic; using System.Composition; using System.Diagnostics; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Runtime.Serialization; using System.Text; using System.Threading; using System.Threading.Tasks; using ResXManager.Infrastructure; using TomsToolbox.Essentials; [Export(typeof(ITranslator)), Shared] public class AzureTranslator : TranslatorBase { private static readonly Uri _uri = new("https://www.microsoft.com/en-us/translator/"); // Azure has a 5000-character translation limit across all Texts in a single request private const int MaxCharsPerApiCall = 5000; private const int MaxItemsPerApiCall = 100; public AzureTranslator() : base("Azure", "Azure", _uri, GetCredentials()) { } [DataMember] public bool AutoDetectHtml { get; set; } = true; [DataMember] public int MaxCharactersPerMinute { get; set; } = 33300; protected override async Task Translate(ITranslationSession translationSession) { var authenticationKey = AuthenticationKey; if (authenticationKey.IsNullOrEmpty()) { translationSession.AddMessage("Azure Translator requires API key."); return; } using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", authenticationKey); if (!Region.IsNullOrEmpty()) { client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Region", Region); } var throttle = new Throttle(MaxCharactersPerMinute, translationSession.CancellationToken); var itemsByLanguage = translationSession.Items.GroupBy(item => item.TargetCulture); foreach (var languageGroup in itemsByLanguage) { var cultureKey = languageGroup.Key; var targetLanguage = cultureKey.Culture ?? translationSession.NeutralResourcesLanguage; var itemsByTextType = languageGroup.GroupBy(GetTextType); foreach (var textTypeGroup in itemsByTextType) { var textType = textTypeGroup.Key; foreach (var sourceItems in SplitIntoChunks(translationSession, textTypeGroup)) { if (!sourceItems.Any()) break; var sourceStrings = sourceItems .Select(item => item.Source) .Select(RemoveKeyboardShortcutIndicators) .ToList(); await throttle.Tick(sourceItems).ConfigureAwait(false); if (translationSession.IsCanceled) return; var uri = new Uri($"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from={translationSession.SourceLanguage.IetfLanguageTag}&to={targetLanguage.IetfLanguageTag}&textType={textType}"); using var content = CreateRequestContent(sourceStrings); var response = await client.PostAsync(uri, content, translationSession.CancellationToken).ConfigureAwait(false); response.EnsureSuccessStatusCode(); var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); using (var reader = new StreamReader(stream, Encoding.UTF8)) { var translations = JsonConvert.DeserializeObject<List<AzureTranslationResponse>>(reader.ReadToEnd()); if (translations != null) { await translationSession.MainThread.StartNew(() => ReturnResults(sourceItems, translations)).ConfigureAwait(false); } } } } } } } [DataMember(Name = "AuthenticationKey")] public string? SerializedAuthenticationKey { get => SaveCredentials ? Credentials[0].Value : null; set => Credentials[0].Value = value; } [DataMember(Name = "Region")] public string? Region { get => Credentials[1].Value; set => Credentials[1].Value = value; } private string? AuthenticationKey => Credentials[0].Value; private void ReturnResults(IEnumerable<ITranslationItem> items, IEnumerable<AzureTranslationResponse> responses) { foreach (var tuple in Enumerate.AsTuples(items, responses)) { var response = tuple.Item2; var translationItem = tuple.Item1; var translations = response.Translations; if (translations == null) continue; foreach (var match in translations) { translationItem.Results.Add(new TranslationMatch(this, match.Text, Ranking)); } } } private static IList<ICredentialItem> GetCredentials() { return new ICredentialItem[] { new CredentialItem("AuthenticationKey", "Key"), new CredentialItem("Region", "Region", false) }; } private static HttpContent CreateRequestContent(IEnumerable<string> texts) { var payload = texts.Select(text => new { Text = text }).ToArray(); var serialized = JsonConvert.SerializeObject(payload); Debug.Assert(serialized != null, nameof(serialized) + " != null"); var serializedBytes = Encoding.UTF8.GetBytes(serialized); var byteContent = new ByteArrayContent(serializedBytes); byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); return byteContent; } private string GetTextType(ITranslationItem item) { return AutoDetectHtml && item.Source.ContainsHtml() ? "html" : "plain"; } private static IEnumerable<ICollection<ITranslationItem>> SplitIntoChunks(ITranslationSession translationSession, IEnumerable<ITranslationItem> items) { var chunk = new List<ITranslationItem>(); var chunkTextLength = 0; foreach (var item in items) { var textLength = item.Source.Length; if (textLength > MaxCharsPerApiCall) { translationSession.AddMessage($"Resource length exceeds Azure's {MaxCharsPerApiCall}-character limit: {item.Source.Substring(0, 20)}..."); continue; } if ((chunk.Count == MaxItemsPerApiCall) || ((chunkTextLength + textLength) > MaxCharsPerApiCall)) { yield return chunk; chunk = new List<ITranslationItem>(); chunkTextLength = 0; } chunk.Add(item); chunkTextLength += textLength; } yield return chunk; } private class Throttle { private readonly int _maxCharactersPerMinute; private readonly CancellationToken _cancellationToken; private readonly List<Tuple<DateTime, int>> _characterCounts = new(); public Throttle(int maxCharactersPerMinute, CancellationToken cancellationToken) { _maxCharactersPerMinute = maxCharactersPerMinute; _cancellationToken = cancellationToken; } public async Task Tick(ICollection<ITranslationItem> sourceItems) { var newCharacterCount = sourceItems.Sum(item => item.Source.Length); var threshold = DateTime.Now.Subtract(TimeSpan.FromMinutes(1)); _characterCounts.RemoveAll(t => t.Item1 < threshold); var totalCharacterCount = newCharacterCount; for (var i = _characterCounts.Count - 1; i >= 0; i--) { var tuple = _characterCounts[i]; if (totalCharacterCount + tuple.Item2 > _maxCharactersPerMinute) { var nextCallTime = tuple.Item1.AddMinutes(1); var millisecondsToDelay = (int)Math.Ceiling((nextCallTime - DateTime.Now).TotalMilliseconds); if (millisecondsToDelay > 0) { await Task.Delay(millisecondsToDelay, _cancellationToken).ConfigureAwait(false); } break; } totalCharacterCount += tuple.Item2; } _characterCounts.Add(new Tuple<DateTime, int>(DateTime.Now, newCharacterCount)); } } } }
//----------------------------------------------------------------------- // Copyright (c) Microsoft Open Technologies, Inc. // All Rights Reserved // Apache License 2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //----------------------------------------------------------------------- namespace System.IdentityModel.Tokens { using System.Collections.Generic; using System.Configuration; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IdentityModel.Configuration; using System.IdentityModel.Selectors; using System.Security.Claims; using System.Security.Cryptography.X509Certificates; using System.ServiceModel.Security; using System.Xml; using Attributes = System.IdentityModel.Tokens.JwtConfigurationStrings.Attributes; using AttributeValues = System.IdentityModel.Tokens.JwtConfigurationStrings.AttributeValues; using Elements = System.IdentityModel.Tokens.JwtConfigurationStrings.Elements; /// <summary> /// Provides a location for settings that control how the <see cref="JwtSecurityTokenHandler"/> validates or creates a <see cref="JwtSecurityToken"/>. /// </summary> /// <remarks>These values have precedence over <see cref="SecurityTokenHandler.Configuration"/>.</remarks> [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Suppressed for private or internal fields.")] public class JwtSecurityTokenRequirement { /// <summary> /// The default clock skew. /// </summary> public static readonly Int32 DefaultClockSkewInSeconds = 300; /// <summary> /// The default maximum size of a token that the runtime will process. /// </summary> public static readonly Int32 DefaultMaximumTokenSizeInBytes = 2 * 1024 * 1024; // 2MB // The defaults will only be used if some verification properties are set in config and others are not private X509CertificateValidator certificateValidator; private X509RevocationMode defaultRevocationMode = X509RevocationMode.Online; private StoreLocation defaultStoreLocation = StoreLocation.LocalMachine; private int defaultTokenLifetimeInMinutes = 600; private X509CertificateValidationMode defaultValidationMode = X509CertificateValidationMode.PeerOrChainTrust; private int maxTokenSizeInBytes = 2 * 1024 * 1024; private string nameClaimType; private string roleClaimType; // This indicates that the clockSkew was never set //private TimeSpan? maxClockSkew = null; private Int32 clockSkewInSeconds = JwtSecurityTokenRequirement.DefaultClockSkewInSeconds; /// <summary> /// Initializes a new instance of the <see cref="JwtSecurityTokenRequirement"/> class. /// </summary> public JwtSecurityTokenRequirement() { } /// <summary> /// Initializes a new instance of the <see cref="JwtSecurityTokenRequirement"/> class. /// </summary> /// <remarks> /// <para>A single XML element is expected with up to four optional attributes: {'expected values'} and up to five optional child elements.</para> /// <para>&lt;jwtSecurityTokenRequirement</para> /// <para>&#160;&#160;&#160;&#160;issuerCertificateRevocationMode: {NoCheck, OnLine, OffLine}</para> /// <para>&#160;&#160;&#160;&#160;issuerCertificateTrustedStoreLocation: {CurrentUser, LocalMachine}</para> /// <para>&#160;&#160;&#160;&#160;issuerCertificateValidator: type derived from <see cref="X509CertificateValidator"/></para> /// <para>&#160;&#160;&#160;&#160;issuerCertificateValidationMode: {ChainTrust, Custom, None, PeerTrust, PeerOrChainTrust}</para> /// <para>></para> /// <para>&#160;&#160;&#160;&#160;&lt;nameClaimType value = 'user defined type'/></para> /// <para>&#160;&#160;&#160;&#160;&lt;roleClaimType value = 'user defined type'/></para> /// <para>&#160;&#160;&#160;&#160;&lt;defaultTokenLifetimeInMinutes value = 'uint'/></para> /// <para>&#160;&#160;&#160;&#160;&lt;maxTokenSizeInBytes value = 'uint'/></para> /// <para>&#160;&#160;&#160;&#160;&lt;maxClockSkewInMinutes value = 'uint'/></para> /// <para>&lt;/jwtSecurityTokenRequirement></para> /// </remarks> /// <param name="element">The <see cref="XmlElement"/> to be parsed.</param> /// <exception cref="ArgumentNullException">'element' is null.</exception> /// <exception cref="ConfigurationErrorsException"><see cref="XmlElement.LocalName"/> is not 'jwtSecurityTokenRequirement'.</exception> /// <exception cref="ConfigurationErrorsException">if a <see cref="XmlAttribute.LocalName"/> is not expected.</exception> /// <exception cref="ConfigurationErrorsException">a <see cref="XmlAttribute.Value"/> of &lt;jwtSecurityTokenRequirement> is null or whitespace.</exception> /// <exception cref="ConfigurationErrorsException">a <see cref="XmlAttribute.Value"/> is not expected.</exception> /// <exception cref="ConfigurationErrorsException">if the <see cref="XmlElement.LocalName"/> of a child element of &lt;jwtSecurityTokenRequirement> is not expected.</exception> /// <exception cref="ConfigurationErrorsException">if a child element of &lt;jwtSecurityTokenRequirement> is not well formed.</exception> /// <exception cref="ConfigurationErrorsException">if the 'issuerCertificateValidationMode' == 'Custom' and a 'issuerCertificateValidator' attribute was not specified.</exception> /// <exception cref="ConfigurationErrorsException">if the runtime was not able to create the type specified by a the 'issuerCertificateValidator' attribute.</exception> /// <exception cref="ConfigurationErrorsException">if a child element of &lt;jwtSecurityTokenRequirement> is not well formed.</exception> [SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1118:ParameterMustNotSpanMultipleLines", Justification = "Reviewed. Suppression is OK here.")] public JwtSecurityTokenRequirement(XmlElement element) { if (element == null) { throw new ArgumentNullException("element"); } if (element.LocalName != Elements.JwtSecurityTokenRequirement) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10601, element.LocalName, element.OuterXml)); } X509RevocationMode revocationMode = this.defaultRevocationMode; X509CertificateValidationMode certificateValidationMode = this.defaultValidationMode; StoreLocation trustedStoreLocation = this.defaultStoreLocation; string customValidator = null; bool createCertificateValidator = false; HashSet<string> itemsProcessed = new HashSet<string>(); foreach (XmlAttribute attribute in element.Attributes) { if (string.IsNullOrWhiteSpace(attribute.Value)) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10600, attribute.LocalName, element.OuterXml)); } if (itemsProcessed.Contains(attribute.Value)) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10617, attribute.LocalName, element.OuterXml)); } if (StringComparer.OrdinalIgnoreCase.Equals(attribute.LocalName, Attributes.Validator)) { customValidator = attribute.Value; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.LocalName, Attributes.RevocationMode)) { createCertificateValidator = true; if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509RevocationModeNoCheck)) { revocationMode = X509RevocationMode.NoCheck; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509RevocationModeOffline)) { revocationMode = X509RevocationMode.Offline; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509RevocationModeOnline)) { revocationMode = X509RevocationMode.Online; } else { throw new ConfigurationErrorsException( string.Format( CultureInfo.InvariantCulture, JwtErrors.Jwt10606, Attributes.RevocationMode, attribute.Value, string.Format( CultureInfo.InvariantCulture, "'{0}', '{1}', '{2}'", AttributeValues.X509RevocationModeNoCheck, AttributeValues.X509RevocationModeOffline, AttributeValues.X509RevocationModeOnline), element.OuterXml)); } } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.LocalName, Attributes.ValidationMode)) { createCertificateValidator = true; if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509CertificateValidationModeChainTrust)) { certificateValidationMode = X509CertificateValidationMode.ChainTrust; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509CertificateValidationModePeerOrChainTrust)) { certificateValidationMode = X509CertificateValidationMode.PeerOrChainTrust; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509CertificateValidationModePeerTrust)) { certificateValidationMode = X509CertificateValidationMode.PeerTrust; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509CertificateValidationModeNone)) { certificateValidationMode = X509CertificateValidationMode.None; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509CertificateValidationModeCustom)) { certificateValidationMode = X509CertificateValidationMode.Custom; } else { throw new ConfigurationErrorsException( string.Format( CultureInfo.InvariantCulture, JwtErrors.Jwt10606, Attributes.ValidationMode, attribute.Value, string.Format( CultureInfo.InvariantCulture, "'{0}', '{1}', '{2}', '{3}', '{4}'", AttributeValues.X509CertificateValidationModeChainTrust, AttributeValues.X509CertificateValidationModePeerOrChainTrust, AttributeValues.X509CertificateValidationModePeerTrust, AttributeValues.X509CertificateValidationModeNone, AttributeValues.X509CertificateValidationModeCustom), element.OuterXml)); } } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.LocalName, Attributes.TrustedStoreLocation)) { createCertificateValidator = true; if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509TrustedStoreLocationCurrentUser)) { trustedStoreLocation = StoreLocation.CurrentUser; } else if (StringComparer.OrdinalIgnoreCase.Equals(attribute.Value, AttributeValues.X509TrustedStoreLocationLocalMachine)) { trustedStoreLocation = StoreLocation.LocalMachine; } else { throw new ConfigurationErrorsException( string.Format( CultureInfo.InvariantCulture, JwtErrors.Jwt10606, Attributes.TrustedStoreLocation, attribute.Value, "'" + AttributeValues.X509TrustedStoreLocationCurrentUser + "', '" + AttributeValues.X509TrustedStoreLocationLocalMachine + "'", element.OuterXml)); } } else { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10608, Elements.JwtSecurityTokenRequirement, attribute.LocalName, element.OuterXml)); } } List<XmlElement> configElements = XmlUtil.GetXmlElements(element.ChildNodes); HashSet<string> elementsProcessed = new HashSet<string>(); foreach (XmlElement childElement in configElements) { if (childElement.Attributes.Count > 1) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10609, childElement.LocalName, Attributes.Value, element.OuterXml)); } if (childElement.Attributes.Count == 0) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10607, childElement.LocalName, Attributes.Value, element.OuterXml)); } if (string.IsNullOrWhiteSpace(childElement.Attributes[0].LocalName)) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10600, Attributes.Value, element.OuterXml)); } if (!StringComparer.Ordinal.Equals(childElement.Attributes[0].LocalName, Attributes.Value)) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10610, childElement.LocalName, Attributes.Value, childElement.Attributes[0].LocalName, element.OuterXml)); } if (elementsProcessed.Contains(childElement.LocalName)) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10616, childElement.LocalName, element.OuterXml)); } elementsProcessed.Add(childElement.LocalName); if (StringComparer.Ordinal.Equals(childElement.LocalName, Elements.NameClaimType)) { this.NameClaimType = childElement.Attributes[0].Value; } else if (StringComparer.Ordinal.Equals(childElement.LocalName, Elements.RoleClaimType)) { this.RoleClaimType = childElement.Attributes[0].Value; } else { try { if (StringComparer.Ordinal.Equals(childElement.LocalName, Elements.MaxTokenSizeInBytes)) { this.MaximumTokenSizeInBytes = Convert.ToInt32(childElement.Attributes[0].Value, CultureInfo.InvariantCulture); } else if (StringComparer.Ordinal.Equals(childElement.LocalName, Elements.DefaultTokenLifetimeInMinutes)) { this.DefaultTokenLifetimeInMinutes = Convert.ToInt32(childElement.Attributes[0].Value, CultureInfo.InvariantCulture); } else if (StringComparer.Ordinal.Equals(childElement.LocalName, Elements.MaxClockSkewInMinutes)) { this.ClockSkewInSeconds = Convert.ToInt32(childElement.Attributes[0].Value, CultureInfo.InvariantCulture); } else { throw new ConfigurationErrorsException( string.Format( CultureInfo.InvariantCulture, JwtErrors.Jwt10611, Elements.JwtSecurityTokenRequirement, childElement.LocalName, string.Format( CultureInfo.InvariantCulture, "{0}', '{1}', '{2}', '{3}', '{4}", Elements.NameClaimType, Elements.RoleClaimType, Elements.MaxTokenSizeInBytes, Elements.MaxClockSkewInMinutes, Elements.DefaultTokenLifetimeInMinutes), element.OuterXml)); } } catch (OverflowException oex) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10603, childElement.LocalName, childElement.OuterXml, oex), oex); } catch (FormatException fex) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10603, childElement.LocalName, childElement.OuterXml, fex), fex); } catch (ArgumentOutOfRangeException aex) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10603, childElement.LocalName, childElement.OuterXml, aex), aex); } } } if (certificateValidationMode == X509CertificateValidationMode.Custom) { Type customValidatorType = null; if (customValidator == null) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10612, Attributes.ValidationMode, Attributes.Validator, element.OuterXml)); } try { customValidatorType = Type.GetType(customValidator, true); CustomTypeElement typeElement = new CustomTypeElement(); typeElement.Type = customValidatorType; this.certificateValidator = CustomTypeElement.Resolve<X509CertificateValidator>(typeElement); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10613, customValidator, Attributes.Validator, ex, element.OuterXml), ex); } } else if (customValidator != null) { throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, JwtErrors.Jwt10619, Attributes.Validator, Attributes.ValidationMode, AttributeValues.X509CertificateValidationModeCustom, certificateValidationMode, typeof(X509CertificateValidator).ToString(), customValidator, element.OuterXml)); } else if (createCertificateValidator) { this.certificateValidator = new X509CertificateValidatorEx(certificateValidationMode, revocationMode, trustedStoreLocation); } } /// <summary> /// Gets or sets the <see cref="X509CertificateValidator"/> for validating <see cref="X509Certificate2"/>(s). /// </summary> public X509CertificateValidator CertificateValidator { get { return this.certificateValidator; } set { this.certificateValidator = value; } } /// <summary> /// Gets or sets the clock skew to use when validating times. /// </summary> /// <exception cref="ArgumentOutOfRangeException"> if 'value' is less than 0.</exception> public Int32 ClockSkewInSeconds { get { return this.clockSkewInSeconds; } set { if (value < 0) { throw new ArgumentOutOfRangeException(JwtErrors.Jwt10120); } this.clockSkewInSeconds = value; } } /// <summary> /// Gets or sets the default for token lifetime. /// <see cref="JwtSecurityTokenHandler"/> uses this value when creating a <see cref="JwtSecurityToken"/> if the expiration time is not specified. The expiration time will be set to <see cref="DateTime.UtcNow"/> + <see cref="TimeSpan.FromMinutes"/> with <see cref="JwtSecurityTokenRequirement.DefaultTokenLifetimeInMinutes"/> as the parameter. /// </summary> /// <remarks>Default: 600 (10 hours).</remarks> /// <exception cref="ArgumentOutOfRangeException">value == 0.</exception> public Int32 DefaultTokenLifetimeInMinutes { get { return this.defaultTokenLifetimeInMinutes; } set { if (value < 1) { throw new ArgumentOutOfRangeException("value", JwtErrors.Jwt10115); } this.defaultTokenLifetimeInMinutes = value; } } /// <summary> /// Gets or sets the maximum size of a <see cref="JwtSecurityToken"/> the <see cref="JwtSecurityTokenHandler"/> will read and validate. /// </summary> /// <remarks>Default: 2 megabytes.</remarks> /// <exception cref="ArgumentOutOfRangeException">if value is 0.</exception> public Int32 MaximumTokenSizeInBytes { get { return this.maxTokenSizeInBytes; } set { if (value < 1) { throw new ArgumentOutOfRangeException("value", JwtErrors.Jwt10116); } this.maxTokenSizeInBytes = value; } } /// <summary> /// Gets or sets the <see cref="string"/> the <see cref="JwtSecurityTokenHandler"/> passes as a parameter to <see cref="ClaimsIdentity(string, string, string)"/>. /// <para>This defines the <see cref="Claim.Type"/> to match when finding the <see cref="Claim.Value"/> that is used for the <see cref="ClaimsIdentity.Name"/> property.</para> /// </summary> public string NameClaimType { get { return this.nameClaimType; } set { this.nameClaimType = value; } } /// <summary> /// Gets or sets the <see cref="string"/> the <see cref="JwtSecurityTokenHandler"/> passes as a parameter to <see cref="ClaimsIdentity(string, string, string)"/>. /// <para>This defines the <see cref="Claim"/>(s) that will be considered when answering <see cref="ClaimsPrincipal.IsInRole( string )"/></para> /// </summary> public string RoleClaimType { get { return this.roleClaimType; } set { this.roleClaimType = value; } } } }