context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.SqlServer.TDS.FeatureExtAck; namespace Microsoft.SqlServer.TDS.Login7 { /// <summary> /// Login 7 request packet /// </summary> public class TDSLogin7Token : TDSPacketToken { /// <summary> /// Length of the fixed portion of the packet /// </summary> protected static ushort FixedPacketLength = sizeof(uint) // Length + sizeof(uint) // TDSVersion + sizeof(uint) // PacketSize + sizeof(uint) // ClientProgramVersion + sizeof(uint) // ClientPID + sizeof(uint) // ConnectionID + sizeof(byte) // OptionalFlags1 + sizeof(byte) // OptionalFlags2 + sizeof(byte) // OptionalFlags3 + sizeof(byte) // TypeFlags + sizeof(int) // ClientTimeZone + sizeof(uint) // ClientLCID + sizeof(ushort) + sizeof(ushort) // HostName + sizeof(ushort) + sizeof(ushort) // UserID + sizeof(ushort) + sizeof(ushort) // Password + sizeof(ushort) + sizeof(ushort) // ApplicationName + sizeof(ushort) + sizeof(ushort) // ServerName + sizeof(ushort) + sizeof(ushort) // Unused + sizeof(ushort) + sizeof(ushort) // LibraryName + sizeof(ushort) + sizeof(ushort) // Language + sizeof(ushort) + sizeof(ushort) // Database + 6 * sizeof(byte) // ClientID + sizeof(ushort) + sizeof(ushort) // SSPI + sizeof(ushort) + sizeof(ushort) // AttachDatabaseFile + sizeof(ushort) + sizeof(ushort) // ChangePassword + sizeof(uint); // LongSSPI; /// <summary> /// Version of the TDS protocol /// </summary> public Version TDSVersion { get; set; } /// <summary> /// Size of the TDS packet requested by the client /// </summary> public uint PacketSize { get; set; } /// <summary> /// Version of the client application /// </summary> public uint ClientProgramVersion { get; set; } /// <summary> /// Client application process identifier /// </summary> public uint ClientPID { get; set; } /// <summary> /// Connection identifier /// </summary> public uint ConnectionID { get; set; } /// <summary> /// First byte of optional flags /// </summary> public TDSLogin7TokenOptionalFlags1 OptionalFlags1 { get; set; } /// <summary> /// Second byte of optional flags /// </summary> public TDSLogin7TokenOptionalFlags2 OptionalFlags2 { get; set; } /// <summary> /// Third byte of optional flags /// </summary> public TDSLogin7TokenOptionalFlags3 OptionalFlags3 { get; set; } /// <summary> /// Type flags /// </summary> public TDSLogin7TokenTypeFlags TypeFlags { get; set; } /// <summary> /// Time zone of the client /// </summary> public int ClientTimeZone { get; set; } /// <summary> /// Client locale identifier /// </summary> public uint ClientLCID { get; set; } /// <summary> /// Client host name /// </summary> public string HostName { get; set; } /// <summary> /// User ID /// </summary> public string UserID { get; set; } /// <summary> /// Password /// </summary> public string Password { get; set; } /// <summary> /// Application name /// </summary> public string ApplicationName { get; set; } /// <summary> /// Server name /// </summary> public string ServerName { get; set; } /// <summary> /// Client library name /// </summary> public string LibraryName { get; set; } /// <summary> /// User language /// </summary> public string Language { get; set; } /// <summary> /// User database /// </summary> public string Database { get; set; } /// <summary> /// Unique client identifier /// </summary> public byte[] ClientID { get; set; } /// <summary> /// Attach database file /// </summary> public string AttachDatabaseFile { get; set; } /// <summary> /// Change password /// </summary> public string ChangePassword { get; set; } /// <summary> /// SSPI authentication blob /// </summary> public byte[] SSPI { get; set; } /// <summary> /// Feature extension in the login7. /// </summary> public TDSLogin7FeatureOptionsToken FeatureExt { get; set; } /// <summary> /// Default constructor /// </summary> public TDSLogin7Token() { // Instantiate the first optional flags OptionalFlags1 = new TDSLogin7TokenOptionalFlags1(); // Instantiate the second optional flags OptionalFlags2 = new TDSLogin7TokenOptionalFlags2(); // Instantiate the third optional flags OptionalFlags3 = new TDSLogin7TokenOptionalFlags3(); // Instantiate type flags TypeFlags = new TDSLogin7TokenTypeFlags(); } /// <summary> /// Inflating constructor /// </summary> public TDSLogin7Token(Stream source) { // Inflate token Inflate(source); } /// <summary> /// Inflate the token /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream /// </summary> /// <param name="source">Stream to inflate the token from</param> /// <returns>TRUE if inflation is complete</returns> public override bool Inflate(Stream source) { // Read packet length uint length = TDSUtilities.ReadUInt(source); // Read TDS version string tdsVersion = string.Format("{0:X}", TDSUtilities.ReadUInt(source)); // Consturct TDS version TDSVersion = new Version(int.Parse(tdsVersion.Substring(0, 1)), int.Parse(tdsVersion.Substring(1, 1)), Convert.ToInt32(tdsVersion.Substring(2, 2), 16), Convert.ToInt32(tdsVersion.Substring(4, 4), 16)); // Read packet length PacketSize = TDSUtilities.ReadUInt(source); // Read client program version ClientProgramVersion = TDSUtilities.ReadUInt(source); // Read client program identifier ClientPID = TDSUtilities.ReadUInt(source); // Read connection identifier ConnectionID = TDSUtilities.ReadUInt(source); // Instantiate the first optional flags OptionalFlags1 = new TDSLogin7TokenOptionalFlags1((byte)source.ReadByte()); // Instantiate the second optional flags OptionalFlags2 = new TDSLogin7TokenOptionalFlags2((byte)source.ReadByte()); // Instantiate type flags TypeFlags = new TDSLogin7TokenTypeFlags((byte)source.ReadByte()); // Instantiate the third optional flags OptionalFlags3 = new TDSLogin7TokenOptionalFlags3((byte)source.ReadByte()); // Read client time zone ClientTimeZone = TDSUtilities.ReadInt(source); // Read client locale identifier ClientLCID = TDSUtilities.ReadUInt(source); // Prepare a collection of property values that will be set later IList<TDSLogin7TokenOffsetProperty> variableProperties = new List<TDSLogin7TokenOffsetProperty>(); // Read client host name variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("HostName"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source))); // Read user name and password variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("UserID"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source))); variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("Password"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source))); // Read application name variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("ApplicationName"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source))); // Read server name variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("ServerName"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source))); // Check if extension is used if (OptionalFlags3.ExtensionFlag) { // Read Feature extension. Note that this is just an offset of the value, not the value itself variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("FeatureExt"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source), true)); } else { // Skip unused TDSUtilities.ReadUShort(source); TDSUtilities.ReadUShort(source); } // Read client library name variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("LibraryName"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source))); // Read language variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("Language"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source))); // Read database variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("Database"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source))); ClientID = new byte[6]; // Read unique client identifier source.Read(ClientID, 0, ClientID.Length); // Read SSPI blob variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("SSPI"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source))); // Read database file to be attached variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("AttachDatabaseFile"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source))); // Read password change variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("ChangePassword"), TDSUtilities.ReadUShort(source), TDSUtilities.ReadUShort(source))); // Read long SSPI uint sspiLength = TDSUtilities.ReadUInt(source); // At this point we surpassed the fixed packet length long inflationOffset = FixedPacketLength; // Order strings in ascending order by offset // For the most cases this should not change the order of the options in the stream, but just in case variableProperties = variableProperties.OrderBy(p => p.Position).ToList(); // We can't use "foreach" because FeatureExt processing changes the collection hence we can only go index-based way int iCurrentProperty = 0; // Iterate over each property while (iCurrentProperty < variableProperties.Count) { // Get the property at the indexed position TDSLogin7TokenOffsetProperty property = variableProperties[iCurrentProperty]; // Check if length is positive if (property.Length == 0) { // Move to the next propety iCurrentProperty++; continue; } // Ensure that current offset points to the option while (inflationOffset < property.Position) { // Read the stream source.ReadByte(); // Advance position inflationOffset++; } // Check special properties if (property.Property.Name == "Password" || property.Property.Name == "ChangePassword") { // Read passwod string property.Property.SetValue(this, TDSUtilities.ReadPasswordString(source, (ushort)(property.Length * 2)), null); // Advance the position inflationOffset += (property.Length * 2); } else if (property.Property.Name == "SSPI") { // If cbSSPI < USHRT_MAX, then this length MUST be used for SSPI and cbSSPILong MUST be ignored. // If cbSSPI == USHRT_MAX, then cbSSPILong MUST be checked. if (property.Length == ushort.MaxValue) { // If cbSSPILong > 0, then that value MUST be used. If cbSSPILong ==0, then cbSSPI (USHRT_MAX) MUST be used. if (sspiLength > 0) { // We don't know how to handle SSPI packets that exceed TDS packet size throw new NotSupportedException("Long SSPI blobs are not supported yet"); } } // Use short length instead sspiLength = property.Length; // Allocate buffer for SSPI data SSPI = new byte[sspiLength]; // Read SSPI blob source.Read(SSPI, 0, SSPI.Length); // Advance the position inflationOffset += sspiLength; } else if (property.Property.Name == "FeatureExt") { // Check if this is the property or a pointer to the property if (property.IsOffsetOffset) { // Read the actual offset of the feature extension property.Position = TDSUtilities.ReadUInt(source); // Mark that now we have actual value property.IsOffsetOffset = false; // Advance the position inflationOffset += sizeof(uint); // Re-order the collection variableProperties = variableProperties.OrderBy(p => p.Position).ToList(); // Subtract position to stay on the same spot for subsequent property iCurrentProperty--; } else { // Create a list of features. FeatureExt = new TDSLogin7FeatureOptionsToken(); // Inflate feature extension FeatureExt.Inflate(source); // Advance position by the size of the inflated token inflationOffset += FeatureExt.InflationSize; } } else { // Read the string and assign it to the property of this instance property.Property.SetValue(this, TDSUtilities.ReadString(source, (ushort)(property.Length * 2)), null); // Advance the position inflationOffset += (property.Length * 2); } // Advance to the next property iCurrentProperty++; } return true; } /// <summary> /// Deflate the token /// </summary> /// <param name="destination">Stream to deflate token to</param> public override void Deflate(Stream destination) { // Calculate total length by adding strings uint totalPacketLength = (uint)(FixedPacketLength + (uint)(string.IsNullOrEmpty(HostName) ? 0 : HostName.Length * 2) // HostName + (uint)(string.IsNullOrEmpty(UserID) ? 0 : UserID.Length * 2) // UserID + (uint)(string.IsNullOrEmpty(Password) ? 0 : Password.Length * 2) // Password + (uint)(string.IsNullOrEmpty(ApplicationName) ? 0 : ApplicationName.Length * 2) // ApplicationName + (uint)(string.IsNullOrEmpty(ServerName) ? 0 : ServerName.Length * 2) // ServerName + (uint)(string.IsNullOrEmpty(LibraryName) ? 0 : LibraryName.Length * 2) // LibraryName + (uint)(string.IsNullOrEmpty(Language) ? 0 : Language.Length * 2) // Language + (uint)(string.IsNullOrEmpty(Database) ? 0 : Database.Length * 2) // Database + (uint)(string.IsNullOrEmpty(AttachDatabaseFile) ? 0 : AttachDatabaseFile.Length * 2) // AttachDatabaseFile + (uint)(string.IsNullOrEmpty(ChangePassword) ? 0 : ChangePassword.Length * 2) // ChangePassword + (uint)(SSPI == null ? 0 : SSPI.Length) // SSPI + 0); // Feature extension MemoryStream featureExtension = null; // Check if we have a feature extension if (FeatureExt != null) { // Allocate feature extension block featureExtension = new MemoryStream(); // Serialize feature extension FeatureExt.Deflate(featureExtension); // Update total lentgh totalPacketLength += (uint)(sizeof(uint) /* Offset of feature extension data */ + featureExtension.Length /* feature extension itself*/); } // Write packet length TDSUtilities.WriteUInt(destination, totalPacketLength); // Compile TDS version uint tdsVersion = Convert.ToUInt32(string.Format("{0:X}", Math.Max(TDSVersion.Major, 0)) + string.Format("{0:X}", Math.Max(TDSVersion.Minor, 0)) + string.Format("{0:X2}", Math.Max(TDSVersion.Build, 0)) + string.Format("{0:X4}", Math.Max(TDSVersion.Revision, 0)), 16); // Write TDS version TDSUtilities.WriteUInt(destination, tdsVersion); // Write packet length TDSUtilities.WriteUInt(destination, PacketSize); // Write client program version TDSUtilities.WriteUInt(destination, ClientProgramVersion); // Write client program identifier TDSUtilities.WriteUInt(destination, ClientPID); // Write connection identifier TDSUtilities.WriteUInt(destination, ConnectionID); // Write the first optional flags destination.WriteByte(OptionalFlags1.ToByte()); // Write the second optional flags destination.WriteByte(OptionalFlags2.ToByte()); // Instantiate type flags destination.WriteByte(TypeFlags.ToByte()); // Write the third optional flags destination.WriteByte(OptionalFlags3.ToByte()); // Write client time zone TDSUtilities.WriteInt(destination, ClientTimeZone); // Write client locale identifier TDSUtilities.WriteUInt(destination, ClientLCID); // Prepare a collection of property values that will be set later IList<TDSLogin7TokenOffsetProperty> variableProperties = new List<TDSLogin7TokenOffsetProperty>(); // Write client host name variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("HostName"), FixedPacketLength, (ushort)(string.IsNullOrEmpty(HostName) ? 0 : HostName.Length))); TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position); TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Length); // Write user name and password variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("UserID"), (ushort)(variableProperties.Last().Position + variableProperties.Last().Length * 2), (ushort)(string.IsNullOrEmpty(UserID) ? 0 : UserID.Length))); TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position); TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Length); variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("Password"), (ushort)(variableProperties.Last().Position + variableProperties.Last().Length * 2), (ushort)(string.IsNullOrEmpty(Password) ? 0 : Password.Length))); TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position); TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Length); // Write application name variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("ApplicationName"), (ushort)(variableProperties.Last().Position + variableProperties.Last().Length * 2), (ushort)(string.IsNullOrEmpty(ApplicationName) ? 0 : ApplicationName.Length))); TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position); TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Length); // Write server name variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("ServerName"), (ushort)(variableProperties.Last().Position + variableProperties.Last().Length * 2), (ushort)(string.IsNullOrEmpty(ServerName) ? 0 : ServerName.Length))); TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position); TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Length); // Check if we have a feature extension block if (FeatureExt != null) { // Write the offset of the feature extension offset (pointer to pointer) variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("FeatureExt"), (ushort)(variableProperties.Last().Position + variableProperties.Last().Length * 2), sizeof(uint) / 2, true)); // Should be 4 bytes, devided by 2 because the next guy multiplies by 2 TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position); TDSUtilities.WriteUShort(destination, (ushort)(variableProperties.Last().Length * 2)); // Compensate for division by 2 above } else { // Skip unused TDSUtilities.WriteUShort(destination, 0); TDSUtilities.WriteUShort(destination, 0); } // Write client library name // We do not need to account for skipped unused bytes here because they're already accounted in fixedPacketLength variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("LibraryName"), (ushort)(variableProperties.Last().Position + variableProperties.Last().Length * 2), (ushort)(string.IsNullOrEmpty(LibraryName) ? 0 : LibraryName.Length))); TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position); TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Length); // Write language variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("Language"), (ushort)(variableProperties.Last().Position + variableProperties.Last().Length * 2), (ushort)(string.IsNullOrEmpty(Language) ? 0 : Language.Length))); TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position); TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Length); // Write database variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("Database"), (ushort)(variableProperties.Last().Position + variableProperties.Last().Length * 2), (ushort)(string.IsNullOrEmpty(Database) ? 0 : Database.Length))); TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position); TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Length); // Check if client is defined if (ClientID == null) { // Allocate empty identifier ClientID = new byte[6]; } // Write unique client identifier destination.Write(ClientID, 0, 6); // Write SSPI variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("SSPI"), (ushort)(variableProperties.Last().Position + variableProperties.Last().Length * 2), (ushort)(SSPI == null ? 0 : SSPI.Length))); TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position); TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Length); // Write database file to be attached. NOTE, "variableProperties.Last().Length" without " * 2" because the preceeding buffer isn't string variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("AttachDatabaseFile"), (ushort)(variableProperties.Last().Position + variableProperties.Last().Length), (ushort)(string.IsNullOrEmpty(AttachDatabaseFile) ? 0 : AttachDatabaseFile.Length))); TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position); TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Length); // Write password change variableProperties.Add(new TDSLogin7TokenOffsetProperty(GetType().GetProperty("ChangePassword"), (ushort)(variableProperties.Last().Position + variableProperties.Last().Length * 2), (ushort)(string.IsNullOrEmpty(ChangePassword) ? 0 : ChangePassword.Length))); TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Position); TDSUtilities.WriteUShort(destination, (ushort)variableProperties.Last().Length); // Skip long SSPI TDSUtilities.WriteUInt(destination, 0); // We will be changing collection as we go and serialize everything. As such we can't use foreach and iterator. int iCurrentProperty = 0; // Iterate through the collection while (iCurrentProperty < variableProperties.Count) { // Get current property by index TDSLogin7TokenOffsetProperty property = variableProperties[iCurrentProperty]; // Check if length is positive if (property.Length == 0) { // Move to the next property iCurrentProperty++; continue; } // Check special properties if (property.Property.Name == "Password" || property.Property.Name == "ChangePassword") { // Write encrypted string value TDSUtilities.WritePasswordString(destination, (string)property.Property.GetValue(this, null)); } else if (property.Property.Name == "FeatureExt") { // Check if we are to serialize the offset or the actual data if (property.IsOffsetOffset) { // Property will be written at the offset immediately following all variable length data property.Position = variableProperties.Last().Position + variableProperties.Last().Length; // Write the position at which we'll be serializing the feature extension block TDSUtilities.WriteUInt(destination, property.Position); // Order strings in ascending order by offset variableProperties = variableProperties.OrderBy(p => p.Position).ToList(); // Compensate increment to the next position in order to stay on the same iCurrentProperty--; // No longer offset, actual data is going to follow property.IsOffsetOffset = false; } else { // Transfer deflated feature extension into the login stream featureExtension.WriteTo(destination); } } else if (property.Property.Name == "SSPI") { // Write SSPI destination.Write(SSPI, 0, SSPI.Length); } else { // Write the string value TDSUtilities.WriteString(destination, (string)property.Property.GetValue(this, null)); } // Move to the next property iCurrentProperty++; } } } }
// // MonoTests.System.Xml.XPathNavigatorReaderTests // // Author: // Atsushi Enomoto <atsushi@ximian.com> // // Copyright (C) 2005 Novell, Inc. http://www.novell.com // #if NET_2_0 using System; using System.Xml; using System.Xml.XPath; using NUnit.Framework; using MonoTests.System.Xml; // XmlAssert namespace MonoTests.System.Xml.XPath { [TestFixture] public class XPathNavigatorReaderTests { XmlDocument document; XPathNavigator nav; XPathDocument xpathDocument; [SetUp] public void GetReady () { document = new XmlDocument (); } private XPathNavigator GetXmlDocumentNavigator (string xml) { document.LoadXml (xml); return document.CreateNavigator (); } private XPathNavigator GetXPathDocumentNavigator (XmlNode node) { XmlNodeReader xr = new XmlNodeReader (node); xpathDocument = new XPathDocument (xr); return xpathDocument.CreateNavigator (); } [Test] public void ReadSubtree1 () { string xml = "<root/>"; nav = GetXmlDocumentNavigator (xml); ReadSubtree1 (nav, "#1."); nav.MoveToRoot (); nav.MoveToFirstChild (); ReadSubtree1 (nav, "#2."); nav = GetXPathDocumentNavigator (document); ReadSubtree1 (nav, "#3."); nav.MoveToRoot (); nav.MoveToFirstChild (); ReadSubtree1 (nav, "#4."); } void ReadSubtree1 (XPathNavigator nav, string label) { XmlReader r = nav.ReadSubtree (); XmlAssert.AssertNode (label + "#1", r, // NodeType, Depth, IsEmptyElement XmlNodeType.None, 0, false, // Name, Prefix, LocalName, NamespaceURI String.Empty, String.Empty, String.Empty, String.Empty, // Value, HasValue, AttributeCount, HasAttributes String.Empty, false, 0, false); Assert.IsTrue (r.Read (), label + "#2"); XmlAssert.AssertNode (label + "#3", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Element, 0, true, // Name, Prefix, LocalName, NamespaceURI "root", String.Empty, "root", String.Empty, // Value, HasValue, AttributeCount, HasAttributes String.Empty, false, 0, false); Assert.IsFalse (r.Read (), label + "#4"); } [Test] public void ReadSubtree2 () { string xml = "<root></root>"; nav = GetXmlDocumentNavigator (xml); ReadSubtree2 (nav, "#1."); nav.MoveToRoot (); nav.MoveToFirstChild (); ReadSubtree2 (nav, "#2."); nav = GetXPathDocumentNavigator (document); ReadSubtree2 (nav, "#3."); nav.MoveToRoot (); nav.MoveToFirstChild (); ReadSubtree2 (nav, "#4."); } void ReadSubtree2 (XPathNavigator nav, string label) { XmlReader r = nav.ReadSubtree (); XmlAssert.AssertNode (label + "#1", r, // NodeType, Depth, IsEmptyElement XmlNodeType.None, 0, false, // Name, Prefix, LocalName, NamespaceURI String.Empty, String.Empty, String.Empty, String.Empty, // Value, HasValue, AttributeCount, HasAttributes String.Empty, false, 0, false); Assert.IsTrue (r.Read (), label + "#2"); XmlAssert.AssertNode (label + "#3", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Element, 0, false, // Name, Prefix, LocalName, NamespaceURI "root", String.Empty, "root", String.Empty, // Value, HasValue, AttributeCount, HasAttributes String.Empty, false, 0, false); Assert.IsTrue (r.Read (), label + "#4"); XmlAssert.AssertNode (label + "#5", r, // NodeType, Depth, IsEmptyElement XmlNodeType.EndElement, 0, false, // Name, Prefix, LocalName, NamespaceURI "root", String.Empty, "root", String.Empty, // Value, HasValue, AttributeCount, HasAttributes String.Empty, false, 0, false); Assert.IsFalse (r.Read (), label + "#6"); } [Test] public void ReadSubtree3 () { string xml = "<root attr='value'/>"; nav = GetXmlDocumentNavigator (xml); ReadSubtree3 (nav, "#1."); nav.MoveToRoot (); nav.MoveToFirstChild (); ReadSubtree3 (nav, "#2."); nav = GetXPathDocumentNavigator (document); ReadSubtree3 (nav, "#3."); nav.MoveToRoot (); nav.MoveToFirstChild (); ReadSubtree3 (nav, "#4."); } void ReadSubtree3 (XPathNavigator nav, string label) { XmlReader r = nav.ReadSubtree (); XmlAssert.AssertNode (label + "#1", r, // NodeType, Depth, IsEmptyElement XmlNodeType.None, 0, false, // Name, Prefix, LocalName, NamespaceURI String.Empty, String.Empty, String.Empty, String.Empty, // Value, HasValue, AttributeCount, HasAttributes String.Empty, false, 0, false); Assert.IsTrue (r.Read (), label + "#2"); XmlAssert.AssertNode (label + "#3", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Element, 0, true, // Name, Prefix, LocalName, NamespaceURI "root", String.Empty, "root", String.Empty, // Value, HasValue, AttributeCount, HasAttributes String.Empty, false, 1, true); Assert.IsTrue (r.MoveToFirstAttribute (), label + "#4"); XmlAssert.AssertNode (label + "#5", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Attribute, 1, false, // Name, Prefix, LocalName, NamespaceURI "attr", String.Empty, "attr", String.Empty, // Value, HasValue, AttributeCount, HasAttributes "value", true, 1, true); Assert.IsTrue (r.ReadAttributeValue (), label + "#6"); XmlAssert.AssertNode (label + "#7", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Text, 2, false, // Name, Prefix, LocalName, NamespaceURI String.Empty, String.Empty, String.Empty, String.Empty, // Value, HasValue, AttributeCount, HasAttributes "value", true, 1, true); Assert.IsFalse (r.ReadAttributeValue (), label + "#8"); Assert.IsFalse (r.MoveToNextAttribute (), label + "#9"); Assert.IsTrue (r.MoveToElement (), label + "#10"); Assert.IsFalse (r.Read (), label + "#11"); } [Test] public void DocElem_OpenClose_Attribute () { string xml = "<root attr='value'></root>"; nav = GetXmlDocumentNavigator (xml); DocElem_OpenClose_Attribute (nav, "#1."); nav.MoveToRoot (); nav.MoveToFirstChild (); DocElem_OpenClose_Attribute (nav, "#2."); nav = GetXPathDocumentNavigator (document); DocElem_OpenClose_Attribute (nav, "#3."); nav.MoveToRoot (); nav.MoveToFirstChild (); DocElem_OpenClose_Attribute (nav, "#4."); } void DocElem_OpenClose_Attribute (XPathNavigator nav, string label) { XmlReader r = nav.ReadSubtree (); XmlAssert.AssertNode (label + "#1", r, // NodeType, Depth, IsEmptyElement XmlNodeType.None, 0, false, // Name, Prefix, LocalName, NamespaceURI String.Empty, String.Empty, String.Empty, String.Empty, // Value, HasValue, AttributeCount, HasAttributes String.Empty, false, 0, false); Assert.IsTrue (r.Read (), label + "#2"); XmlAssert.AssertNode (label + "#3", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Element, 0, false, // Name, Prefix, LocalName, NamespaceURI "root", String.Empty, "root", String.Empty, // Value, HasValue, AttributeCount, HasAttributes String.Empty, false, 1, true); Assert.IsTrue (r.MoveToFirstAttribute (), label + "#4"); XmlAssert.AssertNode (label + "#5", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Attribute, 1, false, // Name, Prefix, LocalName, NamespaceURI "attr", String.Empty, "attr", String.Empty, // Value, HasValue, AttributeCount, HasAttributes "value", true, 1, true); Assert.IsTrue (r.ReadAttributeValue (), label + "#6"); XmlAssert.AssertNode (label + "#7", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Text, 2, false, // Name, Prefix, LocalName, NamespaceURI String.Empty, String.Empty, String.Empty, String.Empty, // Value, HasValue, AttributeCount, HasAttributes "value", true, 1, true); Assert.IsFalse (r.ReadAttributeValue (), label + "#8"); Assert.IsFalse (r.MoveToNextAttribute (), label + "#9"); Assert.IsTrue (r.MoveToElement (), label + "#10"); Assert.IsTrue (r.Read (), label + "#11"); XmlAssert.AssertNode (label + "#12", r, // NodeType, Depth, IsEmptyElement XmlNodeType.EndElement, 0, false, // Name, Prefix, LocalName, NamespaceURI "root", String.Empty, "root", String.Empty, // Value, HasValue, AttributeCount, HasAttributes String.Empty, false, 0, false); Assert.IsFalse (r.Read (), label + "#13"); } [Test] public void FromChildElement () { string xml = "<root><foo attr='value'>test</foo><bar/></root>"; nav = GetXmlDocumentNavigator (xml); nav.MoveToFirstChild (); nav.MoveToFirstChild (); // foo FromChildElement (nav, "#1."); nav = GetXPathDocumentNavigator (document); nav.MoveToFirstChild (); nav.MoveToFirstChild (); // foo FromChildElement (nav, "#2."); } void FromChildElement (XPathNavigator nav, string label) { XmlReader r = nav.ReadSubtree (); XmlAssert.AssertNode (label + "#1", r, // NodeType, Depth, IsEmptyElement XmlNodeType.None, 0, false, // Name, Prefix, LocalName, NamespaceURI String.Empty, String.Empty, String.Empty, String.Empty, // Value, HasValue, AttributeCount, HasAttributes String.Empty, false, 0, false); Assert.IsTrue (r.Read (), label + "#2"); XmlAssert.AssertNode (label + "#3", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Element, 0, false, // Name, Prefix, LocalName, NamespaceURI "foo", String.Empty, "foo", String.Empty, // Value, HasValue, AttributeCount, HasAttributes String.Empty, false, 1, true); Assert.IsTrue (r.Read (), label + "#4"); XmlAssert.AssertNode (label + "#5", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Text, 1, false, // Name, Prefix, LocalName, NamespaceURI String.Empty, String.Empty, String.Empty, String.Empty, // Value, HasValue, AttributeCount, HasAttributes "test", true, 0, false); Assert.IsTrue (r.Read (), label + "#6"); XmlAssert.AssertNode (label + "#7", r, // NodeType, Depth, IsEmptyElement XmlNodeType.EndElement, 0, false, // Name, Prefix, LocalName, NamespaceURI "foo", String.Empty, "foo", String.Empty, // Value, HasValue, AttributeCount, HasAttributes String.Empty, false, 0, false); // end at </foo>, without moving toward <bar>. Assert.IsFalse (r.Read (), label + "#8"); } [Test] [Category ("NotDotNet")] // MS bug public void AttributesAndNamespaces () { string xml = "<root attr='value' x:a2='v2' xmlns:x='urn:foo' xmlns='urn:default'></root>"; nav = GetXmlDocumentNavigator (xml); AttributesAndNamespaces (nav, "#1."); nav.MoveToRoot (); nav.MoveToFirstChild (); AttributesAndNamespaces (nav, "#2."); nav = GetXPathDocumentNavigator (document); AttributesAndNamespaces (nav, "#3."); nav.MoveToRoot (); nav.MoveToFirstChild (); AttributesAndNamespaces (nav, "#4."); } void AttributesAndNamespaces (XPathNavigator nav, string label) { XmlReader r = nav.ReadSubtree (); XmlAssert.AssertNode (label + "#1", r, // NodeType, Depth, IsEmptyElement XmlNodeType.None, 0, false, // Name, Prefix, LocalName, NamespaceURI String.Empty, String.Empty, String.Empty, String.Empty, // Value, HasValue, AttributeCount, HasAttributes String.Empty, false, 0, false); Assert.IsTrue (r.Read (), label + "#2"); XmlAssert.AssertNode (label + "#3", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Element, 0, false, // Name, Prefix, LocalName, NamespaceURI "root", String.Empty, "root", "urn:default", // Value, HasValue, AttributeCount, HasAttributes String.Empty, false, 4, true); // Namespaces Assert.IsTrue (r.MoveToAttribute ("xmlns:x"), label + "#4"); XmlAssert.AssertNode (label + "#5", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Attribute, 1, false, // Name, Prefix, LocalName, NamespaceURI "xmlns:x", "xmlns", "x", "http://www.w3.org/2000/xmlns/", // Value, HasValue, AttributeCount, HasAttributes "urn:foo", true, 4, true); Assert.IsTrue (r.ReadAttributeValue (), label + "#6"); ///* MS.NET has a bug here XmlAssert.AssertNode (label + "#7", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Text, 2, false, // Name, Prefix, LocalName, NamespaceURI String.Empty, String.Empty, String.Empty, String.Empty, // Value, HasValue, AttributeCount, HasAttributes "urn:foo", true, 4, true); //*/ Assert.IsFalse (r.ReadAttributeValue (), label + "#8"); Assert.IsTrue (r.MoveToAttribute ("xmlns"), label + "#9"); XmlAssert.AssertNode (label + "#10", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Attribute, 1, false, // Name, Prefix, LocalName, NamespaceURI "xmlns", String.Empty, "xmlns", "http://www.w3.org/2000/xmlns/", // Value, HasValue, AttributeCount, HasAttributes "urn:default", true, 4, true); Assert.IsTrue (r.ReadAttributeValue (), label + "#11"); ///* MS.NET has a bug here XmlAssert.AssertNode (label + "#12", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Text, 2, false, // Name, Prefix, LocalName, NamespaceURI String.Empty, String.Empty, String.Empty, String.Empty, // Value, HasValue, AttributeCount, HasAttributes "urn:default", true, 4, true); //*/ Assert.IsFalse (r.ReadAttributeValue (), label + "#13"); // Attributes Assert.IsTrue (r.MoveToAttribute ("attr"), label + "#14"); XmlAssert.AssertNode (label + "#15", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Attribute, 1, false, // Name, Prefix, LocalName, NamespaceURI "attr", String.Empty, "attr", String.Empty, // Value, HasValue, AttributeCount, HasAttributes "value", true, 4, true); Assert.IsTrue (r.ReadAttributeValue (), label + "#16"); XmlAssert.AssertNode (label + "#17", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Text, 2, false, // Name, Prefix, LocalName, NamespaceURI String.Empty, String.Empty, String.Empty, String.Empty, // Value, HasValue, AttributeCount, HasAttributes "value", true, 4, true); Assert.IsFalse (r.ReadAttributeValue (), label + "#18"); Assert.IsTrue (r.MoveToAttribute ("x:a2"), label + "#19"); XmlAssert.AssertNode (label + "#20", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Attribute, 1, false, // Name, Prefix, LocalName, NamespaceURI "x:a2", "x", "a2", "urn:foo", // Value, HasValue, AttributeCount, HasAttributes "v2", true, 4, true); Assert.IsTrue (r.ReadAttributeValue (), label + "#21"); XmlAssert.AssertNode (label + "#22", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Text, 2, false, // Name, Prefix, LocalName, NamespaceURI String.Empty, String.Empty, String.Empty, String.Empty, // Value, HasValue, AttributeCount, HasAttributes "v2", true, 4, true); Assert.IsTrue (r.MoveToElement (), label + "#24"); Assert.IsTrue (r.Read (), label + "#25"); XmlAssert.AssertNode (label + "#26", r, // NodeType, Depth, IsEmptyElement XmlNodeType.EndElement, 0, false, // Name, Prefix, LocalName, NamespaceURI "root", String.Empty, "root", "urn:default", // Value, HasValue, AttributeCount, HasAttributes String.Empty, false, 0, false); Assert.IsFalse (r.Read (), label + "#27"); } [Test] public void MixedContentAndDepth () { string xml = @"<one> <two>Some data.<three>more</three> done.</two> </one>"; nav = GetXmlDocumentNavigator (xml); MixedContentAndDepth (nav, "#1."); nav.MoveToRoot (); nav.MoveToFirstChild (); MixedContentAndDepth (nav, "#2."); nav = GetXPathDocumentNavigator (document); MixedContentAndDepth (nav, "#3."); nav.MoveToRoot (); nav.MoveToFirstChild (); MixedContentAndDepth (nav, "#4."); } void MixedContentAndDepth (XPathNavigator nav, string label) { XmlReader r = nav.ReadSubtree (); r.Read (); XmlAssert.AssertNode (label + "#1", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Element, 0, false, // Name, Prefix, LocalName, NamespaceURI "one", String.Empty, "one", String.Empty, // Value, HasValue, AttributeCount, HasAttributes String.Empty, false, 0, false); r.Read (); XmlAssert.AssertNode (label + "#2", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Element, 1, false, // Name, Prefix, LocalName, NamespaceURI "two", String.Empty, "two", String.Empty, // Value, HasValue, AttributeCount, HasAttributes String.Empty, false, 0, false); r.Read (); XmlAssert.AssertNode (label + "#3", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Text, 2, false, // Name, Prefix, LocalName, NamespaceURI String.Empty, String.Empty, String.Empty, String.Empty, // Value, HasValue, AttributeCount, HasAttributes "Some data.", true, 0, false); r.Read (); XmlAssert.AssertNode (label + "#4", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Element, 2, false, // Name, Prefix, LocalName, NamespaceURI "three", String.Empty, "three", String.Empty, // Value, HasValue, AttributeCount, HasAttributes String.Empty, false, 0, false); r.Read (); XmlAssert.AssertNode (label + "#5", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Text, 3, false, // Name, Prefix, LocalName, NamespaceURI String.Empty, String.Empty, String.Empty, String.Empty, // Value, HasValue, AttributeCount, HasAttributes "more", true, 0, false); r.Read (); XmlAssert.AssertNode (label + "#6", r, // NodeType, Depth, IsEmptyElement XmlNodeType.EndElement, 2, false, // Name, Prefix, LocalName, NamespaceURI "three", String.Empty, "three", String.Empty, // Value, HasValue, AttributeCount, HasAttributes String.Empty, false, 0, false); r.Read (); XmlAssert.AssertNode (label + "#7", r, // NodeType, Depth, IsEmptyElement XmlNodeType.Text, 2, false, // Name, Prefix, LocalName, NamespaceURI String.Empty, String.Empty, String.Empty, String.Empty, // Value, HasValue, AttributeCount, HasAttributes " done.", true, 0, false); r.Read (); XmlAssert.AssertNode (label + "#8", r, // NodeType, Depth, IsEmptyElement XmlNodeType.EndElement, 1, false, // Name, Prefix, LocalName, NamespaceURI "two", String.Empty, "two", String.Empty, // Value, HasValue, AttributeCount, HasAttributes String.Empty, false, 0, false); r.Read (); XmlAssert.AssertNode (label + "#9", r, // NodeType, Depth, IsEmptyElement XmlNodeType.EndElement, 0, false, // Name, Prefix, LocalName, NamespaceURI "one", String.Empty, "one", String.Empty, // Value, HasValue, AttributeCount, HasAttributes String.Empty, false, 0, false); Assert.IsFalse (r.Read (), label + "#10"); } [Test] public void MoveToFirstAttributeFromAttribute () { string xml = @"<one xmlns:foo='urn:foo' a='v' />"; nav = GetXmlDocumentNavigator (xml); MoveToFirstAttributeFromAttribute (nav, "#1."); nav.MoveToRoot (); nav.MoveToFirstChild (); MoveToFirstAttributeFromAttribute (nav, "#2."); nav = GetXPathDocumentNavigator (document); MoveToFirstAttributeFromAttribute (nav, "#3."); nav.MoveToRoot (); nav.MoveToFirstChild (); MoveToFirstAttributeFromAttribute (nav, "#4."); } void MoveToFirstAttributeFromAttribute (XPathNavigator nav, string label) { XmlReader r = nav.ReadSubtree (); r.MoveToContent (); Assert.IsTrue (r.MoveToFirstAttribute (), label + "#1"); Assert.IsTrue (r.MoveToFirstAttribute (), label + "#2"); r.ReadAttributeValue (); Assert.IsTrue (r.MoveToFirstAttribute (), label + "#3"); Assert.IsTrue (r.MoveToNextAttribute (), label + "#4"); Assert.IsTrue (r.MoveToFirstAttribute (), label + "#5"); } [Test] [ExpectedException (typeof (InvalidOperationException))] public void ReadSubtreeAttribute () { string xml = "<root a='b' />"; nav = GetXmlDocumentNavigator (xml); nav.MoveToFirstChild (); nav.MoveToFirstAttribute (); nav.ReadSubtree (); } [Test] [ExpectedException (typeof (InvalidOperationException))] public void ReadSubtreeNamespace () { string xml = "<root xmlns='urn:foo' />"; nav = GetXmlDocumentNavigator (xml); nav.MoveToFirstChild (); nav.MoveToFirstNamespace (); nav.ReadSubtree (); } [Test] [ExpectedException (typeof (InvalidOperationException))] public void ReadSubtreePI () { string xml = "<?pi ?><root xmlns='urn:foo' />"; nav = GetXmlDocumentNavigator (xml); nav.MoveToFirstChild (); nav.ReadSubtree (); } [Test] [ExpectedException (typeof (InvalidOperationException))] public void ReadSubtreeComment () { string xml = "<!-- comment --><root xmlns='urn:foo' />"; nav = GetXmlDocumentNavigator (xml); nav.MoveToFirstChild (); nav.ReadSubtree (); } [Test] public void ReadSubtreeAttributesByIndex () { XmlWriter xw; XmlDocument doc = new XmlDocument (); doc.LoadXml ("<u:Timestamp u:Id='ID1' xmlns:u='urn:foo'></u:Timestamp>"); XmlReader r = doc.CreateNavigator ().ReadSubtree (); r.Read (); r.MoveToAttribute (0); if (r.LocalName != "Id") r.MoveToAttribute (1); if (r.LocalName != "Id") Assert.Fail ("Should move to the attribute."); } } } #endif
using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using SIL.Keyboarding; using SIL.Reporting; using SIL.WritingSystems; namespace SIL.Windows.Forms.WritingSystems { public partial class WSSortControl : UserControl { private WritingSystemSetupModel _model; private readonly Hashtable _sortUsingValueMap; private Hashtable _languageOptionMap; private bool _changingModel; private IKeyboardDefinition _defaultKeyboard; private string _defaultFontName; private float _defaultFontSize; public event EventHandler UserWantsHelpWithCustomSorting; public WSSortControl() { InitializeComponent(); _sortUsingValueMap = new Hashtable(); foreach (KeyValuePair<string, string> sortUsingOption in WritingSystemSetupModel.SortUsingOptions) { int index = _sortUsingComboBox.Items.Add(sortUsingOption.Value); _sortUsingValueMap[sortUsingOption.Key] = index; _sortUsingValueMap[index] = sortUsingOption.Key; } _defaultFontName = _sortRulesTextBox.Font.Name; _defaultFontSize = _sortRulesTextBox.Font.SizeInPoints; // default text for testing the sort rules _testSortText.Text = string.Join(Environment.NewLine, "pear", "apple", "orange", "mango", "peach"); } public void BindToModel(WritingSystemSetupModel model) { if (_model != null) { _model.SelectionChanged -= ModelSelectionChanged; _model.CurrentItemUpdated -= ModelCurrentItemUpdated; } _model = model; if (_model != null) { UpdateFromModel(); _model.SelectionChanged += ModelSelectionChanged; _model.CurrentItemUpdated += ModelCurrentItemUpdated; } this.Disposed += OnDisposed; } void OnDisposed(object sender, EventArgs e) { if (_model != null) { _model.SelectionChanged -= ModelSelectionChanged; _model.CurrentItemUpdated -= ModelCurrentItemUpdated; } } private void ModelSelectionChanged(object sender, EventArgs e) { UpdateFromModel(); } private void ModelCurrentItemUpdated(object sender, EventArgs e) { if (_changingModel) { return; } UpdateFromModel(); } private void UpdateFromModel() { if (!_model.HasCurrentSelection) { _sortrules_panel.Visible = false; _languagecombo_panel.Visible = false; Enabled = false; return; } Enabled = true; LoadLanguageChoicesFromModel(); if (_sortUsingValueMap.ContainsKey(_model.CurrentCollationRulesType)) { _sortUsingComboBox.SelectedIndex = (int)_sortUsingValueMap[_model.CurrentCollationRulesType]; } else { _sortUsingComboBox.SelectedIndex = -1; } SetControlFonts(); } private void LoadLanguageChoicesFromModel() { _languageComboBox.Items.Clear(); _languageOptionMap = new Hashtable(); foreach (KeyValuePair<string, string> languageOption in _model.SortLanguageOptions) { int index = _languageComboBox.Items.Add(languageOption.Value); _languageOptionMap[index] = languageOption.Key; _languageOptionMap[languageOption.Key] = index; } _sortUsingComboBox.SelectedIndex = -1; } private void _sortRulesTextBox_TextChanged(object sender, EventArgs e) { if (ValidateSortRules()) { _changingModel = true; try { _model.CurrentCollationRules = _sortRulesTextBox.Text; } finally { _changingModel = false; } } } private void _sortUsingComboBox_SelectedIndexChanged(object sender, EventArgs e) { _sortrules_panel.Visible = false; _languagecombo_panel.Visible = false; if (_sortUsingComboBox.SelectedIndex == -1) { return; } string newValue = (string)_sortUsingValueMap[_sortUsingComboBox.SelectedIndex]; _changingModel = true; try { _model.CurrentCollationRulesType = newValue; } finally { _changingModel = false; } if (newValue == "OtherLanguage") { _sortrules_panel.Visible = true; _languagecombo_panel.Visible = true; if (_languageOptionMap.ContainsKey(_model.CurrentCollationRules)) { _languageComboBox.SelectedIndex = (int)_languageOptionMap[_model.CurrentCollationRules]; } } else if (newValue == "CustomSimple" || newValue == "CustomIcu") { _sortrules_panel.Visible = true; _sortRulesTextBox.Text = _model.CurrentCollationRules; } } private void _languageComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (_languageComboBox.SelectedIndex == -1) { return; } string newValue = (string) _languageOptionMap[_languageComboBox.SelectedIndex]; _changingModel = true; try { _model.CurrentCollationRules = newValue; } finally { _changingModel = false; } } private void _testSortButton_Click(object sender, EventArgs e) { try { if (ValidateSortRules()) { _testSortResult.Text = _model.TestSort(_testSortText.Text); } } catch (ApplicationException ex) { ErrorReport.NotifyUserOfProblem("Unable to sort test text: {0}", ex.Message); } } private void SetControlFonts() { float fontSize = _model.CurrentDefaultFontSize; if (fontSize <= 0 || float.IsNaN(fontSize) || float.IsInfinity(fontSize)) { fontSize = _defaultFontSize; } string fontName = _model.CurrentDefaultFontName; if (string.IsNullOrEmpty(fontName)) { fontName = _defaultFontName; } Font customFont = new Font(fontName, fontSize); _sortRulesTextBox.Font = customFont; // We are not setting the RightToLeft propert for the sort rules because the ICU syntax is inherently left to right. _testSortText.Font = customFont; _testSortText.RightToLeft = _model.CurrentRightToLeftScript ? RightToLeft.Yes : RightToLeft.No; _testSortResult.Font = customFont; _testSortResult.RightToLeft = _model.CurrentRightToLeftScript ? RightToLeft.Yes : RightToLeft.No; } private void TextControl_Enter(object sender, EventArgs e) { if (_model == null) { return; } _defaultKeyboard = Keyboard.Controller.ActiveKeyboard; _model.ActivateCurrentKeyboard(); } private void TextControl_Leave(object sender, EventArgs e) { if (_model == null) { return; } _defaultKeyboard.Activate(); ValidateSortRules(); } private bool ValidateSortRules() { CollationDefinition cd; switch (_model.CurrentCollationRulesType) { case "CustomIcu": { cd = new IcuRulesCollationDefinition((IcuRulesCollationDefinition)_model.CurrentDefinition.DefaultCollation) { IcuRules = _sortRulesTextBox.Text }; break; } case "CustomSimple": { cd = new SimpleRulesCollationDefinition((SimpleRulesCollationDefinition)_model.CurrentDefinition.DefaultCollation) { SimpleRules = _sortRulesTextBox.Text }; break; } default: { return false; } } string message; const string prefixToMessage = "SORT RULES WILL NOT BE SAVED\r\n"; if (!cd.Validate(out message)) { _testSortResult.Text = prefixToMessage + (message ?? String.Empty); _testSortResult.ForeColor = Color.Red; return false; } if (_testSortResult.Text.StartsWith(prefixToMessage)) { _testSortResult.Text = String.Empty; _testSortResult.ForeColor = Color.Black; } return true; } private void OnHelpLabelClicked(object sender, LinkLabelLinkClickedEventArgs e) { if (UserWantsHelpWithCustomSorting != null) UserWantsHelpWithCustomSorting(sender, e); } } }
#region CopyrightHeader // // Copyright by Contributors // // 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.txt // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections.Generic; using System.Text; using gov.va.medora.mdo.dao.vista; using gov.va.medora.mdo.dao.vista.fhie; namespace gov.va.medora.mdo.dao { public abstract class AbstractDaoFactory { public const int PVISTA = 0; // pooled vista public const int VISTA = 1; public const int FHIE = 2; public const int HL7 = 3; public const int RPMS = 4; public const int NPT = 100; public const int VBACORP = 200; public const int ADR = 201; public const int MHV = 202; public const int VADIR = 203; public const int CDW = 204; public const int SM = 205; public const int RDW = 206; public const int LDAP = 300; public const int XVISTA = 998; public const int MOCK = 999; public abstract AbstractConnection getConnection(DataSource dataSource); public abstract IUserDao getUserDao(AbstractConnection cxn); public abstract IPatientDao getPatientDao(AbstractConnection cxn); public abstract IClinicalDao getClinicalDao(AbstractConnection cxn); public abstract IEncounterDao getEncounterDao(AbstractConnection cxn); public abstract IPharmacyDao getPharmacyDao(AbstractConnection cxn); public abstract ILabsDao getLabsDao(AbstractConnection cxn); public abstract IToolsDao getToolsDao(AbstractConnection cxn); public abstract INoteDao getNoteDao(AbstractConnection cxn); public abstract IVitalsDao getVitalsDao(AbstractConnection cxn); public abstract IChemHemDao getChemHemDao(AbstractConnection cxn); public abstract IClaimsDao getClaimsDao(AbstractConnection cxn); public abstract IConsultDao getConsultDao(AbstractConnection cxn); public abstract IRemindersDao getRemindersDao(AbstractConnection cxn); public abstract ILocationDao getLocationDao(AbstractConnection cxn); public abstract IOrdersDao getOrdersDao(AbstractConnection cxn); public abstract IRadiologyDao getRadiologyDao(AbstractConnection cxn); public abstract ISchedulingDao getSchedulingDao(AbstractConnection cxn); public Object getDaoByName(string daoName, AbstractConnection cxn) { if (daoName == "AbstractConnection" || daoName.EndsWith("Connection")) { return getConnection(cxn.DataSource); } if (daoName == "ISchedulingDao") { return getSchedulingDao(cxn); } if (daoName == "IToolsDao") { return getToolsDao(cxn); } if (daoName == "IPatientDao") { return getPatientDao(cxn); } if (daoName == "IUserDao") { return getUserDao(cxn); } if (daoName == "IClinicalDao") { return getClinicalDao(cxn); } if (daoName == "IEncounterDao") { return getEncounterDao(cxn); } if (daoName == "IPharmacyDao") { return getPharmacyDao(cxn); } if (daoName == "ILabsDao") { return getLabsDao(cxn); } if (daoName == "INoteDao") { return getNoteDao(cxn); } if (daoName == "IVitalsDao") { return getVitalsDao(cxn); } if (daoName == "IChemHemDao") { return getChemHemDao(cxn); } if (daoName == "IClaimsDao") { return getClaimsDao(cxn); } if (daoName == "IConsultDao") { return getConsultDao(cxn); } if (daoName == "IRemindersDao") { return getRemindersDao(cxn); } if (daoName == "ILocationDao") { return getLocationDao(cxn); } if (daoName == "IOrdersDao") { return getOrdersDao(cxn); } if (daoName == "IRadiologyDao") { return getRadiologyDao(cxn); } return null; } public static int getConstant (string value) { if (value == "PVISTA") { return PVISTA; } if (value == "VISTA") { return VISTA; } if (value == "FHIE") { return FHIE; } if (value == "HL7") { return HL7; } if (value == "RPMS") { return RPMS; } if (value == "NPT") { return NPT; } if (value == "VBACORP") { return VBACORP; } if (value == "ADR") { return ADR; } if (value == "MHV") { return MHV; } if (value == "VADIR") { return VADIR; } if (String.Equals("CDW", value, StringComparison.CurrentCultureIgnoreCase)) { return CDW; } if (value == "XVISTA") { return XVISTA; } if (value == "MOCK") { return MOCK; } if (String.Equals(value, "SM", StringComparison.CurrentCultureIgnoreCase)) { return SM; } if (String.Equals(value, "LDAP", StringComparison.CurrentCultureIgnoreCase)) { return LDAP; } if (String.Equals(value, "RDW", StringComparison.CurrentCultureIgnoreCase)) { return RDW; } return 0; } public static AbstractDaoFactory getDaoFactory (int protocol) { switch (protocol) { case PVISTA: return new VistaConnectionPoolDaoFactory(); case VISTA: return new VistaDaoFactory(); case FHIE: return new FhieDaoFactory(); case HL7: return new gov.va.medora.mdo.dao.hl7.HL7DaoFactory(); case NPT: return new gov.va.medora.mdo.dao.sql.npt.NptDaoFactory(); case VBACORP: return new gov.va.medora.mdo.dao.oracle.vbacorp.VbacorpDaoFactory(); case ADR: return new gov.va.medora.mdo.dao.oracle.adr.AdrDaoFactory(); //case MHV: // return new gov.va.medora.mdo.dao.oracle.mhv.MhvDaoFactory(); case VADIR: return new gov.va.medora.mdo.dao.oracle.vadir.VadirDaoFactory(); case CDW: return new gov.va.medora.mdo.dao.sql.cdw.CdwDaoFactory(); case MOCK: return new MockDaoFactory(); case XVISTA: return new XDaoFactory(); default: return null; } } } }
/* * 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 CSJ2K; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Imaging; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Reflection; using System.Text; namespace OpenSim.Region.CoreModules.Agent.TextureSender { public delegate void J2KDecodeDelegate(UUID assetID); [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "J2KDecoderModule")] public class J2KDecoderModule : ISharedRegionModule, IJ2KDecoder { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary>Temporarily holds deserialized layer data information in memory</summary> private readonly ThreadedClasses.ExpiringCache<UUID, OpenJPEG.J2KLayerInfo[]> m_decodedCache = new ThreadedClasses.ExpiringCache<UUID, OpenJPEG.J2KLayerInfo[]>(30); /// <summary>List of client methods to notify of results of decode</summary> private readonly Dictionary<UUID, List<DecodedCallback>> m_notifyList = new Dictionary<UUID, List<DecodedCallback>>(); /// <summary>Cache that will store decoded JPEG2000 layer boundary data</summary> private IImprovedAssetCache m_cache; private IImprovedAssetCache Cache { get { if (m_cache == null) m_cache = m_scene.RequestModuleInterface<IImprovedAssetCache>(); return m_cache; } } /// <summary>Reference to a scene (doesn't matter which one as long as it can load the cache module)</summary> private UUID m_CreatorID = UUID.Zero; private Scene m_scene; #region ISharedRegionModule private bool m_useCSJ2K = true; public string Name { get { return "J2KDecoderModule"; } } public J2KDecoderModule() { } public void Initialise(IConfigSource source) { IConfig startupConfig = source.Configs["Startup"]; if (startupConfig != null) { m_useCSJ2K = startupConfig.GetBoolean("UseCSJ2K", m_useCSJ2K); } } public void AddRegion(Scene scene) { if (m_scene == null) { m_scene = scene; m_CreatorID = scene.RegionInfo.RegionID; } scene.RegisterModuleInterface<IJ2KDecoder>(this); } public void RemoveRegion(Scene scene) { if (m_scene == scene) m_scene = null; } public void PostInitialise() { } public void Close() { } public void RegionLoaded(Scene scene) { } public Type ReplaceableInterface { get { return null; } } #endregion Region Module interface #region IJ2KDecoder public void BeginDecode(UUID assetID, byte[] j2kData, DecodedCallback callback) { OpenJPEG.J2KLayerInfo[] result; // If it's cached, return the cached results if (m_decodedCache.TryGetValue(assetID, out result)) { // m_log.DebugFormat( // "[J2KDecoderModule]: Returning existing cached {0} layers j2k decode for {1}", // result.Length, assetID); callback(assetID, result); } else { // Not cached, we need to decode it. // Add to notify list and start decoding. // Next request for this asset while it's decoding will only be added to the notify list // once this is decoded, requests will be served from the cache and all clients in the notifylist will be updated bool decode = false; lock (m_notifyList) { if (m_notifyList.ContainsKey(assetID)) { m_notifyList[assetID].Add(callback); } else { List<DecodedCallback> notifylist = new List<DecodedCallback>(); notifylist.Add(callback); m_notifyList.Add(assetID, notifylist); decode = true; } } // Do Decode! if (decode) Util.FireAndForget(delegate { Decode(assetID, j2kData); }); } } public bool Decode(UUID assetID, byte[] j2kData) { OpenJPEG.J2KLayerInfo[] layers; int components; return Decode(assetID, j2kData, out layers, out components); } public bool Decode(UUID assetID, byte[] j2kData, out OpenJPEG.J2KLayerInfo[] layers, out int components) { return DoJ2KDecode(assetID, j2kData, out layers, out components); } public Image DecodeToImage(byte[] j2kData) { if (m_useCSJ2K) return J2kImage.FromBytes(j2kData); else { ManagedImage mimage; Image image; if (OpenJPEG.DecodeToImage(j2kData, out mimage, out image)) { mimage = null; return image; } else return null; } } #endregion IJ2KDecoder /// <summary> /// Decode Jpeg2000 Asset Data /// </summary> /// <param name="assetID">UUID of Asset</param> /// <param name="j2kData">JPEG2000 data</param> /// <param name="layers">layer data</param> /// <param name="components">number of components</param> /// <returns>true if decode was successful. false otherwise.</returns> private bool DoJ2KDecode(UUID assetID, byte[] j2kData, out OpenJPEG.J2KLayerInfo[] layers, out int components) { // m_log.DebugFormat( // "[J2KDecoderModule]: Doing J2K decoding of {0} bytes for asset {1}", j2kData.Length, assetID); bool decodedSuccessfully = true; //int DecodeTime = 0; //DecodeTime = Environment.TickCount; // We don't get this from CSJ2K. Is it relevant? components = 0; if (!TryLoadCacheForAsset(assetID, out layers)) { if (m_useCSJ2K) { try { List<int> layerStarts; using (MemoryStream ms = new MemoryStream(j2kData)) { layerStarts = CSJ2K.J2kImage.GetLayerBoundaries(ms); } if (layerStarts != null && layerStarts.Count > 0) { layers = new OpenJPEG.J2KLayerInfo[layerStarts.Count]; for (int i = 0; i < layerStarts.Count; i++) { OpenJPEG.J2KLayerInfo layer = new OpenJPEG.J2KLayerInfo(); if (i == 0) layer.Start = 0; else layer.Start = layerStarts[i]; if (i == layerStarts.Count - 1) layer.End = j2kData.Length; else layer.End = layerStarts[i + 1] - 1; layers[i] = layer; } } } catch (Exception ex) { m_log.Warn("[J2KDecoderModule]: CSJ2K threw an exception decoding texture " + assetID + ": " + ex.Message); decodedSuccessfully = false; } } else { if (!OpenJPEG.DecodeLayerBoundaries(j2kData, out layers, out components)) { m_log.Warn("[J2KDecoderModule]: OpenJPEG failed to decode texture " + assetID); decodedSuccessfully = false; } } if (layers == null || layers.Length == 0) { m_log.Warn("[J2KDecoderModule]: Failed to decode layer data for texture " + assetID + ", guessing sane defaults"); // Layer decoding completely failed. Guess at sane defaults for the layer boundaries layers = CreateDefaultLayers(j2kData.Length); decodedSuccessfully = false; } // Cache Decoded layers SaveFileCacheForAsset(assetID, layers); } // Notify Interested Parties lock (m_notifyList) { if (m_notifyList.ContainsKey(assetID)) { foreach (DecodedCallback d in m_notifyList[assetID]) { if (d != null) d.DynamicInvoke(assetID, layers); } m_notifyList.Remove(assetID); } } return decodedSuccessfully; } private OpenJPEG.J2KLayerInfo[] CreateDefaultLayers(int j2kLength) { OpenJPEG.J2KLayerInfo[] layers = new OpenJPEG.J2KLayerInfo[5]; for (int i = 0; i < layers.Length; i++) layers[i] = new OpenJPEG.J2KLayerInfo(); // These default layer sizes are based on a small sampling of real-world texture data // with extra padding thrown in for good measure. This is a worst case fallback plan // and may not gracefully handle all real world data layers[0].Start = 0; layers[1].Start = (int)((float)j2kLength * 0.02f); layers[2].Start = (int)((float)j2kLength * 0.05f); layers[3].Start = (int)((float)j2kLength * 0.20f); layers[4].Start = (int)((float)j2kLength * 0.50f); layers[0].End = layers[1].Start - 1; layers[1].End = layers[2].Start - 1; layers[2].End = layers[3].Start - 1; layers[3].End = layers[4].Start - 1; layers[4].End = j2kLength; return layers; } private void SaveFileCacheForAsset(UUID AssetId, OpenJPEG.J2KLayerInfo[] Layers) { m_decodedCache.AddOrUpdate(AssetId, Layers, TimeSpan.FromMinutes(10)); if (Cache != null) { string assetID = "j2kCache_" + AssetId.ToString(); AssetBase layerDecodeAsset = new AssetBase(assetID, assetID, (sbyte)AssetType.Notecard, m_CreatorID.ToString()); layerDecodeAsset.Local = true; layerDecodeAsset.Temporary = true; #region Serialize Layer Data StringBuilder stringResult = new StringBuilder(); string strEnd = "\n"; for (int i = 0; i < Layers.Length; i++) { if (i == Layers.Length - 1) strEnd = String.Empty; stringResult.AppendFormat("{0}|{1}|{2}{3}", Layers[i].Start, Layers[i].End, Layers[i].End - Layers[i].Start, strEnd); } layerDecodeAsset.Data = Util.UTF8.GetBytes(stringResult.ToString()); #endregion Serialize Layer Data Cache.Cache(layerDecodeAsset); } } bool TryLoadCacheForAsset(UUID AssetId, out OpenJPEG.J2KLayerInfo[] Layers) { if (m_decodedCache.TryGetValue(AssetId, out Layers)) { return true; } else if (Cache != null) { string assetName = "j2kCache_" + AssetId.ToString(); AssetBase layerDecodeAsset = Cache.Get(assetName); if (layerDecodeAsset != null) { #region Deserialize Layer Data string readResult = Util.UTF8.GetString(layerDecodeAsset.Data); string[] lines = readResult.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); if (lines.Length == 0) { m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (empty) " + assetName); Cache.Expire(assetName); return false; } Layers = new OpenJPEG.J2KLayerInfo[lines.Length]; for (int i = 0; i < lines.Length; i++) { string[] elements = lines[i].Split('|'); if (elements.Length == 3) { int element1, element2; try { element1 = Convert.ToInt32(elements[0]); element2 = Convert.ToInt32(elements[1]); } catch (FormatException) { m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (format) " + assetName); Cache.Expire(assetName); return false; } Layers[i] = new OpenJPEG.J2KLayerInfo(); Layers[i].Start = element1; Layers[i].End = element2; } else { m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (layout) " + assetName); Cache.Expire(assetName); return false; } } #endregion Deserialize Layer Data return true; } } return false; } } }
/* * Copyright (c) 2007-2009, openmetaverse.org * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using System.Threading; using OpenMetaverse.Packets; using OpenMetaverse.Messages.Linden; using OpenMetaverse.Interfaces; namespace OpenMetaverse { /// <summary> /// Registers, unregisters, and fires events generated by incoming packets /// </summary> public class PacketEventDictionary { /// <summary> /// Object that is passed to worker threads in the ThreadPool for /// firing packet callbacks /// </summary> private struct PacketCallbackWrapper { /// <summary>Callback to fire for this packet</summary> public EventHandler<PacketReceivedEventArgs> Callback; /// <summary>Reference to the simulator that this packet came from</summary> public Simulator Simulator; /// <summary>The packet that needs to be processed</summary> public Packet Packet; } /// <summary>Reference to the GridClient object</summary> public GridClient Client; private Dictionary<PacketType, EventHandler<PacketReceivedEventArgs>> _EventTable = new Dictionary<PacketType, EventHandler<PacketReceivedEventArgs>>(); private WaitCallback _ThreadPoolCallback; /// <summary> /// Default constructor /// </summary> /// <param name="client"></param> public PacketEventDictionary(GridClient client) { Client = client; _ThreadPoolCallback = new WaitCallback(ThreadPoolDelegate); } /// <summary> /// Register an event handler /// </summary> /// <remarks>Use PacketType.Default to fire this event on every /// incoming packet</remarks> /// <param name="packetType">Packet type to register the handler for</param> /// <param name="eventHandler">Callback to be fired</param> public void RegisterEvent(PacketType packetType, EventHandler<PacketReceivedEventArgs> eventHandler) { lock (_EventTable) { if (_EventTable.ContainsKey(packetType)) _EventTable[packetType] += eventHandler; else _EventTable[packetType] = eventHandler; } } /// <summary> /// Unregister an event handler /// </summary> /// <param name="packetType">Packet type to unregister the handler for</param> /// <param name="eventHandler">Callback to be unregistered</param> public void UnregisterEvent(PacketType packetType, EventHandler<PacketReceivedEventArgs> eventHandler) { lock (_EventTable) { if (_EventTable.ContainsKey(packetType) && _EventTable[packetType] != null) _EventTable[packetType] -= eventHandler; } } /// <summary> /// Fire the events registered for this packet type synchronously /// </summary> /// <param name="packetType">Incoming packet type</param> /// <param name="packet">Incoming packet</param> /// <param name="simulator">Simulator this packet was received from</param> internal void RaiseEvent(PacketType packetType, Packet packet, Simulator simulator) { EventHandler<PacketReceivedEventArgs> callback; // Default handler first, if one exists if (_EventTable.TryGetValue(PacketType.Default, out callback)) { try { callback(this, new PacketReceivedEventArgs(packet, simulator)); } catch (Exception ex) { Logger.Log("Default packet event handler: " + ex.ToString(), Helpers.LogLevel.Error, Client); } } if (_EventTable.TryGetValue(packetType, out callback)) { try { callback(this, new PacketReceivedEventArgs(packet, simulator)); } catch (Exception ex) { Logger.Log("Packet event handler: " + ex.ToString(), Helpers.LogLevel.Error, Client); } return; } if (packetType != PacketType.Default && packetType != PacketType.PacketAck) { Logger.DebugLog("No handler registered for packet event " + packetType, Client); } } /// <summary> /// Fire the events registered for this packet type asynchronously /// </summary> /// <param name="packetType">Incoming packet type</param> /// <param name="packet">Incoming packet</param> /// <param name="simulator">Simulator this packet was received from</param> internal void BeginRaiseEvent(PacketType packetType, Packet packet, Simulator simulator) { EventHandler<PacketReceivedEventArgs> callback; PacketCallbackWrapper wrapper; // Default handler first, if one exists if (_EventTable.TryGetValue(PacketType.Default, out callback)) { if (callback != null) { wrapper.Callback = callback; wrapper.Packet = packet; wrapper.Simulator = simulator; ThreadPool.QueueUserWorkItem(_ThreadPoolCallback, wrapper); } } if (_EventTable.TryGetValue(packetType, out callback)) { if (callback != null) { wrapper.Callback = callback; wrapper.Packet = packet; wrapper.Simulator = simulator; ThreadPool.QueueUserWorkItem(_ThreadPoolCallback, wrapper); return; } } if (packetType != PacketType.Default && packetType != PacketType.PacketAck) { Logger.DebugLog("No handler registered for packet event " + packetType, Client); } } private void ThreadPoolDelegate(Object state) { PacketCallbackWrapper wrapper = (PacketCallbackWrapper)state; try { wrapper.Callback(this, new PacketReceivedEventArgs(wrapper.Packet, wrapper.Simulator)); } catch (Exception ex) { Logger.Log("Async Packet Event Handler: " + ex.ToString(), Helpers.LogLevel.Error, Client); } } } /// <summary> /// Registers, unregisters, and fires events generated by the Capabilities /// event queue /// </summary> public class CapsEventDictionary { /// <summary> /// Object that is passed to worker threads in the ThreadPool for /// firing CAPS callbacks /// </summary> private struct CapsCallbackWrapper { /// <summary>Callback to fire for this packet</summary> public Caps.EventQueueCallback Callback; /// <summary>Name of the CAPS event</summary> public string CapsEvent; /// <summary>Strongly typed decoded data</summary> public IMessage Message; /// <summary>Reference to the simulator that generated this event</summary> public Simulator Simulator; } /// <summary>Reference to the GridClient object</summary> public GridClient Client; private Dictionary<string, Caps.EventQueueCallback> _EventTable = new Dictionary<string, Caps.EventQueueCallback>(); private WaitCallback _ThreadPoolCallback; /// <summary> /// Default constructor /// </summary> /// <param name="client">Reference to the GridClient object</param> public CapsEventDictionary(GridClient client) { Client = client; _ThreadPoolCallback = new WaitCallback(ThreadPoolDelegate); } /// <summary> /// Register an new event handler for a capabilities event sent via the EventQueue /// </summary> /// <remarks>Use String.Empty to fire this event on every CAPS event</remarks> /// <param name="capsEvent">Capability event name to register the /// handler for</param> /// <param name="eventHandler">Callback to fire</param> public void RegisterEvent(string capsEvent, Caps.EventQueueCallback eventHandler) { lock (_EventTable) { if (_EventTable.ContainsKey(capsEvent)) _EventTable[capsEvent] += eventHandler; else _EventTable[capsEvent] = eventHandler; } } /// <summary> /// Unregister a previously registered capabilities handler /// </summary> /// <param name="capsEvent">Capability event name unregister the /// handler for</param> /// <param name="eventHandler">Callback to unregister</param> public void UnregisterEvent(string capsEvent, Caps.EventQueueCallback eventHandler) { lock (_EventTable) { if (_EventTable.ContainsKey(capsEvent) && _EventTable[capsEvent] != null) _EventTable[capsEvent] -= eventHandler; } } /// <summary> /// Fire the events registered for this event type synchronously /// </summary> /// <param name="capsEvent">Capability name</param> /// <param name="message">Decoded event body</param> /// <param name="simulator">Reference to the simulator that /// generated this event</param> internal void RaiseEvent(string capsEvent, IMessage message, Simulator simulator) { bool specialHandler = false; Caps.EventQueueCallback callback; // Default handler first, if one exists if (_EventTable.TryGetValue(capsEvent, out callback)) { if (callback != null) { try { callback(capsEvent, message, simulator); } catch (Exception ex) { Logger.Log("CAPS Event Handler: " + ex.ToString(), Helpers.LogLevel.Error, Client); } } } // Explicit handler next if (_EventTable.TryGetValue(capsEvent, out callback) && callback != null) { try { callback(capsEvent, message, simulator); } catch (Exception ex) { Logger.Log("CAPS Event Handler: " + ex.ToString(), Helpers.LogLevel.Error, Client); } specialHandler = true; } if (!specialHandler) Logger.Log("Unhandled CAPS event " + capsEvent, Helpers.LogLevel.Warning, Client); } /// <summary> /// Fire the events registered for this event type asynchronously /// </summary> /// <param name="capsEvent">Capability name</param> /// <param name="message">Decoded event body</param> /// <param name="simulator">Reference to the simulator that /// generated this event</param> internal void BeginRaiseEvent(string capsEvent, IMessage message, Simulator simulator) { bool specialHandler = false; Caps.EventQueueCallback callback; // Default handler first, if one exists if (_EventTable.TryGetValue(String.Empty, out callback)) { if (callback != null) { CapsCallbackWrapper wrapper; wrapper.Callback = callback; wrapper.CapsEvent = capsEvent; wrapper.Message = message; wrapper.Simulator = simulator; ThreadPool.QueueUserWorkItem(_ThreadPoolCallback, wrapper); } } // Explicit handler next if (_EventTable.TryGetValue(capsEvent, out callback) && callback != null) { CapsCallbackWrapper wrapper; wrapper.Callback = callback; wrapper.CapsEvent = capsEvent; wrapper.Message = message; wrapper.Simulator = simulator; ThreadPool.QueueUserWorkItem(_ThreadPoolCallback, wrapper); specialHandler = true; } if (!specialHandler) Logger.Log("Unhandled CAPS event " + capsEvent, Helpers.LogLevel.Warning, Client); } private void ThreadPoolDelegate(Object state) { CapsCallbackWrapper wrapper = (CapsCallbackWrapper)state; try { wrapper.Callback(wrapper.CapsEvent, wrapper.Message, wrapper.Simulator); } catch (Exception ex) { Logger.Log("Async CAPS Event Handler: " + ex.ToString(), Helpers.LogLevel.Error, Client); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Xunit; namespace System.Security.Cryptography.EcDsa.Tests { public sealed class ECDsaTests_Array : ECDsaTests { protected override bool VerifyData(ECDsa ecdsa, byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm) => ecdsa.VerifyData(data, offset, count, signature, hashAlgorithm); protected override byte[] SignData(ECDsa ecdsa, byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) => ecdsa.SignData(data, offset, count, hashAlgorithm); [Theory, MemberData(nameof(RealImplementations))] public void SignData_InvalidArguments_Throws(ECDsa ecdsa) { AssertExtensions.Throws<ArgumentNullException>("data", () => ecdsa.SignData((byte[])null, default(HashAlgorithmName))); AssertExtensions.Throws<ArgumentNullException>("data", () => ecdsa.SignData(null, -1, -1, default(HashAlgorithmName))); AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => ecdsa.SignData(new byte[0], -1, -1, default(HashAlgorithmName))); AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => ecdsa.SignData(new byte[0], 2, 1, default(HashAlgorithmName))); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => ecdsa.SignData(new byte[0], 0, -1, default(HashAlgorithmName))); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => ecdsa.SignData(new byte[0], 0, 1, default(HashAlgorithmName))); AssertExtensions.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.SignData(new byte[0], default(HashAlgorithmName))); AssertExtensions.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.SignData(new byte[0], 0, 0, default(HashAlgorithmName))); AssertExtensions.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.SignData(new byte[0], 0, 0, default(HashAlgorithmName))); AssertExtensions.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.SignData(new byte[10], 0, 10, new HashAlgorithmName(""))); Assert.ThrowsAny<CryptographicException>(() => ecdsa.SignData(new byte[0], new HashAlgorithmName(Guid.NewGuid().ToString("N")))); Assert.ThrowsAny<CryptographicException>(() => ecdsa.SignData(new byte[0], 0, 0, new HashAlgorithmName(Guid.NewGuid().ToString("N")))); } [Theory, MemberData(nameof(RealImplementations))] public void VerifyData_InvalidArguments_Throws(ECDsa ecdsa) { AssertExtensions.Throws<ArgumentNullException>("data", () => ecdsa.VerifyData((byte[])null, null, default(HashAlgorithmName))); AssertExtensions.Throws<ArgumentNullException>("data", () => ecdsa.VerifyData(null, -1, -1, null, default(HashAlgorithmName))); AssertExtensions.Throws<ArgumentNullException>("signature", () => ecdsa.VerifyData(new byte[0], null, default(HashAlgorithmName))); AssertExtensions.Throws<ArgumentNullException>("signature", () => ecdsa.VerifyData(new byte[0], 0, 0, null, default(HashAlgorithmName))); AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => ecdsa.VerifyData(new byte[0], -1, -1, null, default(HashAlgorithmName))); AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => ecdsa.VerifyData(new byte[0], 2, 1, null, default(HashAlgorithmName))); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => ecdsa.VerifyData(new byte[0], 0, -1, null, default(HashAlgorithmName))); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => ecdsa.VerifyData(new byte[0], 0, 1, null, default(HashAlgorithmName))); AssertExtensions.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.VerifyData(new byte[0], new byte[0], default(HashAlgorithmName))); AssertExtensions.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.VerifyData(new byte[0], 0, 0, new byte[0], default(HashAlgorithmName))); AssertExtensions.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.VerifyData(new byte[10], new byte[0], new HashAlgorithmName(""))); AssertExtensions.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.VerifyData(new byte[10], 0, 10, new byte[0], new HashAlgorithmName(""))); Assert.ThrowsAny<CryptographicException>(() => ecdsa.VerifyData(new byte[0], new byte[0], new HashAlgorithmName(Guid.NewGuid().ToString("N")))); Assert.ThrowsAny<CryptographicException>(() => ecdsa.VerifyData(new byte[0], 0, 0, new byte[0], new HashAlgorithmName(Guid.NewGuid().ToString("N")))); } [Theory, MemberData(nameof(RealImplementations))] public void SignHash_InvalidArguments_Throws(ECDsa ecdsa) { AssertExtensions.Throws<ArgumentNullException>("hash", () => ecdsa.SignHash(null)); } [Theory, MemberData(nameof(RealImplementations))] public void VerifyHash_InvalidArguments_Throws(ECDsa ecdsa) { AssertExtensions.Throws<ArgumentNullException>("hash", () => ecdsa.VerifyHash(null, null)); AssertExtensions.Throws<ArgumentNullException>("signature", () => ecdsa.VerifyHash(new byte[0], null)); } } public sealed class ECDsaTests_Stream : ECDsaTests { protected override bool VerifyData(ECDsa ecdsa, byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm) { var stream = new MemoryStream(data, offset, count); bool result = ecdsa.VerifyData(stream, signature, hashAlgorithm); Assert.Equal(stream.Length, stream.Position); return result; } protected override byte[] SignData(ECDsa ecdsa, byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { var stream = new MemoryStream(data, offset, count); byte[] result = ecdsa.SignData(stream, hashAlgorithm); Assert.Equal(stream.Length, stream.Position); return result; } [Theory, MemberData(nameof(RealImplementations))] public void SignData_InvalidArguments_Throws(ECDsa ecdsa) { AssertExtensions.Throws<ArgumentNullException>("data", () => ecdsa.SignData((Stream)null, default(HashAlgorithmName))); AssertExtensions.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.SignData(new MemoryStream(), default(HashAlgorithmName))); Assert.ThrowsAny<CryptographicException>(() => ecdsa.SignData(new MemoryStream(), new HashAlgorithmName(Guid.NewGuid().ToString("N")))); } [Theory, MemberData(nameof(RealImplementations))] public void VerifyData_InvalidArguments_Throws(ECDsa ecdsa) { AssertExtensions.Throws<ArgumentNullException>("data", () => ecdsa.VerifyData((Stream)null, null, default(HashAlgorithmName))); AssertExtensions.Throws<ArgumentNullException>("signature", () => ecdsa.VerifyData(new MemoryStream(), null, default(HashAlgorithmName))); AssertExtensions.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.VerifyData(new MemoryStream(), new byte[0], default(HashAlgorithmName))); AssertExtensions.Throws<ArgumentException>("hashAlgorithm", () => ecdsa.VerifyData(new MemoryStream(), new byte[0], new HashAlgorithmName(""))); Assert.ThrowsAny<CryptographicException>(() => ecdsa.VerifyData(new MemoryStream(), new byte[0], new HashAlgorithmName(Guid.NewGuid().ToString("N")))); } } public abstract partial class ECDsaTests : ECDsaTestsBase { protected bool VerifyData(ECDsa ecdsa, byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm) => VerifyData(ecdsa, data, 0, data.Length, signature, hashAlgorithm); protected abstract bool VerifyData(ECDsa ecdsa, byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm); protected byte[] SignData(ECDsa ecdsa, byte[] data, HashAlgorithmName hashAlgorithm) => SignData(ecdsa, data, 0, data.Length, hashAlgorithm); protected abstract byte[] SignData(ECDsa ecdsa, byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm); public static IEnumerable<object[]> RealImplementations() => new[] { new ECDsa[] { ECDsaFactory.Create() }, }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// [Theory] [MemberData(nameof(RealImplementations))] public void SignData_MaxOffset_ZeroLength_NoThrow(ECDsa ecdsa) { // Explicitly larger than Array.Empty byte[] data = new byte[10]; byte[] signature = SignData(ecdsa, data, data.Length, 0, HashAlgorithmName.SHA256); Assert.True(VerifyData(ecdsa, Array.Empty<byte>(), signature, HashAlgorithmName.SHA256)); } [Theory] [MemberData(nameof(RealImplementations))] public void VerifyData_MaxOffset_ZeroLength_NoThrow(ECDsa ecdsa) { // Explicitly larger than Array.Empty byte[] data = new byte[10]; byte[] signature = SignData(ecdsa, Array.Empty<byte>(), HashAlgorithmName.SHA256); Assert.True(VerifyData(ecdsa, data, data.Length, 0, signature, HashAlgorithmName.SHA256)); } [Theory] [MemberData(nameof(RealImplementations))] public void Roundtrip_WithOffset(ECDsa ecdsa) { byte[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; byte[] halfData = { 5, 6, 7, 8, 9 }; byte[] dataSignature = SignData(ecdsa, data, 5, data.Length - 5, HashAlgorithmName.SHA256); byte[] halfDataSignature = SignData(ecdsa, halfData, HashAlgorithmName.SHA256); // Cross-feed the VerifyData calls to prove that both offsets work Assert.True(VerifyData(ecdsa, data, 5, data.Length - 5, halfDataSignature, HashAlgorithmName.SHA256)); Assert.True(VerifyData(ecdsa, halfData, dataSignature, HashAlgorithmName.SHA256)); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// [Theory] [InlineData(256)] [InlineData(384)] [InlineData(521)] public void CreateKey(int keySize) { using (ECDsa ecdsa = ECDsaFactory.Create()) { // Step 1, don't throw here. ecdsa.KeySize = keySize; // Step 2, ensure the key was generated without throwing. SignData(ecdsa, Array.Empty<byte>(), HashAlgorithmName.SHA256); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static IEnumerable<object[]> InteroperableSignatureConfigurations() { foreach (HashAlgorithmName hashAlgorithm in new[] { HashAlgorithmName.MD5, HashAlgorithmName.SHA1, HashAlgorithmName.SHA256, HashAlgorithmName.SHA384, HashAlgorithmName.SHA512 }) { yield return new object[] { ECDsaFactory.Create(), hashAlgorithm }; } } [Theory] [MemberData(nameof(InteroperableSignatureConfigurations))] public void SignVerify_InteroperableSameKeys_RoundTripsUnlessTampered(ECDsa ecdsa, HashAlgorithmName hashAlgorithm) { byte[] data = Encoding.UTF8.GetBytes("something to repeat and sign"); // large enough to make hashing work though multiple iterations and not a multiple of 4KB it uses. byte[] dataArray = new byte[33333]; byte[] dataArray2 = new byte[dataArray.Length + 2]; dataArray.CopyTo(dataArray2, 1); HashAlgorithm halg; if (hashAlgorithm == HashAlgorithmName.MD5) halg = MD5.Create(); else if (hashAlgorithm == HashAlgorithmName.SHA1) halg = SHA1.Create(); else if (hashAlgorithm == HashAlgorithmName.SHA256) halg = SHA256.Create(); else if (hashAlgorithm == HashAlgorithmName.SHA384) halg = SHA384.Create(); else if (hashAlgorithm == HashAlgorithmName.SHA512) halg = SHA512.Create(); else throw new Exception("Hash algorithm not supported."); List<byte[]> signatures = new List<byte[]>(6); // Compute a signature using each of the SignData overloads. Then, verify it using each // of the VerifyData overloads, and VerifyHash overloads. // // Then, verify that VerifyHash fails if the data is tampered with. signatures.Add(SignData(ecdsa, dataArray, hashAlgorithm)); signatures.Add(ecdsa.SignHash(halg.ComputeHash(dataArray))); foreach (byte[] signature in signatures) { Assert.True(VerifyData(ecdsa, dataArray, signature, hashAlgorithm), "Verify 1"); Assert.True(ecdsa.VerifyHash(halg.ComputeHash(dataArray), signature), "Verify 4"); } int distinctSignatures = signatures.Distinct(new ByteArrayComparer()).Count(); Assert.True(distinctSignatures == signatures.Count, "Signing should be randomized"); foreach (byte[] signature in signatures) { signature[signature.Length - 1] ^= 0xFF; // flip some bits Assert.False(VerifyData(ecdsa, dataArray, signature, hashAlgorithm), "Verify Tampered 1"); Assert.False(ecdsa.VerifyHash(halg.ComputeHash(dataArray), signature), "Verify Tampered 4"); } } private class ByteArrayComparer : IEqualityComparer<byte[]> { public bool Equals(byte[] x, byte[] y) { return x.SequenceEqual(y); } public int GetHashCode(byte[] obj) { int h = 5381; foreach (byte b in obj) { h = unchecked((h << 5) + h) ^ b.GetHashCode(); } return h; } } } }
//------------------------------------------------------------------------------ // <copyright file="DataServiceBuildProvider.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ // Putting the build provider in the System.Data.Services.Design namespace forces DataSvcUtil.exe to also take dependency on System.Web.dll // Hence putting this in a different namespace. [module: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "System.Data.Services.BuildProvider")] namespace System.Data.Services.BuildProvider { using System; using System.Collections; using System.Data.Services.Design; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using System.Web; using System.Web.Compilation; using System.Web.Hosting; using System.Xml; using System.Xml.Schema; /// <summary> /// A build provider for data service references in website projects. /// Data services (Astoria): in order to support Astoria "data services" we added code /// to scan for "datasvcmap" files in addition to the existing "svcmap" files. For data services /// we call into the Astoria code-gen library to do the work instead of the regular indigo path. /// /// </summary> [FolderLevelBuildProviderAppliesTo(FolderLevelBuildProviderAppliesTo.WebReferences)] [System.Security.SecurityCritical] public class DataServiceBuildProvider : BuildProvider { private const string WebRefDirectoryName = "App_WebReferences"; private const string DataSvcMapExtension = ".datasvcmap"; private const string UseCollectionParameterName = "UseDataServiceCollection"; private const string VersionParameterName = "Version"; private const string Version1Dot0 = "1.0"; private const string Version2Dot0 = "2.0"; /// <summary> /// Search through the folder represented by base.VirtualPath for .svcmap and .datasvcmap files. /// If any .svcmap/.datasvcmap files are found, then generate proxy code for them into the /// specified assemblyBuilder. /// </summary> /// <param name="assemblyBuilder">Where to generate the proxy code</param> /// <remarks> /// When this routine is called, it is expected that the protected VirtualPath property has /// been set to the folder to scan for .svcmap/.datasvcmap files. /// </remarks> [System.Security.SecuritySafeCritical] public override void GenerateCode(AssemblyBuilder assemblyBuilder) { // Go through all the svcmap files in the directory VirtualDirectory vdir = GetVirtualDirectory(VirtualPath); foreach (VirtualFile child in vdir.Files) { string extension = IO.Path.GetExtension(child.VirtualPath); if (extension.Equals(DataSvcMapExtension, StringComparison.OrdinalIgnoreCase)) { // NOTE: the WebReferences code requires a physical path, so this feature // cannot work with a non-file based VirtualPathProvider string physicalPath = HostingEnvironment.MapPath(child.VirtualPath); GenerateCodeFromDataServiceMapFile(physicalPath, assemblyBuilder); } } } /// <summary> /// Generate code for one .datasvcmap file /// </summary> /// <param name="mapFilePath">The physical path to the data service map file</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "XmlReader over StringReader doesn't need to be disposed")] private void GenerateCodeFromDataServiceMapFile(string mapFilePath, AssemblyBuilder assemblyBuilder) { try { MapFileLoader loader = new MapFileLoader(mapFilePath); loader.LoadDataSvcMapFile(); MapFileLoader.AddAssemblyReferences(assemblyBuilder, loader.UseDataServiceCollection); string edmxContent = loader.GetEdmxContent(); System.Data.Services.Design.EntityClassGenerator generator = new System.Data.Services.Design.EntityClassGenerator(LanguageOption.GenerateCSharpCode); // the EntityClassGenerator works on streams/writers, does not return a CodeDom // object, so we use CreateCodeFile instead of compile units. using (TextWriter writer = assemblyBuilder.CreateCodeFile(this)) { generator.UseDataServiceCollection = loader.UseDataServiceCollection; generator.Version = loader.Version; // Note: currently GenerateCode never actually returns values // for the error case (even though it returns an IList of error // objects). Instead it throws on error. This may need some tweaking // later on. #if DEBUG object errors = #endif generator.GenerateCode( XmlReader.Create(new StringReader(edmxContent)), writer, GetGeneratedNamespace()); #if DEBUG Debug.Assert( errors == null || !(errors is ICollection) || ((ICollection)errors).Count == 0, "Errors reported through the return value. Expected an exception"); #endif writer.Flush(); } } catch (Exception ex) { string errorMessage = ex.Message; errorMessage = String.Format(CultureInfo.CurrentCulture, "{0}: {1}", IO.Path.GetFileName(mapFilePath), errorMessage); throw new InvalidOperationException(errorMessage, ex); } } /// <summary> /// Retrieve a VirtualDirectory for the given virtual path /// </summary> /// <param name="virtualPath"></param> /// <returns></returns> private VirtualDirectory GetVirtualDirectory(string virtualPath) { return HostingEnvironment.VirtualPathProvider.GetDirectory(VirtualPath); } /// <summary> /// Caculate our namespace for current VirtualPath... /// </summary> /// <return></return> /// <remarks></remarks> private string GetGeneratedNamespace() { // First, determine the namespace to use for code generation. This is based on the // relative path of the reference from its base App_WebReferences directory // ... Get the virtual path to the App_WebReferences folder, e.g "/MyApp/App_WebReferences" string rootWebRefDirVirtualPath = GetWebRefDirectoryVirtualPath(); // ... Get the folder's directory path, e.g "/MyApp/Application_WebReferences/Foo/Bar", // where we'll look for .svcmap files string currentSubfolderUnderWebReferences = this.VirtualPath; if (currentSubfolderUnderWebReferences == null) { Debug.Fail("Shouldn't be given a null virtual path"); throw new InvalidOperationException(); } return CalculateGeneratedNamespace(rootWebRefDirVirtualPath, currentSubfolderUnderWebReferences); } /// <summary> /// Determine the namespace to use for the proxy generation /// </summary> /// <param name="webReferencesRootVirtualPath">The path to the App_WebReferences folder</param> /// <param name="virtualPath">The path to the current folder</param> /// <returns></returns> private static string CalculateGeneratedNamespace(string webReferencesRootVirtualPath, string virtualPath) { // ... Ensure both folders have trailing slashes webReferencesRootVirtualPath = VirtualPathUtility.AppendTrailingSlash(webReferencesRootVirtualPath); virtualPath = VirtualPathUtility.AppendTrailingSlash(virtualPath); Debug.Assert(virtualPath.StartsWith(webReferencesRootVirtualPath, StringComparison.OrdinalIgnoreCase), "We expected to be inside the App_WebReferences folder"); // ... Determine the namespace to use, based on the directory structure where the .svcmap file // is found. if (webReferencesRootVirtualPath.Length == virtualPath.Length) { Debug.Assert(string.Equals(webReferencesRootVirtualPath, virtualPath, StringComparison.OrdinalIgnoreCase), "We expected to be in the App_WebReferences directory"); // If it's the root WebReferences dir, use the empty namespace return String.Empty; } else { // We're in a subdirectory of App_WebReferences. // Get the directory's relative path from App_WebReferences, e.g. "Foo/Bar" virtualPath = VirtualPathUtility.RemoveTrailingSlash(virtualPath).Substring(webReferencesRootVirtualPath.Length); // Split it into chunks separated by '/' string[] chunks = virtualPath.Split('/'); // Turn all the relevant chunks into valid namespace chunks for (int i = 0; i < chunks.Length; i++) { chunks[i] = MakeValidTypeNameFromString(chunks[i]); } // Put the relevant chunks back together to form the namespace return String.Join(".", chunks); } } /// <summary> /// Returns the app domain's application virtual path [from HttpRuntime.AppDomainAppVPath]. /// Includes trailing slash, e.g. "/MyApp/" /// </summary> private static string GetAppDomainAppVirtualPath() { string appVirtualPath = HttpRuntime.AppDomainAppVirtualPath; if (appVirtualPath == null) { Debug.Fail("Shouldn't get a null app virtual path from the app domain"); throw new InvalidOperationException(); } return VirtualPathUtility.AppendTrailingSlash(VirtualPathUtility.ToAbsolute(appVirtualPath)); } /// <summary> /// Gets the virtual path to the application's App_WebReferences directory, e.g. "/MyApp/App_WebReferences/" /// </summary> private static string GetWebRefDirectoryVirtualPath() { return VirtualPathUtility.Combine(GetAppDomainAppVirtualPath(), WebRefDirectoryName + @"\"); } /// <summary> /// Return a valid type name from a string by changing any character /// that's not a letter or a digit to an '_'. /// </summary> /// <param name="s"></param> /// <returns></returns> internal static string MakeValidTypeNameFromString(string typeName) { if (String.IsNullOrEmpty(typeName)) throw new ArgumentNullException("typeName"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < typeName.Length; i++) { // Make sure it doesn't start with a digit (ASURT 31134) if (i == 0 && Char.IsDigit(typeName[0])) sb.Append('_'); if (Char.IsLetterOrDigit(typeName[i])) sb.Append(typeName[i]); else sb.Append('_'); } // Identifier can't be a single underscore character string validTypeName = sb.ToString(); if (validTypeName.Equals("_", StringComparison.Ordinal)) { validTypeName = "__"; } return validTypeName; } private class MapFileLoader { /// <summary>Namespace for the dataSvcMap file.</summary> private const string dataSvcSchemaNamespace = "urn:schemas-microsoft-com:xml-dataservicemap"; /// <summary>xsd Schema for the datasvcmap file</summary> private static XmlSchemaSet serviceMapSchemaSet; /// <summary>xsd Schema for the datasvcmap file</summary> private static XmlNamespaceManager namespaceManager; /// <summary>full path of the data svc map file.</summary> private string dataSvcMapFilePath; /// <summary>Name of the edmx schema file.</summary> private string edmxSchemaFileName; /// <summary>True if DataServiceCollection needs to be used, otherwise false.</summary> private bool useDataServiceCollection; /// <summary>Version as specified in the svcmap file.</summary> private DataServiceCodeVersion version; /// <summary> /// Creates the new instance of the dataSvcMapFileLoader. /// </summary> /// <param name="mapFilePath">filePath for the dataSvcMap file.</param> internal MapFileLoader(string mapFilePath) { Debug.Assert(!String.IsNullOrEmpty(mapFilePath), "mapFilePath cannot be null or empty"); this.dataSvcMapFilePath = mapFilePath; } /// <summary>True if the binding code needs to be generated, otherwise false.</summary> internal bool UseDataServiceCollection { get { return this.useDataServiceCollection; } } /// <summary>Returns the version as specified in the svcmap file.</summary> internal DataServiceCodeVersion Version { get { return this.version; } } /// <summary> /// Returns the XMlSchemaSet against which the dataSvcMap needs to be validated against. /// </summary> private static XmlSchemaSet ServiceMapSchemaSet { get { if (serviceMapSchemaSet == null) { XmlSchema serviceMapSchema; System.IO.Stream fileStream = typeof(WCFBuildProvider).Assembly.GetManifestResourceStream(@"System.Web.Compilation.WCFModel.Schema.DataServiceMapSchema.xsd"); System.Diagnostics.Debug.Assert(fileStream != null, "Couldn't find ServiceMapSchema.xsd resource"); serviceMapSchema = XmlSchema.Read(fileStream, null); serviceMapSchemaSet = new XmlSchemaSet(); serviceMapSchemaSet.Add(serviceMapSchema); } return serviceMapSchemaSet; } } /// <summary> /// Returns the namespace manager for the dataSvcMap file. /// </summary> private static XmlNamespaceManager NamespaceManager { get { if (namespaceManager == null) { namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ds", dataSvcSchemaNamespace); } return namespaceManager; } } /// <summary> /// Read the contents from the edmx file. /// </summary> /// <returns>a string instance containing all the contents of the edmx file.</returns> internal string GetEdmxContent() { string edmxFilePath = IO.Path.Combine(IO.Path.GetDirectoryName(this.dataSvcMapFilePath), this.edmxSchemaFileName); return IO.File.ReadAllText(edmxFilePath); } /// <summary> /// Load the DataSvcMapFile from the given location /// </summary> internal void LoadDataSvcMapFile() { using (System.IO.TextReader mapFileReader = IO.File.OpenText(this.dataSvcMapFilePath)) { XmlDocument document = LoadAndValidateFile(mapFileReader); this.edmxSchemaFileName = GetMetadataFileNameFromMapFile(document); ValidateParametersInMapFile(document, out this.version, out this.useDataServiceCollection); } } /// <summary> /// Add the assembly references to the assembly builder depending on whether the databinding is enabled or not. /// </summary> /// <param name="assemblyBuilder">instance of assemblyBuilder where we need to add assembly references.</param> /// <param name="enableDataBinding">indicates whether databinding is enabled or not.</param> internal static void AddAssemblyReferences(AssemblyBuilder assemblyBuilder, bool useDataServiceCollection) { assemblyBuilder.AddAssemblyReference(typeof(System.Data.Services.Client.DataServiceContext).Assembly); if (useDataServiceCollection) { // TODO: SQLBUDT 707098 - Use the helper method which returns the FrameworkName instance as defined in System.Runtime.Versioning namespace. // When generating data binding code for .Net framework 3.5, we need to load the right version of windows base here. // 3.5 Framework version: WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 // In 4.0, ObservableCollection<> class was moved into System.dll. Hence no need to do anything. if (BuildManager.TargetFramework.Version.Major < 4) { assemblyBuilder.AddAssemblyReference(System.Reflection.Assembly.Load("WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")); } } } /// <summary> /// Validates the given map file. /// </summary> /// <param name="mapFileReader">instance of text reader containing the map file.</param> /// <returns>returns an instance of XmlDocument containing the map file.</returns> private static XmlDocument LoadAndValidateFile(TextReader mapFileReader) { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.Schemas = ServiceMapSchemaSet; readerSettings.ValidationType = ValidationType.Schema; readerSettings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings; // Validation Handler ValidationEventHandler handler = delegate(object sender, System.Xml.Schema.ValidationEventArgs e) { if (e.Severity == XmlSeverityType.Error) { throw e.Exception; } }; // Create an xmlDocument and load the map file XmlDocument document = new XmlDocument(); document.Load(mapFileReader); // validate the map file against the xsd document.Schemas = ServiceMapSchemaSet; document.Validate(handler); return document; } /// <summary> /// Gets the metadata file name from the map file. /// </summary> /// <param name="document">instance of xml document which refers to the map file.</param> /// <returns>returns the metadata file path as specified in the map file.</returns> private static string GetMetadataFileNameFromMapFile(XmlDocument document) { // The xsd already validates that there should be exactly one MetadataFile element present. XmlNode node = document.SelectSingleNode("/ds:ReferenceGroup/ds:Metadata/ds:MetadataFile", NamespaceManager); Debug.Assert(node != null, "MetadataFile node must be present"); // Both the attributes FileName and MetadataType must be present, // since the xsd already does this validation. // xsd also does the validation that these attributes cannot be empty. string edmxSchemaFileName = node.Attributes["FileName"].Value; string metadataType = node.Attributes["MetadataType"].Value; // Ideally, this check must be moved in the xsd, so that user gets all the information about where // exactly the error is - file information, line number etc. We currently only have file information // with us if (metadataType != "Edmx") { throw new ArgumentException(Strings.InvalidMetadataType(metadataType, "MetadataType", "Edmx")); } return edmxSchemaFileName; } /// <summary> /// Validate the parameters list in the map file. Currently only EnableDataBinding parameter is supported. /// </summary> /// <param name="document">instance of xml documents which contains the map file.</param> /// <returns>returns true if the data binding parameter is specified and its value is true, otherwise returns false.</returns> private static void ValidateParametersInMapFile(XmlDocument document, out DataServiceCodeVersion version, out bool useDataServiceCollection) { bool isSentinalTypePresent = BuildManager.GetType("System.Data.Services.Client.DataServiceCollection`1", false /*throwOnError*/) != null; // Validate all the parameters specified in the map file XmlNodeList parameters = document.SelectNodes("/ds:ReferenceGroup/ds:Parameters/ds:Parameter", NamespaceManager); bool? useCollectionParamValue = null; DataServiceCodeVersion? versionParamValue = null; if (parameters != null && parameters.Count != 0) { // currently only one parameter can be specified. EnableDataBinding - whose valid values are 'true and 'false' foreach (XmlNode p in parameters) { // Name and value attributes must be present, since they are verified by the xsd XmlAttribute nameAttribute = p.Attributes["Name"]; XmlAttribute valueAttribute = p.Attributes["Value"]; if (nameAttribute.Value == VersionParameterName) { ValidateVersionParameter(ref versionParamValue, valueAttribute.Value); } else if (nameAttribute.Value == UseCollectionParameterName) { ValidateBooleanParameter(ref useCollectionParamValue, valueAttribute.Value, UseCollectionParameterName); } else { throw new ArgumentException( Strings.InvalidParameterName( nameAttribute.Value, String.Format(CultureInfo.InvariantCulture, "'{0}', '{1}'", VersionParameterName, UseCollectionParameterName))); } } } if (!isSentinalTypePresent && useCollectionParamValue.HasValue && useCollectionParamValue == true) { throw new ArgumentException(Strings.UseDataServiceCollectionCannotBeSetToTrue(UseCollectionParameterName)); } version = versionParamValue.HasValue ? versionParamValue.Value : DataServiceCodeVersion.V1; useDataServiceCollection = useCollectionParamValue.HasValue ? useCollectionParamValue.Value : false; } /// <summary> /// Validate the boolean parameter value as specified in the .svcmap file. /// </summary> /// <param name="value">parameter value as specified in the svcmap file.</param> /// <param name="parameterName">name of the parameter whose value is getting validated.</param> /// <returns>boolean value as specified in the svcmap file.</returns> private static void ValidateBooleanParameter(ref bool? paramValue, string value, string parameterName) { if (paramValue == null) { try { paramValue = XmlConvert.ToBoolean(value); } catch (FormatException e) { throw new ArgumentException(Strings.InvalidBooleanParameterValue(value, parameterName), e); } } else { throw new ArgumentException(Strings.ParameterSpecifiedMultipleTimes(UseCollectionParameterName)); } } /// <summary> /// Validate the version parameter value is valid. /// </summary> /// <param name="parameterValue">version parameter value as specified in the .svcmap file.</param> /// <returns>instance of DataServiceCodeVersion, which contains the value of the version parameter as specified in the svcmap file.</returns> private static void ValidateVersionParameter(ref DataServiceCodeVersion? version, string parameterValue) { if (version == null) { if (parameterValue == Version1Dot0) { version = DataServiceCodeVersion.V1; } else if (parameterValue == Version2Dot0) { version = DataServiceCodeVersion.V2; } else { throw new ArgumentException( Strings.InvalidVersionParameterValue( parameterValue, VersionParameterName, String.Format(CultureInfo.InvariantCulture, "'{0}', '{1}'", Version1Dot0, Version2Dot0))); } } else { throw new ArgumentException(Strings.ParameterSpecifiedMultipleTimes(VersionParameterName)); } } } } }
/* * 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 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.Reflection; using System.Threading; using log4net; using log4net.Appender; using log4net.Repository.Hierarchy; using OpenSim.GridLaunch.GUI; using OpenSim.GridLaunch.GUI.Network; namespace OpenSim.GridLaunch { class Program { public static readonly string ConfigFile = "OpenSim.GridLaunch.ini"; internal static Dictionary<string, AppExecutor> AppList = new Dictionary<string, AppExecutor>(); private static readonly int delayBetweenExecuteSeconds = 10; //private static readonly int consoleReadIntervalMilliseconds = 50; ////private static readonly Timer readTimer = new Timer(readConsole, null, Timeout.Infinite, Timeout.Infinite); //private static Thread timerThread; //private static object timerThreadLock = new object(); private static IGUI GUIModule; private static string GUIModuleName = ""; public static readonly CommandProcessor Command = new CommandProcessor(); public static readonly Settings Settings = new Settings(); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public delegate void AppConsoleOutputDelegate(string App, string Text); public static event AppConsoleOutputDelegate AppConsoleOutput; public delegate void AppConsoleErrorDelegate(string App, string Text); public static event AppConsoleErrorDelegate AppConsoleError; public delegate void AppCreatedDelegate(string App); public static event AppCreatedDelegate AppCreated; public delegate void AppRemovedDelegate(string App); public static event AppRemovedDelegate AppRemoved; internal static void FireAppConsoleOutput(string App, string Text) { if (AppConsoleOutput != null) AppConsoleOutput(App, Text); } internal static void FireAppConsoleError(string App, string Text) { if (AppConsoleError != null) AppConsoleError(App, Text); } private static readonly object startStopLock = new object(); public static string Name { get { return "OpenSim Grid executor"; } } #region Start/Shutdown static void Main(string[] args) { log4net.Config.XmlConfigurator.Configure(); // Startup m_log.Info(Name); m_log.Info(new string('-', Name.Length)); // Read settings Settings.LoadConfig(ConfigFile); // Command line arguments override settings Settings.ParseCommandArguments(args); // Start GUI module StartGUIModule(); // Start the processes ThreadPool.QueueUserWorkItem(startProcesses); // Hand over thread control to whatever GUI module GUIModule.StartGUI(); // GUI module returned, we are done Shutdown(); } private static void StartGUIModule() { // Create GUI module GUIModuleName = Settings["GUI"]; switch (GUIModuleName.ToLower()) { case "winform": GUIModuleName = "WinForm"; GUIModule = new GUI.WinForm.ProcessPanel(); break; case "service": GUIModuleName = "Service"; GUIModule = new Service(); break; case "tcpd": GUIModuleName = "TCPD"; GUIModule = new TCPD(); break; case "console": default: GUIModuleName = "Console"; GUIModule = new GUI.Console.Console(); break; } m_log.Info("GUI type: " + GUIModuleName); } internal static void Shutdown() { // Stop the processes stopProcesses(); lock (startStopLock) { // Stop GUI module if (GUIModule != null) { GUIModule.StopGUI(); GUIModule = null; } } } internal static void SafeDisposeOf(object obj) { IDisposable o = obj as IDisposable; try { if (o != null) o.Dispose(); } catch { } } #endregion #region Start / Stop applications private static void startProcesses(Object stateInfo) { // Stop before starting stopProcesses(); // Start console read timer //timer_Start(); // Start the applications foreach (string file in new ArrayList(Settings.Components.Keys)) { // Is this file marked for startup? if (Settings.Components[file]) { AppExecutor app = new AppExecutor(file); app.Start(); AppList.Add(file, app); if (AppCreated != null) AppCreated(app.File); System.Threading.Thread.Sleep(1000*delayBetweenExecuteSeconds); } } } private static void stopProcesses() { // Stop timer //timer_Stop(); // Lock so we don't collide with any timer still executing on AppList lock (AppList) { // Start the applications foreach (AppExecutor app in AppList.Values) { try { m_log.Info("Stopping: " + app.File); app.Stop(); } catch (Exception ex) { m_log.ErrorFormat("Exception while stopping \"{0}\": {1}", app.File, ex.ToString()); } finally { if (AppRemoved != null) AppRemoved(app.File); app.Dispose(); } } AppList.Clear(); } } #endregion public static void Write(string App, string Text) { // Check if it is a commands bool isCommand = Command.Process(App, Text); // Write to stdInput of app if (!isCommand && AppList.ContainsKey(App)) AppList[App].Write(Text); } public static void WriteLine(string App, string Text) { // Check if it is a commands bool isCommand = Command.Process(App, Text); // Write to stdInput of app if (!isCommand && AppList.ContainsKey(App)) AppList[App].WriteLine(Text); } } }
// 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.Xml; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Text.RegularExpressions; using Microsoft.Build.Framework; using Microsoft.Build.BuildEngine.Shared; namespace Microsoft.Build.BuildEngine { /// <summary> /// This class contains utility methods for the MSBuild engine. /// </summary> /// <owner>RGoel</owner> static public class Utilities { private readonly static Regex singlePropertyRegex = new Regex(@"^\$\(([^\$\(\)]*)\)$"); /// <summary> /// Update our table which keeps track of all the properties that are referenced /// inside of a condition and the string values that they are being tested against. /// So, for example, if the condition was " '$(Configuration)' == 'Debug' ", we /// would get passed in leftValue="$(Configuration)" and rightValueExpanded="Debug". /// This call would add the string "Debug" to the list of possible values for the /// "Configuration" property. /// /// This method also handles the case when two or more properties are being /// concatenated together with a vertical bar, as in ' /// $(Configuration)|$(Platform)' == 'Debug|x86' /// </summary> /// <param name="conditionedPropertiesTable"></param> /// <param name="leftValue"></param> /// <param name="rightValueExpanded"></param> /// <owner>rgoel</owner> internal static void UpdateConditionedPropertiesTable ( Hashtable conditionedPropertiesTable, // Hash table containing a StringCollection // of possible values, keyed by property name. string leftValue, // The raw value on the left side of the operator string rightValueExpanded // The fully expanded value on the right side // of the operator. ) { if ((conditionedPropertiesTable != null) && (rightValueExpanded.Length > 0)) { // The left side should be exactly "$(propertyname)" or "$(propertyname1)|$(propertyname2)" // or "$(propertyname1)|$(propertyname2)|$(propertyname3)", etc. Anything else, // and we don't touch the table. // Split up the leftValue into pieces based on the vertical bar character. string[] leftValuePieces = leftValue.Split(new char[]{'|'}); // Loop through each of the pieces. for (int i = 0 ; i < leftValuePieces.Length ; i++) { Match singlePropertyMatch = singlePropertyRegex.Match(leftValuePieces[i]); if (singlePropertyMatch.Success) { // Find the first vertical bar on the right-hand-side expression. int indexOfVerticalBar = rightValueExpanded.IndexOf('|'); string rightValueExpandedPiece; // If there was no vertical bar, then just use the remainder of the right-hand-side // expression as the value of the property, and terminate the loop after this iteration. // Also, if we're on the last segment of the left-hand-side, then use the remainder // of the right-hand-side expression as the value of the property. if ((indexOfVerticalBar == -1) || (i == (leftValuePieces.Length - 1))) { rightValueExpandedPiece = rightValueExpanded; i = leftValuePieces.Length; } else { // If we found a vertical bar, then the portion before the vertical bar is the // property value which we will store in our table. Then remove that portion // from the original string so that the next iteration of the loop can easily search // for the first vertical bar again. rightValueExpandedPiece = rightValueExpanded.Substring(0, indexOfVerticalBar); rightValueExpanded = rightValueExpanded.Substring(indexOfVerticalBar + 1); } // Capture the property name out of the regular expression. string propertyName = singlePropertyMatch.Groups[1].ToString(); // Get the string collection for this property name, if one already exists. StringCollection conditionedPropertyValues = (StringCollection) conditionedPropertiesTable[propertyName]; // If this property is not already represented in the table, add a new entry // for it. if (conditionedPropertyValues == null) { conditionedPropertyValues = new StringCollection(); conditionedPropertiesTable[propertyName] = conditionedPropertyValues; } // If the "rightValueExpanded" is not already in the string collection // for this property name, add it now. if (!conditionedPropertyValues.Contains(rightValueExpandedPiece)) { conditionedPropertyValues.Add(rightValueExpandedPiece); } } } } } /* * Method: GatherReferencedPropertyNames * Owner: DavidLe * * Find and record all of the properties that are referenced in the given * condition. * * FUTURE: it is unfortunate that we have to completely parse+evaluate the expression */ internal static void GatherReferencedPropertyNames ( string condition, // Can be null XmlAttribute conditionAttribute, // XML attribute on which the condition is evaluated Expander expander, // The set of properties to use for expansion Hashtable conditionedPropertiesTable // Can be null ) { EvaluateCondition(condition, conditionAttribute, expander, conditionedPropertiesTable, ParserOptions.AllowProperties | ParserOptions.AllowItemLists, null, null); } // An array of hashtables with cached expression trees for all the combinations of condition strings // and parser options private static volatile Hashtable[] cachedExpressionTrees = new Hashtable[8 /* == ParserOptions.AllowAll*/] { new Hashtable(StringComparer.OrdinalIgnoreCase), new Hashtable(StringComparer.OrdinalIgnoreCase), new Hashtable(StringComparer.OrdinalIgnoreCase), new Hashtable(StringComparer.OrdinalIgnoreCase), new Hashtable(StringComparer.OrdinalIgnoreCase), new Hashtable(StringComparer.OrdinalIgnoreCase), new Hashtable(StringComparer.OrdinalIgnoreCase), new Hashtable(StringComparer.OrdinalIgnoreCase) }; /// <summary> /// Evaluates a string representing a condition from a "condition" attribute. /// If the condition is a malformed string, it throws an InvalidProjectFileException. /// This method uses cached expression trees to avoid generating them from scratch every time it's called. /// This method is thread safe and is called from engine and task execution module threads /// </summary> /// <param name="condition">Can be null</param> /// <param name="conditionAttribute">XML attribute on which the condition is evaluated</param> /// <param name="expander">All the data available for expanding embedded properties, metadata, and items</param> /// <param name="itemListOptions"></param> /// <returns>true, if the expression evaluates to true, otherwise false</returns> internal static bool EvaluateCondition ( string condition, XmlAttribute conditionAttribute, Expander expander, ParserOptions itemListOptions, Project parentProject ) { return EvaluateCondition(condition, conditionAttribute, expander, parentProject.ConditionedProperties, itemListOptions, parentProject.ParentEngine.LoggingServices, parentProject.ProjectBuildEventContext); } /// <summary> /// Evaluates a string representing a condition from a "condition" attribute. /// If the condition is a malformed string, it throws an InvalidProjectFileException. /// This method uses cached expression trees to avoid generating them from scratch every time it's called. /// This method is thread safe and is called from engine and task execution module threads /// </summary> /// <param name="condition">Can be null</param> /// <param name="conditionAttribute">XML attribute on which the condition is evaluated</param> /// <param name="expander">All the data available for expanding embedded properties, metadata, and items</param> /// <param name="itemListOptions"></param> /// <param name="loggingServices">Can be null</param> /// <param name="eventContext"> contains contextual information for logging events</param> /// <returns>true, if the expression evaluates to true, otherwise false</returns> internal static bool EvaluateCondition ( string condition, XmlAttribute conditionAttribute, Expander expander, ParserOptions itemListOptions, EngineLoggingServices loggingServices, BuildEventContext buildEventContext ) { return EvaluateCondition(condition, conditionAttribute, expander, null, itemListOptions, loggingServices, buildEventContext); } /// <summary> /// Evaluates a string representing a condition from a "condition" attribute. /// If the condition is a malformed string, it throws an InvalidProjectFileException. /// This method uses cached expression trees to avoid generating them from scratch every time it's called. /// This method is thread safe and is called from engine and task execution module threads /// </summary> /// <param name="condition">Can be null</param> /// <param name="conditionAttribute">XML attribute on which the condition is evaluated</param> /// <param name="expander">All the data available for expanding embedded properties, metadata, and items</param> /// <param name="conditionedPropertiesTable">Can be null</param> /// <param name="itemListOptions"></param> /// <param name="loggingServices">Can be null</param> /// <param name="buildEventContext"> contains contextual information for logging events</param> /// <returns>true, if the expression evaluates to true, otherwise false</returns> internal static bool EvaluateCondition ( string condition, XmlAttribute conditionAttribute, Expander expander, Hashtable conditionedPropertiesTable, ParserOptions itemListOptions, EngineLoggingServices loggingServices, BuildEventContext buildEventContext ) { ErrorUtilities.VerifyThrow((conditionAttribute != null) || (string.IsNullOrEmpty(condition)), "If condition is non-empty, you must provide the XML node representing the condition."); // An empty condition is equivalent to a "true" condition. if (string.IsNullOrEmpty(condition)) { return true; } Hashtable cachedExpressionTreesForCurrentOptions = cachedExpressionTrees[(int)itemListOptions]; // Try and see if we have an expression tree for this condition already GenericExpressionNode parsedExpression = (GenericExpressionNode) cachedExpressionTreesForCurrentOptions[condition]; if (parsedExpression == null) { Parser conditionParser = new Parser(); #region REMOVE_COMPAT_WARNING conditionParser.LoggingServices = loggingServices; conditionParser.LogBuildEventContext = buildEventContext; #endregion parsedExpression = conditionParser.Parse(condition, conditionAttribute, itemListOptions); // It's possible two threads will add a different tree to the same entry in the hashtable, // but it should be rare and it's not a problem - the previous entry will be thrown away. // We could ensure no dupes with double check locking but it's not really necessary here. // Also, we don't want to lock on every read. lock (cachedExpressionTreesForCurrentOptions) { cachedExpressionTreesForCurrentOptions[condition] = parsedExpression; } } ConditionEvaluationState state = new ConditionEvaluationState(conditionAttribute, expander, conditionedPropertiesTable, condition); bool result; // We are evaluating this expression now and it can cache some state for the duration, // so we don't want multiple threads working on the same expression lock (parsedExpression) { result = parsedExpression.Evaluate(state); parsedExpression.ResetState(); } return result; } /// <summary> /// Sets the inner XML/text of the given XML node, escaping as necessary. /// </summary> /// <owner>SumedhK</owner> /// <param name="node"></param> /// <param name="s">Can be empty string, but not null.</param> internal static void SetXmlNodeInnerContents(XmlNode node, string s) { ErrorUtilities.VerifyThrow(s != null, "Need value to set."); if (s.IndexOf('<') != -1) { // If the value looks like it probably contains XML markup ... try { // Attempt to store it verbatim as XML. node.InnerXml = s; return; } catch (XmlException) { // But that may fail, in the event that "s" is not really well-formed // XML. Eat the exception and fall through below ... } } // The value does not contain valid XML markup. Store it as text, so it gets // escaped properly. node.InnerText = s; } /// <summary> /// Extracts the inner XML/text of the given XML node, unescaping as necessary. /// </summary> /// <owner>SumedhK</owner> /// <param name="node"></param> /// <returns>Inner XML/text of specified node.</returns> internal static string GetXmlNodeInnerContents(XmlNode node) { // XmlNode.InnerXml gives back a string that consists of the set of characters // in between the opening and closing elements of the XML node, without doing any // unescaping. Any "strange" character sequences (like "<![CDATA[...]]>" will remain // exactly so and will not be translated or interpreted. The only modification that // .InnerXml will do is that it will normalize any Xml contained within. This means // normalizing whitespace between XML attributes and quote characters that surround XML // attributes. If PreserveWhitespace is false, then it will also normalize whitespace // between elements. // // XmlNode.InnerText strips out any Xml contained within, and then unescapes the rest // of the text. So if the remaining text contains certain character sequences such as // "&amp;" or "<![CDATA[...]]>", these will be translated into their equivalent representations. // // It's hard to explain, but much easier to demonstrate with examples: // // Original XML XmlNode.InnerText XmlNode.InnerXml // =========================== ============================== ====================================== // // <a><![CDATA[whatever]]></a> whatever <![CDATA[whatever]]> // // <a>123<MyNode/>456</a> 123456 123<MyNode />456 // // <a>123456</a> 123456 123456 // // <a>123<MyNode b='&lt;'/>456</a> 123456 123<MyNode b="&lt;" />456 // // <a>123&amp;456</a> 123&456 123&amp;456 // So the trick for MSBuild when interpreting a property value is to know which one to // use ... InnerXml or InnerText. There are two basic scenarios we care about. // // 1.) The first scenario is that the user is trying to create a property whose // contents are actually XML. That is to say that the contents may be written // to a XML file, or may be passed in as a string to XmlDocument.LoadXml. // In this case, we would want to use XmlNode.InnerXml, because we DO NOT want // character sequences to be unescaped. If we did unescape them, then whatever // XML parser tried to read in the stream as XML later on would totally barf. // // 2.) The second scenario is the the user is trying to create a property that // is just intended to be treated as a string. That string may be very large // and could contain all sorts of whitespace, carriage returns, special characters, // etc. But in the end, it's just a big string. In this case, whatever // task is actually processing this string ... it's not going to know anything // about character sequences such as &amp; and &lt;. These character sequences // are specific to XML markup. So, here we want to use XmlNode.InnerText so that // the character sequences get unescaped into their actual character before // the string is passed to the task (or wherever else the property is used). // Of course, if the string value of the property needs to contain characters // like <, >, &, etc., then the user must XML escape these characters otherwise // the XML parser reading the project file will croak. Or if the user doesn't // want to escape every instance of these characters, he can surround the whole // thing with a CDATA tag. Again, if he does this, we don't want the task to // receive the C, D, A, T, A as part of the string ... this should be stripped off. // Again, using XmlNode.InnerText takes care of this. // // 2b.) A variation of the second scenario is that the user is trying to create a property // that is just intended to be a string, but wants to comment out part of the string. // For example, it's a semicolon separated list that's going ultimately to end up in a list. // eg. (DDB #56841) // // <BuildDirectories> // <!-- // env\TestTools\tshell\pkg; // --> // ndp\fx\src\VSIP\FrameWork; // ndp\fx\src\xmlTools; // ddsuites\src\vs\xmlTools; // </BuildDirectories> // // In this case, we want to treat the string as text, so that we don't retrieve the comment. // We only want to retrieve the comment if there's some other XML in there. The // mere presence of an XML comment shouldn't make us think the value is XML. // // Given these two scenarios, how do we know whether the user intended to treat // a property value as XML or text? We use a simple heuristic which is that if // XmlNode.InnerXml contains any "<" characters, then there pretty much has to be // XML in there, so we'll just use XmlNode.InnerXml. If there are no "<" characters that aren't merely comments, // then we assume it's to be treated as text and we use XmlNode.InnerText. Also, if // it looks like the whole thing is one big CDATA block, then we also use XmlNode.InnerText. // XmlNode.InnerXml is much more expensive than InnerText. Don't use it for trivial cases. // (single child node with a trivial value or no child nodes) if (!node.HasChildNodes) { return string.Empty; } if (node.ChildNodes.Count == 1 && (node.FirstChild.NodeType == XmlNodeType.Text || node.FirstChild.NodeType == XmlNodeType.CDATA)) { return node.InnerText; } string innerXml = node.InnerXml; // If there is no markup under the XML node (detected by the presence // of a '<' sign int firstLessThan = innerXml.IndexOf('<'); if (firstLessThan == -1) { // return the inner text so it gets properly unescaped return node.InnerText; } bool containsNoTagsOtherThanComments = ContainsNoTagsOtherThanComments(innerXml, firstLessThan); // ... or if the only XML is comments, if (containsNoTagsOtherThanComments) { // return the inner text so the comments are stripped // (this is how one might comment out part of a list in a property value) return node.InnerText; } // ...or it looks like the whole thing is a big CDATA tag ... bool startsWithCData = (innerXml.IndexOf("<![CDATA[", StringComparison.Ordinal) == 0); if (startsWithCData) { // return the inner text so it gets properly extracted from the CDATA return node.InnerText; } // otherwise, it looks like genuine XML; return the inner XML so that // tags and comments are preserved and any XML escaping is preserved return innerXml; } /// <summary> /// Figure out whether there are any XML tags, other than comment tags, /// in the string. /// </summary> /// <remarks> /// We know the string coming in is a valid XML fragment. (The project loaded after all.) /// So for example we can ignore an open comment tag without a matching closing comment tag. /// </remarks> private static bool ContainsNoTagsOtherThanComments(string innerXml, int firstLessThan) { bool insideComment = false; for (int i = firstLessThan; i < innerXml.Length; i++) { if (!insideComment) { // XML comments start with exactly "<!--" if (i < innerXml.Length - 3 && innerXml[i] == '<' && innerXml[i + 1] == '!' && innerXml[i + 2] == '-' && innerXml[i + 3] == '-') { // Found the start of a comment insideComment = true; i += 3; continue; } } if (!insideComment) { if (innerXml[i] == '<') { // Found a tag! return false; } } if (insideComment) { // XML comments end with exactly "-->" if (i < innerXml.Length - 2 && innerXml[i] == '-' && innerXml[i + 1] == '-' && innerXml[i + 2] == '>') { // Found the end of a comment insideComment = false; i += 2; continue; } } } // Didn't find any tags, except possibly comments return true; } // used to find the xmlns attribute private static readonly Regex xmlnsPattern = new Regex("xmlns=\"[^\"]*\"\\s*"); /// <summary> /// Removes the xmlns attribute from an XML string. /// </summary> /// <owner>SumedhK</owner> /// <param name="xml">XML string to process.</param> /// <returns>The modified XML string.</returns> internal static string RemoveXmlNamespace(string xml) { return xmlnsPattern.Replace(xml, String.Empty); } /// <summary> /// Escapes given string, that is replaces special characters with escape sequences that allow MSBuild hosts /// to treat MSBuild-interpreted characters literally (';' becomes "%3b" and so on). /// </summary> /// <param name="unescapedExpression">string to escape</param> /// <returns>escaped string</returns> public static string Escape(string unescapedExpression) { return EscapingUtilities.Escape(unescapedExpression); } /// <summary> /// Instantiates a new BuildEventFileInfo object using an XML node (presumably from the project /// file). The reason this isn't just another constructor on BuildEventFileInfo is because /// BuildEventFileInfo.cs gets compiled into multiple assemblies (Engine and Conversion, at least), /// and not all of those assemblies have the code for XmlUtilities. /// </summary> /// <param name="xmlNode"></param> /// <param name="defaultFile"></param> /// <returns></returns> /// <owner>RGoel</owner> internal static BuildEventFileInfo CreateBuildEventFileInfo(XmlNode xmlNode, string defaultFile) { ErrorUtilities.VerifyThrow(xmlNode != null, "Need Xml node."); // Get the file path out of the Xml node. int line = 0; int column = 0; string file = XmlUtilities.GetXmlNodeFile(xmlNode, String.Empty); if (file.Length == 0) { file = defaultFile; } else { // Compute the line number and column number of the XML node. XmlSearcher.GetLineColumnByNode(xmlNode, out line, out column); } return new BuildEventFileInfo(file, line, column); } /// <summary> /// Helper useful for lazy table creation /// </summary> internal static Hashtable CreateTableIfNecessary(Hashtable table) { if (table == null) { return new Hashtable(StringComparer.OrdinalIgnoreCase); } return table; } /// <summary> /// Helper useful for lazy table creation /// </summary> internal static Dictionary<string, V> CreateTableIfNecessary<V>(Dictionary<string, V> table) { if (table == null) { return new Dictionary<string, V>(StringComparer.OrdinalIgnoreCase); } return table; } } }
// This file is part of the Harvest Management library for LANDIS-II. using Landis.Utilities; using Landis.SpatialModeling; using System.Collections; using System.Collections.Generic; namespace Landis.Library.HarvestManagement { /// <summary> /// A site-selection method that harvests site-by-site until a target /// size is reached. /// </summary> public class PartialStandSpreading : StandSpreading, ISiteSelector, IEnumerable<ActiveSite> { private Stand initialStand; private double minTargetSize; private double maxTargetSize; private double areaSelected; private Queue<ActiveSite> harvestableSites; // Sites to harvest Queue<Stand> standsToHarvest; // Stands to harvest Queue<double>standsToHarvestRankings; // Stands to harvest rankings List<Stand> standsToReject; // Stands to mark as rejected private int minTimeSinceDamage; // From prescription //collect all 8 relative neighbor locations in array public static RelativeLocation[] all_neighbor_locations = new RelativeLocation[] { //define 8 neighboring locations new RelativeLocation(-1, 0), new RelativeLocation( 1, 0), new RelativeLocation( 0, -1), new RelativeLocation( 0, 1), new RelativeLocation(-1, -1), new RelativeLocation(-1, 1), new RelativeLocation(1, -1), new RelativeLocation(1, 1) }; //--------------------------------------------------------------------- /// <summary> /// Initializes a new instance. /// </summary> /// <param name="minTargetSize"> /// The min size (area) to harvest. Units: hectares. /// </param> /// <param name="maxTargetSize"> /// The max size (area) to harvest. Units: hectares /// </param> public PartialStandSpreading(double minTargetSize, double maxTargetSize) { this.minTargetSize = minTargetSize; this.maxTargetSize = maxTargetSize; } //--------------------------------------------------------------------- double ISiteSelector.AreaSelected { get { return areaSelected; } } //--------------------------------------------------------------------- IEnumerable<ActiveSite> ISiteSelector.SelectSites(Stand stand) { initialStand = stand; return this; } //--------------------------------------------------------------------- IEnumerator<ActiveSite> IEnumerable<ActiveSite>.GetEnumerator() { // harvestable sites are thos sites that will be harvested if // the minTargetSize is reached // // standsToHarvest are the stands from which harvesting will // be done if minTargetSize is reached. // // standsToHarvestRankings holds the rankings of the stands // we will be harvesting. // // standsToReject are those stands immediately that // are not harvestable and that will be marked // as rejected for the current prescription name harvestableSites = new Queue<ActiveSite>(); areaSelected = 0; standsToHarvest = new Queue<Stand>(); standsToHarvestRankings = new Queue<double>(); standsToReject = new List<Stand>(); string prescriptionName = initialStand.PrescriptionName; Prescription lastPrescription = initialStand.LastPrescription; minTimeSinceDamage = initialStand.MinTimeSinceDamage; this.HarvestedNeighbors.Clear(); // Attempt to do the harvest if (SpreadFromStand(initialStand)) { int eventId = EventId.MakeNewId(); // loop through all harvestable stands and update // appropriate items foreach (Stand standToHarvest in standsToHarvest) { standToHarvest.MarkAsHarvested(); standToHarvest.EventId = eventId; standToHarvest.PrescriptionName = prescriptionName; standToHarvest.LastPrescription = lastPrescription; standToHarvest.MinTimeSinceDamage = minTimeSinceDamage; standToHarvest.HarvestedRank = standsToHarvestRankings.Dequeue(); if(!(standToHarvest==initialStand)) this.HarvestedNeighbors.Add(standToHarvest); } // foreach(Stand standToHarvest in standsToHarvest) } else { // if this set of stands is not harvestable by this prescription // mark them all as such using the prescriptionName. foreach (Stand standToReject in standsToHarvest) { //Model.Core.UI.WriteLine("Rejecting stand {0} for prescription {1}",standToReject.MapCode, prescriptionName); standToReject.RejectPrescriptionName(prescriptionName); standToReject.HarvestedRank = standsToHarvestRankings.Dequeue(); } // foreach(Stand standToReject in standsToHarvest) } // if(SpreadFromStand(initialStand)) ... else // mark all rejected stands as rejected for this // prescription name foreach (Stand standToReject in standsToReject) { //Model.Core.UI.WriteLine("Rejecting stand {0} for prescription {1}",standToReject.MapCode, prescriptionName); standToReject.RejectPrescriptionName(prescriptionName); } // If what was found is enough to harvest, yield it if (harvestableSites.Count >= minTargetSize) { while (harvestableSites.Count > 0) { yield return harvestableSites.Dequeue(); } } } // IEnumerator<ActiveSite> IEnumerable<ActiveSite>.GetEnumerator() private static ActiveSite GetNeighboringSite(List<Stand> harvestedNeighbors, Stand neighborStand) { // get a shared-edge site from any one of the previously harvested neighboring stands // tjs - changed to allow a null return. Sometimes there are not adjacent sites ActiveSite returnSite; foreach (Site current_site in neighborStand) { //check if one of its neighbors is on the edge of the initialStand foreach (RelativeLocation relloc in all_neighbor_locations) { //if it's a valid site and is on the edge if (current_site.GetNeighbor(relloc) != null && current_site.GetNeighbor(relloc).IsActive) { foreach (Stand stand in harvestedNeighbors) { if (SiteVars.Stand[current_site.GetNeighbor(relloc)] == stand) { returnSite = (ActiveSite) current_site; return returnSite; } } } } } return new ActiveSite(); } //-------------------------------------------------------------- // For the starting stand do partial stand spreading until either // we run out of stands or we have our target area private bool SpreadFromStand(Stand startingStand) { List<Stand> standsConsidered = new List<Stand>(); // a list of every stand we have thought about considering // used to prevent considering a stand more than once List<Stand> standsToConsiderAll = new List<Stand>(); List<StandRanking> standsToConsiderRankings = new List<StandRanking>(); bool rtrnVal = false; Stand crntStand; double crntRank; ActiveSite startingSite;// = null; // If we have a valid starting stand, put it on the list to // consider if(startingStand != null && !startingStand.IsSetAside) { standsToConsiderRankings.Insert(0,GetRanking(startingStand)); standsToConsiderAll.Add(startingStand); } while (standsToConsiderRankings.Count > 0 && standsToConsiderRankings[0].Rank > 0 && areaSelected < maxTargetSize) { // Get the stand to work with for this loop iteration crntStand = standsToConsiderRankings[0].Stand; crntRank = standsToConsiderRankings[0].Rank; standsToConsiderRankings.RemoveAt(0); // If the stand is not set aside, Get the starting site if (!crntStand.IsSetAside) { // first stand starts at a random site, subsequent // stands start at an adjoining site if (standsConsidered.Count == 0) { startingSite = crntStand.GetRandomActiveSite; } else { startingSite = GetNeighboringSite(standsConsidered, crntStand); if (startingSite == false) { standsToReject.Add(crntStand); continue; } } } else { // if the stand is set aside, it doesn't get processed // and its neighbors don't go on the stand list standsToReject.Add(crntStand); continue; } // Enqueue the eligible sites and put the stand // on the appropriate queue(s) if (EnqueueEligibleSites(startingSite, crntStand)) { standsToHarvest.Enqueue(crntStand); standsToHarvestRankings.Enqueue(crntRank); } else { standsToReject.Add(crntStand); } standsConsidered.Add(crntStand); if (areaSelected < maxTargetSize) { // Get the neighbors and put them on the // standsToConsider queue foreach (Stand neighbor in crntStand.Neighbors) { if(!standsConsidered.Contains(neighbor) && !standsToConsiderAll.Contains(neighbor) && !neighbor.Harvested) { StandRanking neighborRanking = GetRanking(neighbor); standsToConsiderAll.Add(neighbor); if (neighborRanking.Rank <= 0) { continue; } int i; for (i = 0; i < standsToConsiderRankings.Count; i++) { if (standsToConsiderRankings[i].Rank < neighborRanking.Rank) break; } standsToConsiderRankings.Insert(i, neighborRanking); } } } } // If we found enough to meet our goal, return true, // otherwise return the default of false. if (areaSelected >= minTargetSize) rtrnVal = true; return rtrnVal; } //-------------------------------------------------------------- // For the current stand, enqueue all the eligible sites onto // the harvestableSites queue private bool EnqueueEligibleSites(ActiveSite startingSite, Stand crntStand) { Queue<ActiveSite> sitesConsidered = new Queue<ActiveSite>(); Queue<ActiveSite> sitesToConsider = new Queue<ActiveSite>(); bool rtrnVal = false; ActiveSite crntSite = startingSite; //The following case could happen if prevent establishment //generates empty stands. if (crntStand.GetActiveSites().Count <= 0) return false; if (crntSite != null) sitesToConsider.Enqueue(crntSite); while (sitesToConsider.Count > 0 && areaSelected < maxTargetSize) { // Get the site to work with for this loop iteration crntSite = sitesToConsider.Dequeue(); // Enqueue and increment area if sight is harvestable sitesConsidered.Enqueue(crntSite); if (SiteVars.TimeSinceLastDamage(crntSite) >= minTimeSinceDamage) { harvestableSites.Enqueue(crntSite); areaSelected += Model.Core.CellArea; rtrnVal = true; } // Put those neighbors on the sightsToConsider queue foreach (RelativeLocation loc in all_neighbor_locations) { // get a neighbor site Site tempSite = crntSite.GetNeighbor(loc); if(tempSite != null && tempSite.IsActive) { //get a neighbor site (if it's active and non-null) //if (crntSite.GetNeighbor(loc) != null && crntSite.GetNeighbor(loc).IsActive) //{ ActiveSite neighborSite = (ActiveSite) tempSite; // (ActiveSite)crntSite.GetNeighbor(loc); // check if in the same stand and management area // and if it has not been looked at if (SiteVars.Stand[neighborSite] == SiteVars.Stand[crntSite] && SiteVars.ManagementArea[neighborSite] == SiteVars.ManagementArea[crntSite] && !sitesConsidered.Contains(neighborSite) && !sitesToConsider.Contains(neighborSite)) { sitesToConsider.Enqueue(neighborSite); } } } } return rtrnVal; } //--------------------------------------------------------------------- IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<ActiveSite>)this).GetEnumerator(); } // IEnumerator IEnumerable.GetEnumerator() { } // public class PartialStandSpreading } // namespace Landis.Library.HarvestManagement
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; namespace System.Diagnostics { /// <devdoc> /// <para>Provides a thread-safe list of <see cref='System.Diagnostics.TraceListenerCollection'/>. A thread-safe list is synchronized.</para> /// </devdoc> public class TraceListenerCollection : IList { private List<TraceListener> _list; internal TraceListenerCollection() { _list = new List<TraceListener>(1); } /// <devdoc> /// <para>Gets or sets the <see cref='TraceListener'/> at /// the specified index.</para> /// </devdoc> public TraceListener this[int i] { get { return _list[i]; } set { InitializeListener(value); _list[i] = value; } } /// <devdoc> /// <para>Gets the first <see cref='System.Diagnostics.TraceListener'/> in the list with the specified name.</para> /// </devdoc> public TraceListener this[string name] { get { foreach (TraceListener listener in this) { if (listener.Name == name) return listener; } return null; } } /// <devdoc> /// <para> /// Gets the number of listeners in the list. /// </para> /// </devdoc> public int Count { get { return _list.Count; } } /// <devdoc> /// <para>Adds a <see cref='System.Diagnostics.TraceListener'/> to the list.</para> /// </devdoc> public int Add(TraceListener listener) { InitializeListener(listener); lock (TraceInternal.critSec) { return ((IList)_list).Add(listener); } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void AddRange(TraceListener[] value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } for (int i = 0; ((i) < (value.Length)); i = ((i) + (1))) { this.Add(value[i]); } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void AddRange(TraceListenerCollection value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } int currentCount = value.Count; for (int i = 0; i < currentCount; i = ((i) + (1))) { this.Add(value[i]); } } /// <devdoc> /// <para> /// Clears all the listeners from the /// list. /// </para> /// </devdoc> public void Clear() { _list.Clear(); } /// <devdoc> /// <para>Checks whether the list contains the specified /// listener.</para> /// </devdoc> public bool Contains(TraceListener listener) { return ((IList)this).Contains(listener); } /// <devdoc> /// <para>Copies a section of the current <see cref='System.Diagnostics.TraceListenerCollection'/> list to the specified array at the specified /// index.</para> /// </devdoc> public void CopyTo(TraceListener[] listeners, int index) { ((ICollection)this).CopyTo((Array)listeners, index); } /// <devdoc> /// <para> /// Gets an enumerator for this list. /// </para> /// </devdoc> public IEnumerator GetEnumerator() { return _list.GetEnumerator(); } internal void InitializeListener(TraceListener listener) { if (listener == null) throw new ArgumentNullException(nameof(listener)); listener.IndentSize = TraceInternal.IndentSize; listener.IndentLevel = TraceInternal.IndentLevel; } /// <devdoc> /// <para>Gets the index of the specified listener.</para> /// </devdoc> public int IndexOf(TraceListener listener) { return ((IList)this).IndexOf(listener); } /// <devdoc> /// <para>Inserts the listener at the specified index.</para> /// </devdoc> public void Insert(int index, TraceListener listener) { InitializeListener(listener); lock (TraceInternal.critSec) { _list.Insert(index, listener); } } /// <devdoc> /// <para> /// Removes the specified instance of the <see cref='System.Diagnostics.TraceListener'/> class from the list. /// </para> /// </devdoc> public void Remove(TraceListener listener) { ((IList)this).Remove(listener); } /// <devdoc> /// <para>Removes the first listener in the list that has the /// specified name.</para> /// </devdoc> public void Remove(string name) { TraceListener listener = this[name]; if (listener != null) ((IList)this).Remove(listener); } /// <devdoc> /// <para>Removes the <see cref='System.Diagnostics.TraceListener'/> at the specified index.</para> /// </devdoc> public void RemoveAt(int index) { lock (TraceInternal.critSec) { _list.RemoveAt(index); } } /// <internalonly/> object IList.this[int index] { get { return _list[index]; } set { TraceListener listener = value as TraceListener; if (listener == null) throw new ArgumentException(SR.MustAddListener, nameof(value)); InitializeListener(listener); _list[index] = listener; } } /// <internalonly/> bool IList.IsReadOnly { get { return false; } } /// <internalonly/> bool IList.IsFixedSize { get { return false; } } /// <internalonly/> int IList.Add(object value) { TraceListener listener = value as TraceListener; if (listener == null) throw new ArgumentException(SR.MustAddListener, nameof(value)); InitializeListener(listener); lock (TraceInternal.critSec) { return ((IList)_list).Add(value); } } /// <internalonly/> bool IList.Contains(object value) { return _list.Contains((TraceListener)value); } /// <internalonly/> int IList.IndexOf(object value) { return _list.IndexOf((TraceListener)value); } /// <internalonly/> void IList.Insert(int index, object value) { TraceListener listener = value as TraceListener; if (listener == null) throw new ArgumentException(SR.MustAddListener, nameof(value)); InitializeListener(listener); lock (TraceInternal.critSec) { _list.Insert(index, (TraceListener)value); } } /// <internalonly/> void IList.Remove(object value) { lock (TraceInternal.critSec) { _list.Remove((TraceListener)value); } } /// <internalonly/> object ICollection.SyncRoot { get { return this; } } /// <internalonly/> bool ICollection.IsSynchronized { get { return true; } } /// <internalonly/> void ICollection.CopyTo(Array array, int index) { ((ICollection)_list).CopyTo(array, index); } } }
// 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.Threading; using Xunit; public class TimerFiringTests { [Fact] public void Timer_Fires_After_DueTime_Ellapses() { AutoResetEvent are = new AutoResetEvent(false); using (var t = new Timer(new TimerCallback((object s) => { are.Set(); }), null, TimeSpan.FromMilliseconds(250), TimeSpan.FromMilliseconds(Timeout.Infinite) /* not relevant */)) { Assert.True(are.WaitOne(TimeSpan.FromMilliseconds(750))); } } [Fact] public void Timer_Fires_AndPassesStateThroughCallback() { object state = new object(); using (var t = new Timer(new TimerCallback((object s) => { Assert.Same(s, state); }), state, TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(Timeout.Infinite) /* not relevant */)) { } } [Fact] public void Timer_Fires_AndPassesNullStateThroughCallback() { using (var t = new Timer(new TimerCallback((object s) => { Assert.Null(s); }), null, TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(Timeout.Infinite) /* not relevant */)) { } } [Fact] public void Timer_Fires_After_DueTime_AndOn_Period() { int count = 0; AutoResetEvent are = new AutoResetEvent(false); using (var t = new Timer(new TimerCallback((object s) => { count++; if (count >= 2) { are.Set(); } }), null, TimeSpan.FromMilliseconds(250), TimeSpan.FromMilliseconds(50))) { Assert.True(are.WaitOne(TimeSpan.FromMilliseconds(2000))); } } [Fact] public void Timer_FiresOnlyOnce_OnDueTime_With_InfinitePeriod() { int count = 0; AutoResetEvent are = new AutoResetEvent(false); using (var t = new Timer(new TimerCallback((object s) => { count++; if (count >= 2) { are.Set(); } }), null, TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(Timeout.Infinite) /* not relevant */)) { Assert.False(are.WaitOne(TimeSpan.FromSeconds(1))); } } [Fact] public void MultipleTimers_ShouldFire_InCorrectOrder() { object t1State = new object(); object t2State = new object(); Timer t1 = null; Timer t2 = null; int count = 0; AutoResetEvent are = new AutoResetEvent(false); TimerCallback tc = new TimerCallback((object o) => { if (count == 0) { Assert.Same(t2State, o); count++; } else { Assert.Same(t1State, o); are.Set(); } }); using (t1 = new Timer(tc, t1State, TimeSpan.FromSeconds(1), TimeSpan.FromMilliseconds(-1))) using (t2 = new Timer(tc, t2State, TimeSpan.FromMilliseconds(0), TimeSpan.FromMilliseconds(-1))) { // Wait for both events to fire Assert.True(are.WaitOne(TimeSpan.FromMilliseconds(1500 /*1.5 seconds*/))); } } [Fact] public void Timer_CanDisposeSelfInCallback() { // There's nothing to validate besides that we don't throw an exception, so rely on xunit // to catch any exception that would be thrown and signal a test failure Timer t = null; AutoResetEvent are = new AutoResetEvent(false); TimerCallback tc = new TimerCallback((object o) => { t.Dispose(); are.Set(); }); t = new Timer(tc, null, 1, -1); Assert.True(are.WaitOne(50)); } [Fact] public void Timer_CanBeDisposedMultipleTimes() { // There's nothing to validate besides that we don't throw an exception, so rely on xunit // to catch any exception that would be thrown and signal a test failure TimerCallback tc = new TimerCallback((object o) => { }); var t = new Timer(tc, null, 100, -1); for (int i = 0; i < 10; i++) t.Dispose(); } [Fact] public void NonRepeatingTimer_ThatHasAlreadyFired_CanChangeAndFireAgain() { AutoResetEvent are = new AutoResetEvent(false); TimerCallback tc = new TimerCallback((object o) => are.Set()); using (var t = new Timer(tc, null, 1, Timeout.Infinite)) { Assert.True(are.WaitOne(50), "Should have received first timer event"); Assert.False(are.WaitOne(20), "Should not have received a second timer event"); t.Change(10, Timeout.Infinite); Assert.True(are.WaitOne(50), "Should have received a second timer event after changing it"); } } [Fact] public void Running_Timer_CanBeFinalizedAndStopsFiring() { AutoResetEvent are = new AutoResetEvent(false); TimerCallback tc = new TimerCallback((object o) => are.Set()); var t = new Timer(tc, null, 100, 500); Assert.True(are.WaitOne(250), "Failed to get first timer fire"); t = null; // Remove our refence so the timer can be GC'd GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Assert.False(are.WaitOne(750), "Should not have received a timer fire after it was collected"); } [Fact] public void MultpleTimers_PeriodicTimerIsntBlockedByABlockedTimer() { AutoResetEvent are1 = new AutoResetEvent(false); AutoResetEvent are2 = new AutoResetEvent(false); TimerCallback tc = new TimerCallback((object o) => { using (var t1 = new Timer((object obj) => are1.Set(), null, 1, -1)) { Assert.True(are1.WaitOne(250), "Should have received a second callback while blocked"); are2.Set(); } }); using (var t1 = new Timer(tc, null, 1, -1)) { Assert.True(are2.WaitOne(500), "Blocking callback prevented a second timer from firing"); } } [Fact] public void ManyTimers_EachTimerDoesFire() { int maxTimers = 10000; CountdownEvent ce = new CountdownEvent(maxTimers); Timer[] timers = System.Linq.Enumerable.Range(0, maxTimers).Select(_ => new Timer(s => ce.Signal(), null, 100 /* enough time to wait on the are */, -1)).ToArray(); try { Assert.True(ce.Wait(500), String.Format("Not all timers fired, {0} left of {1}", ce.CurrentCount, maxTimers)); } finally { foreach (Timer t in timers) t.Dispose(); } } }
// 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.Diagnostics; using System.Linq; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Input; using osu.Framework.Input.Events; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Graphics; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using osu.Game.Rulesets.Osu.Edit.Blueprints.HitCircles.Components; using osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders.Components; using osu.Game.Screens.Edit; using osuTK; using osuTK.Input; namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders { public class SliderPlacementBlueprint : PlacementBlueprint { public new Objects.Slider HitObject => (Objects.Slider)base.HitObject; private SliderBodyPiece bodyPiece; private HitCirclePiece headCirclePiece; private HitCirclePiece tailCirclePiece; private PathControlPointVisualiser controlPointVisualiser; private InputManager inputManager; private SliderPlacementState state; private PathControlPoint segmentStart; private PathControlPoint cursor; private int currentSegmentLength; [Resolved(CanBeNull = true)] private HitObjectComposer composer { get; set; } public SliderPlacementBlueprint() : base(new Objects.Slider()) { RelativeSizeAxes = Axes.Both; HitObject.Path.ControlPoints.Add(segmentStart = new PathControlPoint(Vector2.Zero, PathType.Linear)); currentSegmentLength = 1; } [BackgroundDependencyLoader] private void load(OsuColour colours) { InternalChildren = new Drawable[] { bodyPiece = new SliderBodyPiece(), headCirclePiece = new HitCirclePiece(), tailCirclePiece = new HitCirclePiece(), controlPointVisualiser = new PathControlPointVisualiser(HitObject, false) }; setState(SliderPlacementState.Initial); } protected override void LoadComplete() { base.LoadComplete(); inputManager = GetContainingInputManager(); } [Resolved] private EditorBeatmap editorBeatmap { get; set; } public override void UpdateTimeAndPosition(SnapResult result) { base.UpdateTimeAndPosition(result); switch (state) { case SliderPlacementState.Initial: BeginPlacement(); var nearestDifficultyPoint = editorBeatmap.HitObjects.LastOrDefault(h => h.GetEndTime() < HitObject.StartTime)?.DifficultyControlPoint?.DeepClone() as DifficultyControlPoint; HitObject.DifficultyControlPoint = nearestDifficultyPoint ?? new DifficultyControlPoint(); HitObject.Position = ToLocalSpace(result.ScreenSpacePosition); break; case SliderPlacementState.Body: updateCursor(); break; } } protected override bool OnMouseDown(MouseDownEvent e) { if (e.Button != MouseButton.Left) return base.OnMouseDown(e); switch (state) { case SliderPlacementState.Initial: beginCurve(); break; case SliderPlacementState.Body: if (canPlaceNewControlPoint(out var lastPoint)) { // Place a new point by detatching the current cursor. updateCursor(); cursor = null; } else { // Transform the last point into a new segment. Debug.Assert(lastPoint != null); segmentStart = lastPoint; segmentStart.Type = PathType.Linear; currentSegmentLength = 1; } break; } return true; } protected override void OnMouseUp(MouseUpEvent e) { if (state == SliderPlacementState.Body && e.Button == MouseButton.Right) endCurve(); base.OnMouseUp(e); } private void beginCurve() { BeginPlacement(commitStart: true); setState(SliderPlacementState.Body); } private void endCurve() { updateSlider(); EndPlacement(HitObject.Path.HasValidLength); } protected override void Update() { base.Update(); updateSlider(); // Maintain the path type in case it got defaulted to bezier at some point during the drag. updatePathType(); } private void updatePathType() { switch (currentSegmentLength) { case 1: case 2: segmentStart.Type = PathType.Linear; break; case 3: segmentStart.Type = PathType.PerfectCurve; break; default: segmentStart.Type = PathType.Bezier; break; } } private void updateCursor() { if (canPlaceNewControlPoint(out _)) { // The cursor does not overlap a previous control point, so it can be added if not already existing. if (cursor == null) { HitObject.Path.ControlPoints.Add(cursor = new PathControlPoint { Position = Vector2.Zero }); // The path type should be adjusted in the progression of updatePathType() (Linear -> PC -> Bezier). currentSegmentLength++; updatePathType(); } // Update the cursor position. cursor.Position = ToLocalSpace(inputManager.CurrentState.Mouse.Position) - HitObject.Position; } else if (cursor != null) { // The cursor overlaps a previous control point, so it's removed. HitObject.Path.ControlPoints.Remove(cursor); cursor = null; // The path type should be adjusted in the reverse progression of updatePathType() (Bezier -> PC -> Linear). currentSegmentLength--; updatePathType(); } } /// <summary> /// Whether a new control point can be placed at the current mouse position. /// </summary> /// <param name="lastPoint">The last-placed control point. May be null, but is not null if <c>false</c> is returned.</param> /// <returns>Whether a new control point can be placed at the current position.</returns> private bool canPlaceNewControlPoint([CanBeNull] out PathControlPoint lastPoint) { // We cannot rely on the ordering of drawable pieces, so find the respective drawable piece by searching for the last non-cursor control point. var last = HitObject.Path.ControlPoints.LastOrDefault(p => p != cursor); var lastPiece = controlPointVisualiser.Pieces.Single(p => p.ControlPoint == last); lastPoint = last; return lastPiece.IsHovered != true; } private void updateSlider() { HitObject.Path.ExpectedDistance.Value = composer?.GetSnappedDistanceFromDistance(HitObject, (float)HitObject.Path.CalculatedDistance) ?? (float)HitObject.Path.CalculatedDistance; bodyPiece.UpdateFrom(HitObject); headCirclePiece.UpdateFrom(HitObject.HeadCircle); tailCirclePiece.UpdateFrom(HitObject.TailCircle); } private void setState(SliderPlacementState newState) { state = newState; } private enum SliderPlacementState { Initial, Body, } } }
namespace Nancy.Tests.Unit.Security { using System; using System.Collections.Generic; using System.Linq; using FakeItEasy; using Nancy.Responses; using Nancy.Security; using Nancy.Tests.Fakes; using Xunit; public class UserIdentityExtensionsFixture { [Fact] public void Should_return_false_for_authentication_if_the_user_is_null() { // Given IUserIdentity user = null; // When var result = user.IsAuthenticated(); // Then result.ShouldBeFalse(); } [Fact] public void Should_return_false_for_authentication_if_the_username_is_null() { // Given IUserIdentity user = GetFakeUser(null); // When var result = user.IsAuthenticated(); // Then result.ShouldBeFalse(); } [Fact] public void Should_return_false_for_authentication_if_the_username_is_empty() { // Given IUserIdentity user = GetFakeUser(""); // When var result = user.IsAuthenticated(); // Then result.ShouldBeFalse(); } [Fact] public void Should_return_false_for_authentication_if_the_username_is_whitespace() { // Given IUserIdentity user = GetFakeUser(" \r\n "); // When var result = user.IsAuthenticated(); // Then result.ShouldBeFalse(); } [Fact] public void Should_return_true_for_authentication_if_username_is_set() { // Given IUserIdentity user = GetFakeUser("Fake"); // When var result = user.IsAuthenticated(); // Then result.ShouldBeTrue(); } [Fact] public void Should_return_false_for_required_claim_if_the_user_is_null() { // Given IUserIdentity user = null; var requiredClaim = "not-present-claim"; // When var result = user.HasClaim(requiredClaim); // Then result.ShouldBeFalse(); } [Fact] public void Should_return_false_for_required_claim_if_the_claims_are_null() { // Given IUserIdentity user = GetFakeUser("Fake"); var requiredClaim = "not-present-claim"; // When var result = user.HasClaim(requiredClaim); // Then result.ShouldBeFalse(); } [Fact] public void Should_return_false_for_required_claim_if_the_user_does_not_have_claim() { // Given IUserIdentity user = GetFakeUser("Fake", new [] { "present-claim" }) ; var requiredClaim = "not-present-claim"; // When var result = user.HasClaim(requiredClaim); // Then result.ShouldBeFalse(); } [Fact] public void Should_return_true_for_required_claim_if_the_user_does_have_claim() { // Given IUserIdentity user = GetFakeUser("Fake", new [] { "present-claim" }) ; var requiredClaim = "present-claim"; // When var result = user.HasClaim(requiredClaim); // Then result.ShouldBeTrue(); } [Fact] public void Should_return_false_for_required_claims_if_the_user_is_null() { // Given IUserIdentity user = null; var requiredClaims = new[] { "not-present-claim1", "not-present-claim2" }; // When var result = user.HasClaims(requiredClaims); // Then result.ShouldBeFalse(); } [Fact] public void Should_return_false_for_required_claims_if_the_claims_are_null() { // Given IUserIdentity user = GetFakeUser("Fake"); var requiredClaims = new[] { "not-present-claim1", "not-present-claim2" }; // When var result = user.HasClaims(requiredClaims); // Then result.ShouldBeFalse(); } [Fact] public void Should_return_false_for_required_claims_if_the_user_does_not_have_all_claims() { // Given IUserIdentity user = GetFakeUser("Fake", new[] { "present-claim1", "present-claim2", "present-claim3" }); var requiredClaims = new[] { "present-claim1", "not-present-claim1" }; // When var result = user.HasClaims(requiredClaims); // Then result.ShouldBeFalse(); } [Fact] public void Should_return_true_for_required_claims_if_the_user_does_have_all_claims() { // Given IUserIdentity user = GetFakeUser("Fake", new[] { "present-claim1", "present-claim2", "present-claim3" }); var requiredClaims = new[] { "present-claim1", "present-claim2" }; // When var result = user.HasClaims(requiredClaims); // Then result.ShouldBeTrue(); } [Fact] public void Should_return_false_for_any_required_claim_if_the_user_is_null() { // Given IUserIdentity user = null; var requiredClaims = new[] { "not-present-claim1", "not-present-claim2" }; // When var result = user.HasAnyClaim(requiredClaims); // Then result.ShouldBeFalse(); } [Fact] public void Should_return_false_for_any_required_claim_if_the_claims_are_null() { // Given IUserIdentity user = GetFakeUser("Fake"); var requiredClaims = new[] { "not-present-claim1", "not-present-claim2" }; // When var result = user.HasAnyClaim(requiredClaims); // Then result.ShouldBeFalse(); } [Fact] public void Should_return_false_for_any_required_claim_if_the_user_does_not_have_any_claim() { // Given IUserIdentity user = GetFakeUser("Fake", new[] { "present-claim1", "present-claim2", "present-claim3" }); var requiredClaims = new[] { "not-present-claim1", "not-present-claim2" }; // When var result = user.HasAnyClaim(requiredClaims); // Then result.ShouldBeFalse(); } [Fact] public void Should_return_true_for_any_required_claim_if_the_user_does_have_any_of_claim() { // Given IUserIdentity user = GetFakeUser("Fake", new[] { "present-claim1", "present-claim2", "present-claim3" }); var requiredClaims = new[] { "present-claim1", "not-present-claim1" }; // When var result = user.HasAnyClaim(requiredClaims); // Then result.ShouldBeTrue(); } [Fact] public void Should_return_false_for_valid_claim_if_the_user_is_null() { // Given IUserIdentity user = null; Func<IEnumerable<string>, bool> isValid = claims => true; // When var result = user.HasValidClaims(isValid); // Then result.ShouldBeFalse(); } [Fact] public void Should_return_false_for_valid_claim_if_claims_are_null() { // Given IUserIdentity user = GetFakeUser("Fake"); Func<IEnumerable<string>, bool> isValid = claims => true; // When var result = user.HasValidClaims(isValid); // Then result.ShouldBeFalse(); } [Fact] public void Should_return_false_for_valid_claim_if_the_validation_fails() { // Given IUserIdentity user = GetFakeUser("Fake", new[] { "present-claim1", "present-claim2", "present-claim3" }); Func<IEnumerable<string>, bool> isValid = claims => false; // When var result = user.HasValidClaims(isValid); // Then result.ShouldBeFalse(); } [Fact] public void Should_return_true_for_valid_claim_if_the_validation_succeeds() { // Given IUserIdentity user = GetFakeUser("Fake", new[] { "present-claim1", "present-claim2", "present-claim3" }); Func<IEnumerable<string>, bool> isValid = claims => true; // When var result = user.HasValidClaims(isValid); // Then result.ShouldBeTrue(); } [Fact] public void Should_call_validation_with_users_claims() { // Given IEnumerable<string> userClaims = new string[0]; IUserIdentity user = GetFakeUser("Fake", userClaims); IEnumerable<string> validatedClaims = null; Func<IEnumerable<string>, bool> isValid = claims => { // store passed claims for testing assertion validatedClaims = claims; return true; }; // When user.HasValidClaims(isValid); // Then validatedClaims.ShouldBeSameAs(userClaims); } private static IUserIdentity GetFakeUser(string userName, IEnumerable<string> claims = null) { var ret = new FakeUserIdentity(); ret.UserName = userName; ret.Claims = claims; return ret; } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace _0365_CSOM_DemoWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
#if !(UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2) #define SupportCustomYieldInstruction #endif using System; using System.Collections; using System.Collections.Generic; using System.Runtime.ExceptionServices; using System.Reflection; using System.Threading; using UniRx.InternalUtil; using UnityEngine; namespace UniRx { public sealed class MainThreadDispatcher : MonoBehaviour { public enum CullingMode { /// <summary> /// Won't remove any MainThreadDispatchers. /// </summary> Disabled, /// <summary> /// Checks if there is an existing MainThreadDispatcher on Awake(). If so, the new dispatcher removes itself. /// </summary> Self, /// <summary> /// Search for excess MainThreadDispatchers and removes them all on Awake(). /// </summary> All } public static CullingMode cullingMode = CullingMode.Self; #if UNITY_EDITOR // In UnityEditor's EditorMode can't instantiate and work MonoBehaviour.Update. // EditorThreadDispatcher use EditorApplication.update instead of MonoBehaviour.Update. class EditorThreadDispatcher { static object gate = new object(); static EditorThreadDispatcher instance; public static EditorThreadDispatcher Instance { get { // Activate EditorThreadDispatcher is dangerous, completely Lazy. lock (gate) { if (instance == null) { instance = new EditorThreadDispatcher(); } return instance; } } } ThreadSafeQueueWorker editorQueueWorker = new ThreadSafeQueueWorker(); EditorThreadDispatcher() { UnityEditor.EditorApplication.update += Update; } public void Enqueue(Action<object> action, object state) { editorQueueWorker.Enqueue(action, state); } public void UnsafeInvoke(Action action) { try { action(); } catch (Exception ex) { Debug.LogException(ex); } } public void UnsafeInvoke<T>(Action<T> action, T state) { try { action(state); } catch (Exception ex) { Debug.LogException(ex); } } public void PseudoStartCoroutine(IEnumerator routine) { editorQueueWorker.Enqueue(_ => ConsumeEnumerator(routine), null); } void Update() { editorQueueWorker.ExecuteAll(x => Debug.LogException(x)); } void ConsumeEnumerator(IEnumerator routine) { if (routine.MoveNext()) { var current = routine.Current; if (current == null) { goto ENQUEUE; } var type = current.GetType(); if (type == typeof(WWW)) { var www = (WWW)current; editorQueueWorker.Enqueue(_ => ConsumeEnumerator(UnwrapWaitWWW(www, routine)), null); return; } else if (type == typeof(AsyncOperation)) { var asyncOperation = (AsyncOperation)current; editorQueueWorker.Enqueue(_ => ConsumeEnumerator(UnwrapWaitAsyncOperation(asyncOperation, routine)), null); return; } else if (type == typeof(WaitForSeconds)) { var waitForSeconds = (WaitForSeconds)current; var accessor = typeof(WaitForSeconds).GetField("m_Seconds", BindingFlags.Instance | BindingFlags.GetField | BindingFlags.NonPublic); var second = (float)accessor.GetValue(waitForSeconds); editorQueueWorker.Enqueue(_ => ConsumeEnumerator(UnwrapWaitForSeconds(second, routine)), null); return; } else if (type == typeof(Coroutine)) { Debug.Log("Can't wait coroutine on UnityEditor"); goto ENQUEUE; } #if SupportCustomYieldInstruction else if (current is IEnumerator) { var enumerator = (IEnumerator)current; editorQueueWorker.Enqueue(_ => ConsumeEnumerator(UnwrapEnumerator(enumerator, routine)), null); return; } #endif ENQUEUE: editorQueueWorker.Enqueue(_ => ConsumeEnumerator(routine), null); // next update } } IEnumerator UnwrapWaitWWW(WWW www, IEnumerator continuation) { while (!www.isDone) { yield return null; } ConsumeEnumerator(continuation); } IEnumerator UnwrapWaitAsyncOperation(AsyncOperation asyncOperation, IEnumerator continuation) { while (!asyncOperation.isDone) { yield return null; } ConsumeEnumerator(continuation); } IEnumerator UnwrapWaitForSeconds(float second, IEnumerator continuation) { var startTime = DateTimeOffset.UtcNow; while (true) { yield return null; var elapsed = (DateTimeOffset.UtcNow - startTime).TotalSeconds; if (elapsed >= second) { break; } }; ConsumeEnumerator(continuation); } IEnumerator UnwrapEnumerator(IEnumerator enumerator, IEnumerator continuation) { while (enumerator.MoveNext()) { yield return null; } ConsumeEnumerator(continuation); } } #endif /// <summary>Dispatch Asyncrhonous action.</summary> public static void Post(Action<object> action, object state) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.Enqueue(action, state); return; } #endif var dispatcher = Instance; if (!isQuitting && !object.ReferenceEquals(dispatcher, null)) { dispatcher.queueWorker.Enqueue(action, state); } } /// <summary>Dispatch Synchronous action if possible.</summary> public static void Send(Action<object> action, object state) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.Enqueue(action, state); return; } #endif if (mainThreadToken != null) { try { action(state); } catch (Exception ex) { var dispatcher = MainThreadDispatcher.Instance; if (dispatcher != null) { dispatcher.unhandledExceptionCallback(ex); } } } else { Post(action, state); } } /// <summary>Run Synchronous action.</summary> public static void UnsafeSend(Action action) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.UnsafeInvoke(action); return; } #endif try { action(); } catch (Exception ex) { var dispatcher = MainThreadDispatcher.Instance; if (dispatcher != null) { dispatcher.unhandledExceptionCallback(ex); } } } /// <summary>Run Synchronous action.</summary> public static void UnsafeSend<T>(Action<T> action, T state) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.UnsafeInvoke(action, state); return; } #endif try { action(state); } catch (Exception ex) { var dispatcher = MainThreadDispatcher.Instance; if (dispatcher != null) { dispatcher.unhandledExceptionCallback(ex); } } } /// <summary>ThreadSafe StartCoroutine.</summary> public static void SendStartCoroutine(IEnumerator routine) { if (mainThreadToken != null) { StartCoroutine(routine); } else { #if UNITY_EDITOR // call from other thread if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; } #endif var dispatcher = Instance; if (!isQuitting && !object.ReferenceEquals(dispatcher, null)) { dispatcher.queueWorker.Enqueue(_ => { var dispacher2 = Instance; if (dispacher2 != null) { (dispacher2 as MonoBehaviour).StartCoroutine(routine); } }, null); } } } public static void StartUpdateMicroCoroutine(IEnumerator routine) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; } #endif var dispatcher = Instance; if (dispatcher != null) { dispatcher.updateMicroCoroutine.AddCoroutine(routine); } } public static void StartFixedUpdateMicroCoroutine(IEnumerator routine) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; } #endif var dispatcher = Instance; if (dispatcher != null) { dispatcher.fixedUpdateMicroCoroutine.AddCoroutine(routine); } } public static void StartEndOfFrameMicroCoroutine(IEnumerator routine) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; } #endif var dispatcher = Instance; if (dispatcher != null) { dispatcher.endOfFrameMicroCoroutine.AddCoroutine(routine); } } new public static Coroutine StartCoroutine(IEnumerator routine) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return null; } #endif var dispatcher = Instance; if (dispatcher != null) { return (dispatcher as MonoBehaviour).StartCoroutine(routine); } else { return null; } } public static void RegisterUnhandledExceptionCallback(Action<Exception> exceptionCallback) { if (exceptionCallback == null) { // do nothing Instance.unhandledExceptionCallback = Stubs<Exception>.Ignore; } else { Instance.unhandledExceptionCallback = exceptionCallback; } } ThreadSafeQueueWorker queueWorker = new ThreadSafeQueueWorker(); Action<Exception> unhandledExceptionCallback = ex => Debug.LogException(ex); // default MicroCoroutine updateMicroCoroutine = null; MicroCoroutine fixedUpdateMicroCoroutine = null; MicroCoroutine endOfFrameMicroCoroutine = null; static MainThreadDispatcher instance; static bool initialized; static bool isQuitting = false; public static string InstanceName { get { if (instance == null) { throw new NullReferenceException("MainThreadDispatcher is not initialized."); } return instance.name; } } public static bool IsInitialized { get { return initialized && instance != null; } } [ThreadStatic] static object mainThreadToken; static MainThreadDispatcher Instance { get { Initialize(); return instance; } } public static void Initialize() { if (!initialized) { #if UNITY_EDITOR // Don't try to add a GameObject when the scene is not playing. Only valid in the Editor, EditorView. if (!ScenePlaybackDetector.IsPlaying) return; #endif MainThreadDispatcher dispatcher = null; try { dispatcher = GameObject.FindObjectOfType<MainThreadDispatcher>(); } catch { // Throw exception when calling from a worker thread. var ex = new Exception("UniRx requires a MainThreadDispatcher component created on the main thread. Make sure it is added to the scene before calling UniRx from a worker thread."); UnityEngine.Debug.LogException(ex); ExceptionDispatchInfo.Capture(ex).Throw(); } if (isQuitting) { // don't create new instance after quitting // avoid "Some objects were not cleaned up when closing the scene find target" error. return; } if (dispatcher == null) { // awake call immediately from UnityEngine new GameObject("MainThreadDispatcher").AddComponent<MainThreadDispatcher>(); } else { dispatcher.Awake(); // force awake } } } public static bool IsInMainThread { get { return (mainThreadToken != null); } } void Awake() { if (instance == null) { instance = this; mainThreadToken = new object(); initialized = true; #if (ENABLE_MONO_BLEEDING_EDGE_EDITOR || ENABLE_MONO_BLEEDING_EDGE_STANDALONE) if (UniRxSynchronizationContext.AutoInstall) { SynchronizationContext.SetSynchronizationContext(new UniRxSynchronizationContext()); } #endif updateMicroCoroutine = new MicroCoroutine(ex => unhandledExceptionCallback(ex)); fixedUpdateMicroCoroutine = new MicroCoroutine(ex => unhandledExceptionCallback(ex)); endOfFrameMicroCoroutine = new MicroCoroutine(ex => unhandledExceptionCallback(ex)); StartCoroutine(RunUpdateMicroCoroutine()); StartCoroutine(RunFixedUpdateMicroCoroutine()); StartCoroutine(RunEndOfFrameMicroCoroutine()); DontDestroyOnLoad(gameObject); } else { if (this != instance) { if (cullingMode == CullingMode.Self) { // Try to destroy this dispatcher if there's already one in the scene. Debug.LogWarning("There is already a MainThreadDispatcher in the scene. Removing myself..."); DestroyDispatcher(this); } else if (cullingMode == CullingMode.All) { Debug.LogWarning("There is already a MainThreadDispatcher in the scene. Cleaning up all excess dispatchers..."); CullAllExcessDispatchers(); } else { Debug.LogWarning("There is already a MainThreadDispatcher in the scene."); } } } } IEnumerator RunUpdateMicroCoroutine() { while (true) { yield return null; updateMicroCoroutine.Run(); } } IEnumerator RunFixedUpdateMicroCoroutine() { while (true) { yield return YieldInstructionCache.WaitForFixedUpdate; fixedUpdateMicroCoroutine.Run(); } } IEnumerator RunEndOfFrameMicroCoroutine() { while (true) { yield return YieldInstructionCache.WaitForEndOfFrame; endOfFrameMicroCoroutine.Run(); } } static void DestroyDispatcher(MainThreadDispatcher aDispatcher) { if (aDispatcher != instance) { // Try to remove game object if it's empty var components = aDispatcher.gameObject.GetComponents<Component>(); if (aDispatcher.gameObject.transform.childCount == 0 && components.Length == 2) { if (components[0] is Transform && components[1] is MainThreadDispatcher) { Destroy(aDispatcher.gameObject); } } else { // Remove component MonoBehaviour.Destroy(aDispatcher); } } } public static void CullAllExcessDispatchers() { var dispatchers = GameObject.FindObjectsOfType<MainThreadDispatcher>(); for (int i = 0; i < dispatchers.Length; i++) { DestroyDispatcher(dispatchers[i]); } } void OnDestroy() { if (instance == this) { instance = GameObject.FindObjectOfType<MainThreadDispatcher>(); initialized = instance != null; /* // Although `this` still refers to a gameObject, it won't be found. var foundDispatcher = GameObject.FindObjectOfType<MainThreadDispatcher>(); if (foundDispatcher != null) { // select another game object Debug.Log("new instance: " + foundDispatcher.name); instance = foundDispatcher; initialized = true; } */ } } void Update() { if (update != null) { try { update.OnNext(Unit.Default); } catch (Exception ex) { unhandledExceptionCallback(ex); } } queueWorker.ExecuteAll(unhandledExceptionCallback); } // for Lifecycle Management Subject<Unit> update; public static IObservable<Unit> UpdateAsObservable() { return Instance.update ?? (Instance.update = new Subject<Unit>()); } Subject<Unit> lateUpdate; void LateUpdate() { if (lateUpdate != null) lateUpdate.OnNext(Unit.Default); } public static IObservable<Unit> LateUpdateAsObservable() { return Instance.lateUpdate ?? (Instance.lateUpdate = new Subject<Unit>()); } Subject<bool> onApplicationFocus; void OnApplicationFocus(bool focus) { if (onApplicationFocus != null) onApplicationFocus.OnNext(focus); } public static IObservable<bool> OnApplicationFocusAsObservable() { return Instance.onApplicationFocus ?? (Instance.onApplicationFocus = new Subject<bool>()); } Subject<bool> onApplicationPause; void OnApplicationPause(bool pause) { if (onApplicationPause != null) onApplicationPause.OnNext(pause); } public static IObservable<bool> OnApplicationPauseAsObservable() { return Instance.onApplicationPause ?? (Instance.onApplicationPause = new Subject<bool>()); } Subject<Unit> onApplicationQuit; void OnApplicationQuit() { isQuitting = true; if (onApplicationQuit != null) onApplicationQuit.OnNext(Unit.Default); } public static IObservable<Unit> OnApplicationQuitAsObservable() { return Instance.onApplicationQuit ?? (Instance.onApplicationQuit = new Subject<Unit>()); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Sep.Git.Tfs.Commands; using Sep.Git.Tfs.Core; using Sep.Git.Tfs.Core.TfsInterop; using Sep.Git.Tfs.Util; using StructureMap; namespace Sep.Git.Tfs.VsFake { public class MockBranchObject : IBranchObject { public string Path { get; set; } public string ParentPath { get; set; } public bool IsRoot { get; set; } } public class TfsHelper : ITfsHelper { #region misc/null IContainer _container; TextWriter _stdout; Script _script; FakeVersionControlServer _versionControlServer; public TfsHelper(IContainer container, TextWriter stdout, Script script) { _container = container; _stdout = stdout; _script = script; _versionControlServer = new FakeVersionControlServer(_script); } public string TfsClientLibraryVersion { get { return "(FAKE)"; } } public string Url { get; set; } public string Username { get; set; } public string Password { get; set; } public void EnsureAuthenticated() {} public void SetPathResolver() {} public bool CanShowCheckinDialog { get { return false; } } public long ShowCheckinDialog(IWorkspace workspace, IPendingChange[] pendingChanges, IEnumerable<IWorkItemCheckedInfo> checkedInfos, string checkinComment) { throw new NotImplementedException(); } public IIdentity GetIdentity(string username) { return new NullIdentity(); } #endregion #region read changesets public ITfsChangeset GetLatestChangeset(IGitTfsRemote remote) { return _script.Changesets.LastOrDefault().Try(x => BuildTfsChangeset(x, remote)); } public int GetLatestChangesetId(IGitTfsRemote remote) { return _script.Changesets.LastOrDefault().Id; } public IEnumerable<ITfsChangeset> GetChangesets(string path, long startVersion, IGitTfsRemote remote, long lastVersion = -1, bool byLots = false) { if (!_script.Changesets.Any(c => c.IsBranchChangeset) && _script.Changesets.Any(c => c.IsMergeChangeset)) return _script.Changesets.Where(x => x.Id >= startVersion).Select(x => BuildTfsChangeset(x, remote)); var branchPath = path + "/"; return _script.Changesets .Where(x => x.Id >= startVersion && x.Changes.Any(c => c.RepositoryPath.IndexOf(branchPath, StringComparison.CurrentCultureIgnoreCase) == 0 || branchPath.IndexOf(c.RepositoryPath, StringComparison.CurrentCultureIgnoreCase) == 0)) .Select(x => BuildTfsChangeset(x, remote)); } public int FindMergeChangesetParent(string path, long firstChangeset, GitTfsRemote remote) { var firstChangesetOfBranch = _script.Changesets.FirstOrDefault(c => c.IsMergeChangeset && c.MergeChangesetDatas.MergeIntoBranch == path && c.MergeChangesetDatas.BeforeMergeChangesetId < firstChangeset); if (firstChangesetOfBranch != null) return firstChangesetOfBranch.MergeChangesetDatas.BeforeMergeChangesetId; return -1; } private ITfsChangeset BuildTfsChangeset(ScriptedChangeset changeset, IGitTfsRemote remote) { var tfsChangeset = _container.With<ITfsHelper>(this).With<IChangeset>(new Changeset(_versionControlServer, changeset)).GetInstance<TfsChangeset>(); tfsChangeset.Summary = new TfsChangesetInfo { ChangesetId = changeset.Id, Remote = remote }; return tfsChangeset; } class Changeset : IChangeset { private IVersionControlServer _versionControlServer; private ScriptedChangeset _changeset; public Changeset(IVersionControlServer versionControlServer, ScriptedChangeset changeset) { _versionControlServer = versionControlServer; _changeset = changeset; } public IChange[] Changes { get { return _changeset.Changes.Select(x => new Change(_versionControlServer, _changeset, x)).ToArray(); } } public string Committer { get { return "todo"; } } public DateTime CreationDate { get { return _changeset.CheckinDate; } } public string Comment { get { return _changeset.Comment; } } public int ChangesetId { get { return _changeset.Id; } } public IVersionControlServer VersionControlServer { get { throw new NotImplementedException(); } } public void Get(ITfsWorkspace workspace, IEnumerable<IChange> changes, Action<Exception> ignorableErrorHandler) { workspace.Get(this.ChangesetId, changes); } } class Change : IChange, IItem { IVersionControlServer _versionControlServer; ScriptedChangeset _changeset; ScriptedChange _change; public Change(IVersionControlServer versionControlServer, ScriptedChangeset changeset, ScriptedChange change) { _versionControlServer = versionControlServer; _changeset = changeset; _change = change; } TfsChangeType IChange.ChangeType { get { return _change.ChangeType; } } IItem IChange.Item { get { return this; } } IVersionControlServer IItem.VersionControlServer { get { return _versionControlServer; } } int IItem.ChangesetId { get { return _changeset.Id; } } string IItem.ServerItem { get { return _change.RepositoryPath; } } int IItem.DeletionId { get { return 0; } } TfsItemType IItem.ItemType { get { return _change.ItemType; } } int IItem.ItemId { get { return _change.ItemId.Value; } } long IItem.ContentLength { get { using (var temp = ((IItem)this).DownloadFile()) return new FileInfo(temp).Length; } } TemporaryFile IItem.DownloadFile() { var temp = new TemporaryFile(); using(var writer = new StreamWriter(temp)) writer.Write(_change.Content); return temp; } } #endregion #region workspaces public void WithWorkspace(string localDirectory, IGitTfsRemote remote, IEnumerable<Tuple<string, string>> mappings, TfsChangesetInfo versionToFetch, Action<ITfsWorkspace> action) { Trace.WriteLine("Setting up a TFS workspace at " + localDirectory); var fakeWorkspace = new FakeWorkspace(localDirectory, remote.TfsRepositoryPath); var workspace = _container.With("localDirectory").EqualTo(localDirectory) .With("remote").EqualTo(remote) .With("contextVersion").EqualTo(versionToFetch) .With("workspace").EqualTo(fakeWorkspace) .With("tfsHelper").EqualTo(this) .GetInstance<TfsWorkspace>(); action(workspace); } public void WithWorkspace(string directory, IGitTfsRemote remote, TfsChangesetInfo versionToFetch, Action<ITfsWorkspace> action) { Trace.WriteLine("Setting up a TFS workspace at " + directory); var fakeWorkspace = new FakeWorkspace(directory, remote.TfsRepositoryPath); var workspace = _container.With("localDirectory").EqualTo(directory) .With("remote").EqualTo(remote) .With("contextVersion").EqualTo(versionToFetch) .With("workspace").EqualTo(fakeWorkspace) .With("tfsHelper").EqualTo(this) .GetInstance<TfsWorkspace>(); action(workspace); } class FakeWorkspace : IWorkspace { string _directory; string _repositoryRoot; public FakeWorkspace(string directory, string repositoryRoot) { _directory = directory; _repositoryRoot = repositoryRoot; } public void GetSpecificVersion(IChangeset changeset) { GetSpecificVersion(changeset.ChangesetId, changeset.Changes); } public void GetSpecificVersion(int changeset, IEnumerable<IChange> changes) { var repositoryRoot = _repositoryRoot.ToLower(); if(!repositoryRoot.EndsWith("/")) repositoryRoot += "/"; foreach (var change in changes) { if (change.Item.ItemType == TfsItemType.File) { var outPath = Path.Combine(_directory, change.Item.ServerItem.ToLower().Replace(repositoryRoot, "")); var outDir = Path.GetDirectoryName(outPath); if (!Directory.Exists(outDir)) Directory.CreateDirectory(outDir); using (var download = change.Item.DownloadFile()) File.WriteAllText(outPath, File.ReadAllText(download.Path)); } } } #region unimplemented public void Merge(string sourceTfsPath, string tfsRepositoryPath) { throw new NotImplementedException(); } public IPendingChange[] GetPendingChanges() { throw new NotImplementedException(); } public ICheckinEvaluationResult EvaluateCheckin(TfsCheckinEvaluationOptions options, IPendingChange[] allChanges, IPendingChange[] changes, string comment, ICheckinNote checkinNote, IEnumerable<IWorkItemCheckinInfo> workItemChanges) { throw new NotImplementedException(); } public ICheckinEvaluationResult EvaluateCheckin(TfsCheckinEvaluationOptions options, IPendingChange[] allChanges, IPendingChange[] changes, string comment, string authors, ICheckinNote checkinNote, IEnumerable<IWorkItemCheckinInfo> workItemChanges) { throw new NotImplementedException(); } public void Shelve(IShelveset shelveset, IPendingChange[] changes, TfsShelvingOptions options) { throw new NotImplementedException(); } public int Checkin(IPendingChange[] changes, string comment, string author, ICheckinNote checkinNote, IEnumerable<IWorkItemCheckinInfo> workItemChanges, TfsPolicyOverrideInfo policyOverrideInfo, bool overrideGatedCheckIn) { throw new NotImplementedException(); } public int PendAdd(string path) { throw new NotImplementedException(); } public int PendEdit(string path) { throw new NotImplementedException(); } public int PendDelete(string path) { throw new NotImplementedException(); } public int PendRename(string pathFrom, string pathTo) { throw new NotImplementedException(); } public void ForceGetFile(string path, int changeset) { throw new NotImplementedException(); } public void GetSpecificVersion(int changeset) { throw new NotImplementedException(); } public string GetLocalItemForServerItem(string serverItem) { throw new NotImplementedException(); } public string GetServerItemForLocalItem(string localItem) { throw new NotImplementedException(); } public string OwnerName { get { throw new NotImplementedException(); } } #endregion } public void CleanupWorkspaces(string workingDirectory) { } public bool IsExistingInTfs(string path) { var exists = false; foreach (var changeset in _script.Changesets) { foreach (var change in changeset.Changes) { if (change.RepositoryPath == path) { exists = !change.ChangeType.IncludesOneOf(TfsChangeType.Delete); } } } return exists; } public bool CanGetBranchInformation { get { return true; } } public IChangeset GetChangeset(int changesetId) { return new Changeset(_versionControlServer, _script.Changesets.First(c => c.Id == changesetId)); } public IList<RootBranch> GetRootChangesetForBranch(string tfsPathBranchToCreate, int lastChangesetIdToCheck = -1, string tfsPathParentBranch = null) { var firstChangesetOfBranch = _script.Changesets.FirstOrDefault(c => c.IsBranchChangeset && c.BranchChangesetDatas.BranchPath == tfsPathBranchToCreate); if (firstChangesetOfBranch != null) return new List<RootBranch> { new RootBranch(firstChangesetOfBranch.BranchChangesetDatas.RootChangesetId, tfsPathBranchToCreate) }; return new List<RootBranch> { new RootBranch(-1, tfsPathBranchToCreate) }; } public IEnumerable<IBranchObject> GetBranches(bool getDeletedBranches = false) { var branches = new List<IBranchObject>(); branches.AddRange(_script.RootBranches.Select(b => new MockBranchObject { IsRoot = true, Path = b.BranchPath, ParentPath = null })); branches.AddRange(_script.Changesets.Where(c=>c.IsBranchChangeset).Select(c => new MockBranchObject { IsRoot = false, Path = c.BranchChangesetDatas.BranchPath, ParentPath = c.BranchChangesetDatas.ParentBranch })); return branches; } #endregion #region unimplemented public IShelveset CreateShelveset(IWorkspace workspace, string shelvesetName) { throw new NotImplementedException(); } public IEnumerable<IWorkItemCheckinInfo> GetWorkItemInfos(IEnumerable<string> workItems, TfsWorkItemCheckinAction checkinAction) { throw new NotImplementedException(); } public IEnumerable<IWorkItemCheckedInfo> GetWorkItemCheckedInfos(IEnumerable<string> workItems, TfsWorkItemCheckinAction checkinAction) { throw new NotImplementedException(); } public ICheckinNote CreateCheckinNote(Dictionary<string, string> checkinNotes) { throw new NotImplementedException(); } public ITfsChangeset GetChangeset(int changesetId, IGitTfsRemote remote) { throw new NotImplementedException(); } public bool HasShelveset(string shelvesetName) { throw new NotImplementedException(); } public ITfsChangeset GetShelvesetData(IGitTfsRemote remote, string shelvesetOwner, string shelvesetName) { throw new NotImplementedException(); } public int ListShelvesets(ShelveList shelveList, IGitTfsRemote remote) { throw new NotImplementedException(); } public IEnumerable<string> GetAllTfsRootBranchesOrderedByCreation() { return new List<string>(); } public IEnumerable<TfsLabel> GetLabels(string tfsPathBranch, string nameFilter = null) { throw new NotImplementedException(); } public void CreateBranch(string sourcePath, string targetPath, int changesetId, string comment = null) { throw new NotImplementedException(); } public void CreateTfsRootBranch(string projectName, string mainBranch, string gitRepositoryPath, bool createTeamProjectFolder) { throw new NotImplementedException(); } #endregion private class FakeVersionControlServer : IVersionControlServer { Script _script; public FakeVersionControlServer(Script script) { _script = script; } public IItem GetItem(int itemId, int changesetNumber) { var match = _script.Changesets.AsEnumerable().Reverse() .SkipWhile(cs => cs.Id > changesetNumber) .Select(cs => new { Changeset = cs, Change = cs.Changes.SingleOrDefault(change => change.ItemId == itemId) }) .First(x => x.Change != null); return new Change(this, match.Changeset, match.Change); } public IItem GetItem(string itemPath, int changesetNumber) { throw new NotImplementedException(); } public IItem[] GetItems(string itemPath, int changesetNumber, TfsRecursionType recursionType) { throw new NotImplementedException(); } public IEnumerable<IChangeset> QueryHistory(string path, int version, int deletionId, TfsRecursionType recursion, string user, int versionFrom, int versionTo, int maxCount, bool includeChanges, bool slotMode, bool includeDownloadInfo) { throw new NotImplementedException(); } } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Emulation.ArmProcessor.FlashMemory { using System; using System.Collections.Generic; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using ElementTypes = Microsoft.Zelig.MetaData.ElementTypes; //--// public class S29WS064 : Simulator.MemoryHandler { const uint Sector4KWord = 4 * 1024 * sizeof(ushort); const uint Sector32KWord = 32 * 1024 * sizeof(ushort); const uint ChipSize = 8 * 1024 * 1024; //--// static ushort[] sequence_CFI = new ushort[] { 0x055, 0x0098 }; static ushort[] sequence_PROGRAM = new ushort[] { 0x555, 0x00AA , 0x2AA, 0x0055 , 0x555, 0x00A0 }; static ushort[] sequence_ERASE = new ushort[] { 0x555, 0x00AA , 0x2AA, 0x0055 , 0x555, 0x0080 , 0x555, 0x00AA , 0x2AA, 0x0055 }; enum Mode { Normal , Query , Program, Erase , } class SequenceTracker { // // State // internal ushort[] m_sequence; internal int m_pos; internal ulong m_lastWrite; // // Constructor Methods // internal SequenceTracker( ushort[] sequence ) { m_sequence = sequence; m_pos = 0; } // // Helper Methods // internal void Reset() { m_pos = 0; } internal void Advance( uint relativeAddress , ushort value , Simulator owner ) { // // If the writes are too spaced out, abort. // if(m_pos > 0 && owner.ClockTicks - m_lastWrite > 5 * 30) { Reset(); return; } if(IsMatch( relativeAddress, value, m_sequence, m_pos ) == false) { Reset(); return; } m_pos += 2; m_lastWrite = owner.ClockTicks; } private static bool IsMatch( uint relativeAddress , ushort value , ushort[] sequence , int pos ) { return (sequence[pos ] == relativeAddress / sizeof(ushort) && sequence[pos+1] == value ); } // // Access Methods // internal bool IsRecognized { get { return m_pos == m_sequence.Length; } } } class BankState { static ushort[] query_results = new ushort[] { 0x10, 0x0051, // 0x11, 0x0052, // Query Unique ASCII string "QRY" 0x12, 0x0059, // 0x13, 0x0002, // Primary OEM Command Set 0x14, 0x0000, // 0x15, 0x0040, // Address for Primary Extended Table 0x16, 0x0000, // 0x17, 0x0000, // Alternate OEM Command Set 0x18, 0x0000, // 0x2C, 0x0003, // Number of Erase Block Regions within device. 0x2D, 0x0007, // Erase Block Region 1 Information 0x2E, 0x0000, // 0x2F, 0x0020, // 0x30, 0x0000, // 0x31, 0x007D, // Erase Block Region 2 Information 0x32, 0x0000, // 0x33, 0x0000, // 0x34, 0x0001, // 0x35, 0x0007, // Erase Block Region 3 Information 0x36, 0x0000, // 0x37, 0x0020, // 0x38, 0x0000, // }; const ushort resetCommand = 0x00F0; const ushort eraseCommand = 0x0030; const ushort c_DQ7 = (ushort)(1u << 7); const ushort c_DQ6 = (ushort)(1u << 6); const ushort c_DQ3 = (ushort)(1u << 3); const ushort c_DQ2 = (ushort)(1u << 2); // // State // internal uint m_addressStart; internal uint m_addressEnd; internal uint[] m_sectorSizes; internal Mode m_mode; internal ushort m_lastStatusValue; internal ulong m_timer; internal int m_erasingSectorIndex; internal uint m_programmingAddress; internal ushort m_programmingValue; // // Constructor Methods // internal BankState( uint addressStart , params uint[] sectorDefinition ) { uint totalSize = 0; uint totalSectors = 0; for(int i = 0; i < sectorDefinition.Length; i += 2) { uint sectorSize = sectorDefinition[i ]; uint sectorNum = sectorDefinition[i+1]; totalSectors += sectorNum; totalSize += sectorNum * sectorSize; } m_addressStart = addressStart; m_addressEnd = addressStart + totalSize; m_sectorSizes = new uint[totalSectors]; m_mode = Mode.Normal; uint offset = 0; for(int i = 0; i < sectorDefinition.Length; i += 2) { uint sectorSize = sectorDefinition[i ]; uint sectorNum = sectorDefinition[i+1]; while(sectorNum-- > 0) { m_sectorSizes[offset++] = sectorSize; } } } // // Helper Methods // internal void HandleWrite( Simulator owner , uint address , ushort value ) { switch(m_mode) { case Mode.Normal: break; case Mode.Query: if(address == 0 && value == resetCommand) { m_mode = Mode.Normal; } break; case Mode.Program: m_programmingAddress = address; m_programmingValue = value; m_timer = owner.ClockTicks + 10 * 30; // BUGBUG: We need a way to convert from Ticks to Time. m_lastStatusValue = (ushort)(~value & c_DQ7); // DQ7# break; case Mode.Erase: uint offset = address - m_addressStart; for(int i = 0; i < m_sectorSizes.Length; i++) { if(offset < m_sectorSizes[i]) { m_erasingSectorIndex = i; break; } offset -= m_sectorSizes[i]; } //m_timer = owner.ClockTicks + 400 * 1000 * 30; // BUGBUG: We need a way to convert from Ticks to Time. m_timer = owner.ClockTicks + 40 * 30; // BUGBUG: We need a way to convert from Ticks to Time. m_lastStatusValue = c_DQ3; break; } } internal bool HandleRead( Simulator owner , uint address , out ushort value ) { switch(m_mode) { case Mode.Normal: break; case Mode.Query: for(int i = 0; i < query_results.Length; i += 2) { if(query_results[i] == address / sizeof(ushort)) { value = query_results[i+1]; return true; } } value = 0xFFFF; return true; case Mode.Program: if(owner.ClockTicks < m_timer) { value = m_lastStatusValue; m_lastStatusValue ^= c_DQ6; // Toggle DQ6. return true; } m_mode = Mode.Normal; break; case Mode.Erase: if(owner.ClockTicks < m_timer) { value = m_lastStatusValue; m_lastStatusValue ^= c_DQ6 | c_DQ2; // Toggle DQ6 and DQ2. return true; } m_mode = Mode.Normal; break; } value = 0xFFFF; return false; } internal bool FindSector( uint address , out uint sectorStart , out uint sectorEnd ) { if(m_addressStart <= address && address < m_addressEnd) { uint sector = m_addressStart; foreach(uint sectorSize in m_sectorSizes) { uint sectorNext = sector + sectorSize; if(sector <= address && address < sectorNext) { sectorStart = sector; sectorEnd = sectorNext; return true; } sector = sectorNext; } } sectorStart = 0; sectorEnd = 0; return false; } } // // State // BankState[] m_banks; Mode m_mode; SequenceTracker m_sequenceTracker_CFI; SequenceTracker m_sequenceTracker_Program; SequenceTracker m_sequenceTracker_Erase; // // Constructor Methods // public S29WS064() { m_banks = new BankState[4]; m_mode = Mode.Normal; // // Bank A // m_banks[0] = new BankState( 0, Sector4KWord, 8, Sector32KWord, 15 ); // // Bank B // m_banks[1] = new BankState( m_banks[0].m_addressEnd, Sector32KWord, 48 ); // // Bank C // m_banks[2] = new BankState( m_banks[1].m_addressEnd, Sector32KWord, 48 ); // // Bank D // m_banks[3] = new BankState( m_banks[2].m_addressEnd, Sector32KWord, 48, Sector4KWord, 8 ); //--// m_sequenceTracker_CFI = new SequenceTracker( sequence_CFI ); m_sequenceTracker_Program = new SequenceTracker( sequence_PROGRAM ); m_sequenceTracker_Erase = new SequenceTracker( sequence_ERASE ); } // // Helper Methods // public override void Initialize( Simulator owner , ulong rangeLength , uint rangeWidth , uint readLatency , uint writeLatency ) { base.Initialize( owner, rangeLength, rangeWidth, readLatency, writeLatency ); // // Erase the whole chip. // for(int i = 0; i < m_target.Length; i++) { m_target[i] = 0xFFFFFFFF; } } public override uint Read( uint address , uint relativeAddress , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { if(m_owner.AreTimingUpdatesEnabled) { BankState bank; uint sectorStart; uint sectorEnd; if(FindSector( relativeAddress, out bank, out sectorStart, out sectorEnd )) { ushort value; if(bank.HandleRead( m_owner, relativeAddress, out value )) { UpdateClockTicksForLoad( address, kind ); return value; } } } return base.Read( address, relativeAddress, kind ); } public override void Write( uint address , uint relativeAddress , uint value , TargetAdapterAbstractionLayer.MemoryAccessType kind ) { if(m_owner.AreTimingUpdatesEnabled) { BankState bank; uint sectorStart; uint sectorEnd; if(kind != TargetAdapterAbstractionLayer.MemoryAccessType.UINT16) { throw new TargetAdapterAbstractionLayer.BusErrorException( address, kind ); } UpdateClockTicksForStore( address, kind ); ushort valueShort = (ushort)value; if(m_mode == Mode.Normal) { m_sequenceTracker_CFI .Advance( relativeAddress, valueShort, m_owner ); m_sequenceTracker_Program.Advance( relativeAddress, valueShort, m_owner ); m_sequenceTracker_Erase .Advance( relativeAddress, valueShort, m_owner ); if(m_sequenceTracker_CFI.IsRecognized) { foreach(var bank2 in m_banks) { bank2.m_mode = Mode.Query; } m_mode = Mode.Query; return; } if(m_sequenceTracker_Program.IsRecognized) { m_mode = Mode.Program; return; } if(m_sequenceTracker_Erase.IsRecognized) { m_mode = Mode.Erase; return; } } if(m_mode != Mode.Normal) { m_sequenceTracker_CFI .Reset(); m_sequenceTracker_Program.Reset(); m_sequenceTracker_Erase .Reset(); if(FindSector( relativeAddress, out bank, out sectorStart, out sectorEnd )) { bank.m_mode = m_mode; bank.HandleWrite( m_owner, relativeAddress, valueShort ); switch(m_mode) { case Mode.Query: if(bank.m_mode == Mode.Normal) { foreach(var bank2 in m_banks) { bank2.m_mode = Mode.Normal; } m_mode = Mode.Normal; } break; case Mode.Program: base.Write( relativeAddress, relativeAddress, value, kind ); m_mode = Mode.Normal; break; case Mode.Erase: while(sectorStart < sectorEnd) { base.Write( sectorStart, sectorStart, 0xFFFF, TargetAdapterAbstractionLayer.MemoryAccessType.UINT16 ); sectorStart += sizeof(ushort); } m_mode = Mode.Normal; break; } } } return; } base.Write( address, relativeAddress, value, kind ); } //--// bool FindSector( uint address , out BankState bank , out uint sectorStart , out uint sectorEnd ) { foreach(BankState bank2 in m_banks) { if(bank2.FindSector( address, out sectorStart, out sectorEnd )) { bank = bank2; return true; } } bank = null; sectorStart = 0; sectorEnd = 0; return false; } } }
namespace WHOperation { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region 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(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.tfdnno = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.DNNo = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.POLine = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Vendor = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.PartNumber = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.MFGPartNo = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.RIRNo = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.PONumber = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ASNMFGPN = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.DNQty = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.DNDate = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.DNSite = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.t_urg = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.t_loc = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.t_msd = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.t_cust_part = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.t_shelf_life = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.t_wt = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.t_wt_ind = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.t_conn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.PrintedQty = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.RowID = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.label14 = new System.Windows.Forms.Label(); this.tfdndate = new System.Windows.Forms.DateTimePicker(); this.label17 = new System.Windows.Forms.Label(); this.cbsystem = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.textBox2 = new System.Windows.Forms.TextBox(); this.cbfiltertype = new System.Windows.Forms.ComboBox(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.dataGridView3 = new System.Windows.Forms.DataGridView(); this.TempID = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.pb1 = new System.Windows.Forms.PictureBox(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.splitContainer2 = new System.Windows.Forms.SplitContainer(); this.tab3_QRBar = new System.Windows.Forms.TabControl(); this.tabPage5_OldQRBar = new System.Windows.Forms.TabPage(); this.bStop = new System.Windows.Forms.Button(); this.bEnableScan = new System.Windows.Forms.Button(); this.tfscanarea = new System.Windows.Forms.TextBox(); this.bDisableScan = new System.Windows.Forms.Button(); this.bStart = new System.Windows.Forms.Button(); this.label22 = new System.Windows.Forms.Label(); this.tabPage6_NewQRBar = new System.Windows.Forms.TabPage(); this.txt0ListKeyMsg = new System.Windows.Forms.ListBox(); this.btn6_StopQR = new System.Windows.Forms.Button(); this.btn5_startQR = new System.Windows.Forms.Button(); this.label9 = new System.Windows.Forms.Label(); this.cbtrimmfgpart = new System.Windows.Forms.CheckBox(); this.tfnoofcartons = new System.Windows.Forms.TextBox(); this.label10 = new System.Windows.Forms.Label(); this.cbprintcartonlabel = new System.Windows.Forms.CheckBox(); this.lMRecPartNumber = new System.Windows.Forms.Label(); this.lMRecQty = new System.Windows.Forms.Label(); this.lMRecMfgPart = new System.Windows.Forms.Label(); this.lMExpireDate = new System.Windows.Forms.Label(); this.lMDateCode = new System.Windows.Forms.Label(); this.lMLotNumber = new System.Windows.Forms.Label(); this.pbdnpartnumber = new System.Windows.Forms.PictureBox(); this.ldnpartnumber = new System.Windows.Forms.Label(); this.tfdnpartnumber = new System.Windows.Forms.TextBox(); this.cbSmartScan = new System.Windows.Forms.CheckBox(); this.cbAutoPrint = new System.Windows.Forms.CheckBox(); this.label5 = new System.Windows.Forms.Label(); this.tfsite = new System.Windows.Forms.TextBox(); this.pbexpiredate = new System.Windows.Forms.PictureBox(); this.pblotnumber = new System.Windows.Forms.PictureBox(); this.pbrecmfgpart = new System.Windows.Forms.PictureBox(); this.pbrecqty = new System.Windows.Forms.PictureBox(); this.pbmfgdate = new System.Windows.Forms.PictureBox(); this.pbdatecode = new System.Windows.Forms.PictureBox(); this.tfrecmfgrpart = new System.Windows.Forms.TextBox(); this.lrecmfgpart = new System.Windows.Forms.Label(); this.tfexpiredate = new System.Windows.Forms.TextBox(); this.tfmfgdate = new System.Windows.Forms.TextBox(); this.tfnooflabels = new System.Windows.Forms.TextBox(); this.tfhdndate = new System.Windows.Forms.TextBox(); this.label21 = new System.Windows.Forms.Label(); this.lmfgdate = new System.Windows.Forms.Label(); this.label16 = new System.Windows.Forms.Label(); this.label20 = new System.Windows.Forms.Label(); this.cbprintertype = new System.Windows.Forms.ComboBox(); this.label15 = new System.Windows.Forms.Label(); this.cbport = new System.Windows.Forms.ComboBox(); this.tfdnqty = new System.Windows.Forms.TextBox(); this.label13 = new System.Windows.Forms.Label(); this.tfcumqty = new System.Windows.Forms.TextBox(); this.label12 = new System.Windows.Forms.Label(); this.tfdatecode = new System.Windows.Forms.TextBox(); this.tfmfgpart = new System.Windows.Forms.TextBox(); this.tfrirno = new System.Windows.Forms.TextBox(); this.tfrecqty = new System.Windows.Forms.TextBox(); this.tflotno = new System.Windows.Forms.TextBox(); this.tfpartno = new System.Windows.Forms.TextBox(); this.tfvendor = new System.Windows.Forms.TextBox(); this.ldatecode = new System.Windows.Forms.Label(); this.lexpiredate = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.lrecqty = new System.Windows.Forms.Label(); this.llotnumber = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.panel4 = new System.Windows.Forms.Panel(); this.lStatus = new System.Windows.Forms.Label(); this.panel1 = new System.Windows.Forms.Panel(); this.label6 = new System.Windows.Forms.Label(); this.tftodndate = new System.Windows.Forms.DateTimePicker(); this.bGo = new System.Windows.Forms.Button(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.dgDNNumber = new System.Windows.Forms.DataGridView(); this.DNNumber = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.tabControl2 = new System.Windows.Forms.TabControl(); this.tabPage3 = new System.Windows.Forms.TabPage(); this.tabPage4 = new System.Windows.Forms.TabPage(); this.dgComplete = new System.Windows.Forms.DataGridView(); this.dataGridViewTextBoxColumn4 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn5 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn6 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn7 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn8 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn9 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn20 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.clearToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.reStartToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.tabControl1.SuspendLayout(); this.tabPage1.SuspendLayout(); this.groupBox4.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView3)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pb1)).BeginInit(); this.tabPage2.SuspendLayout(); this.groupBox2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).BeginInit(); this.splitContainer2.Panel1.SuspendLayout(); this.splitContainer2.Panel2.SuspendLayout(); this.splitContainer2.SuspendLayout(); this.tab3_QRBar.SuspendLayout(); this.tabPage5_OldQRBar.SuspendLayout(); this.tabPage6_NewQRBar.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pbdnpartnumber)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pbexpiredate)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pblotnumber)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pbrecmfgpart)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pbrecqty)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pbmfgdate)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pbdatecode)).BeginInit(); this.panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dgDNNumber)).BeginInit(); this.tabControl2.SuspendLayout(); this.tabPage3.SuspendLayout(); this.tabPage4.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dgComplete)).BeginInit(); this.contextMenuStrip1.SuspendLayout(); this.SuspendLayout(); // // tfdnno // this.tfdnno.Location = new System.Drawing.Point(206, 13); this.tfdnno.Name = "tfdnno"; this.tfdnno.Size = new System.Drawing.Size(100, 21); this.tfdnno.TabIndex = 3; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(137, 17); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(71, 12); this.label1.TabIndex = 2; this.label1.Text = "Supplier ID"; // // dataGridView1 // this.dataGridView1.AllowUserToAddRows = false; this.dataGridView1.AllowUserToDeleteRows = false; this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.DNNo, this.POLine, this.Vendor, this.PartNumber, this.MFGPartNo, this.RIRNo, this.PONumber, this.ASNMFGPN, this.DNQty, this.DNDate, this.DNSite, this.t_urg, this.t_loc, this.t_msd, this.t_cust_part, this.t_shelf_life, this.t_wt, this.t_wt_ind, this.t_conn, this.PrintedQty, this.RowID}); this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill; this.dataGridView1.Location = new System.Drawing.Point(3, 3); this.dataGridView1.MultiSelect = false; this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.ReadOnly = true; this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dataGridView1.Size = new System.Drawing.Size(727, 141); this.dataGridView1.TabIndex = 0; // // DNNo // this.DNNo.HeaderText = "DN-No"; this.DNNo.Name = "DNNo"; this.DNNo.ReadOnly = true; this.DNNo.Visible = false; this.DNNo.Width = 60; // // POLine // this.POLine.HeaderText = "Line"; this.POLine.Name = "POLine"; this.POLine.ReadOnly = true; this.POLine.Visible = false; this.POLine.Width = 30; // // Vendor // this.Vendor.HeaderText = "Vendor"; this.Vendor.Name = "Vendor"; this.Vendor.ReadOnly = true; this.Vendor.Visible = false; this.Vendor.Width = 60; // // PartNumber // this.PartNumber.HeaderText = "PartNumber"; this.PartNumber.Name = "PartNumber"; this.PartNumber.ReadOnly = true; this.PartNumber.Width = 130; // // MFGPartNo // this.MFGPartNo.HeaderText = "PO QPL-Part No"; this.MFGPartNo.Name = "MFGPartNo"; this.MFGPartNo.ReadOnly = true; this.MFGPartNo.Width = 130; // // RIRNo // this.RIRNo.HeaderText = "RIR-No"; this.RIRNo.Name = "RIRNo"; this.RIRNo.ReadOnly = true; // // PONumber // this.PONumber.HeaderText = "PONumber"; this.PONumber.Name = "PONumber"; this.PONumber.ReadOnly = true; this.PONumber.Width = 65; // // ASNMFGPN // this.ASNMFGPN.HeaderText = "ASN MFG P/N"; this.ASNMFGPN.Name = "ASNMFGPN"; this.ASNMFGPN.ReadOnly = true; this.ASNMFGPN.Width = 110; // // DNQty // this.DNQty.HeaderText = "DNQty"; this.DNQty.Name = "DNQty"; this.DNQty.ReadOnly = true; this.DNQty.Width = 45; // // DNDate // this.DNDate.HeaderText = "DN-Date"; this.DNDate.Name = "DNDate"; this.DNDate.ReadOnly = true; this.DNDate.Visible = false; this.DNDate.Width = 60; // // DNSite // this.DNSite.HeaderText = "DNSite"; this.DNSite.Name = "DNSite"; this.DNSite.ReadOnly = true; this.DNSite.Visible = false; // // t_urg // this.t_urg.HeaderText = "t_urg"; this.t_urg.Name = "t_urg"; this.t_urg.ReadOnly = true; this.t_urg.Visible = false; // // t_loc // this.t_loc.HeaderText = "t_loc"; this.t_loc.Name = "t_loc"; this.t_loc.ReadOnly = true; this.t_loc.Visible = false; // // t_msd // this.t_msd.HeaderText = "t_msd"; this.t_msd.Name = "t_msd"; this.t_msd.ReadOnly = true; this.t_msd.Visible = false; // // t_cust_part // this.t_cust_part.HeaderText = "t_cust_part"; this.t_cust_part.Name = "t_cust_part"; this.t_cust_part.ReadOnly = true; this.t_cust_part.Visible = false; // // t_shelf_life // this.t_shelf_life.HeaderText = "t_shelf_life"; this.t_shelf_life.Name = "t_shelf_life"; this.t_shelf_life.ReadOnly = true; this.t_shelf_life.Visible = false; // // t_wt // this.t_wt.HeaderText = "t_wt"; this.t_wt.Name = "t_wt"; this.t_wt.ReadOnly = true; this.t_wt.Visible = false; // // t_wt_ind // this.t_wt_ind.HeaderText = "t_wt_ind"; this.t_wt_ind.Name = "t_wt_ind"; this.t_wt_ind.ReadOnly = true; this.t_wt_ind.Visible = false; // // t_conn // this.t_conn.HeaderText = "t_conn"; this.t_conn.Name = "t_conn"; this.t_conn.ReadOnly = true; this.t_conn.Visible = false; // // PrintedQty // this.PrintedQty.HeaderText = "PrintedQty"; this.PrintedQty.Name = "PrintedQty"; this.PrintedQty.ReadOnly = true; this.PrintedQty.Width = 80; // // RowID // this.RowID.HeaderText = "RowID"; this.RowID.Name = "RowID"; this.RowID.ReadOnly = true; this.RowID.Visible = false; // // label14 // this.label14.AutoSize = true; this.label14.Location = new System.Drawing.Point(316, 17); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(47, 12); this.label14.TabIndex = 4; this.label14.Text = "DN Date"; // // tfdndate // this.tfdndate.CustomFormat = "MM/dd/yy"; this.tfdndate.Format = System.Windows.Forms.DateTimePickerFormat.Custom; this.tfdndate.Location = new System.Drawing.Point(371, 13); this.tfdndate.Name = "tfdndate"; this.tfdndate.Size = new System.Drawing.Size(98, 21); this.tfdndate.TabIndex = 5; this.tfdndate.Value = new System.DateTime(2013, 6, 5, 10, 23, 0, 0); // // label17 // this.label17.AutoSize = true; this.label17.Location = new System.Drawing.Point(18, 17); this.label17.Name = "label17"; this.label17.Size = new System.Drawing.Size(41, 12); this.label17.TabIndex = 0; this.label17.Text = "System"; // // cbsystem // this.cbsystem.Location = new System.Drawing.Point(65, 13); this.cbsystem.Name = "cbsystem"; this.cbsystem.ReadOnly = true; this.cbsystem.Size = new System.Drawing.Size(71, 21); this.cbsystem.TabIndex = 1; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(638, 17); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(41, 12); this.label2.TabIndex = 7; this.label2.Text = "Filter"; // // groupBox3 // this.groupBox3.Location = new System.Drawing.Point(1022, 5); this.groupBox3.Margin = new System.Windows.Forms.Padding(5); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(28, 24); this.groupBox3.TabIndex = 11; this.groupBox3.TabStop = false; this.groupBox3.Text = "Captured Image"; this.groupBox3.Visible = false; // // textBox2 // this.textBox2.Location = new System.Drawing.Point(800, 14); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(146, 21); this.textBox2.TabIndex = 9; this.textBox2.TextChanged += new System.EventHandler(this.textBox2_TextChanged); // // cbfiltertype // this.cbfiltertype.FormattingEnabled = true; this.cbfiltertype.Items.AddRange(new object[] { "Part Number", "Mfgr Part Number"}); this.cbfiltertype.Location = new System.Drawing.Point(673, 14); this.cbfiltertype.Name = "cbfiltertype"; this.cbfiltertype.Size = new System.Drawing.Size(121, 20); this.cbfiltertype.TabIndex = 8; // // tabControl1 // this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Location = new System.Drawing.Point(12, 234); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(978, 330); this.tabControl1.TabIndex = 20; // // tabPage1 // this.tabPage1.Controls.Add(this.groupBox4); this.tabPage1.Location = new System.Drawing.Point(4, 22); this.tabPage1.Name = "tabPage1"; this.tabPage1.Padding = new System.Windows.Forms.Padding(3); this.tabPage1.Size = new System.Drawing.Size(970, 304); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "Vendor Template"; this.tabPage1.UseVisualStyleBackColor = true; // // groupBox4 // this.groupBox4.Controls.Add(this.dataGridView3); this.groupBox4.Controls.Add(this.pb1); this.groupBox4.Location = new System.Drawing.Point(6, 6); this.groupBox4.Name = "groupBox4"; this.groupBox4.Size = new System.Drawing.Size(476, 238); this.groupBox4.TabIndex = 12; this.groupBox4.TabStop = false; this.groupBox4.Text = "Vendor Template"; // // dataGridView3 // this.dataGridView3.AllowUserToAddRows = false; this.dataGridView3.AllowUserToDeleteRows = false; this.dataGridView3.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView3.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.TempID}); this.dataGridView3.Location = new System.Drawing.Point(11, 18); this.dataGridView3.Name = "dataGridView3"; this.dataGridView3.ReadOnly = true; this.dataGridView3.Size = new System.Drawing.Size(142, 216); this.dataGridView3.TabIndex = 0; // // TempID // this.TempID.HeaderText = "TemplateID"; this.TempID.Name = "TempID"; this.TempID.ReadOnly = true; this.TempID.Width = 70; // // pb1 // this.pb1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.pb1.Location = new System.Drawing.Point(165, 18); this.pb1.Name = "pb1"; this.pb1.Size = new System.Drawing.Size(305, 214); this.pb1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.pb1.TabIndex = 0; this.pb1.TabStop = false; // // tabPage2 // this.tabPage2.Controls.Add(this.groupBox2); this.tabPage2.Location = new System.Drawing.Point(4, 22); this.tabPage2.Name = "tabPage2"; this.tabPage2.Padding = new System.Windows.Forms.Padding(3); this.tabPage2.Size = new System.Drawing.Size(970, 304); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Capture PIMS Data"; this.tabPage2.UseVisualStyleBackColor = true; // // groupBox2 // this.groupBox2.Controls.Add(this.splitContainer2); this.groupBox2.Controls.Add(this.panel4); this.groupBox2.Controls.Add(this.lStatus); this.groupBox2.Location = new System.Drawing.Point(6, 6); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(943, 295); this.groupBox2.TabIndex = 0; this.groupBox2.TabStop = false; this.groupBox2.Text = "PIMS Data Capture"; // // splitContainer2 // this.splitContainer2.FixedPanel = System.Windows.Forms.FixedPanel.Panel1; this.splitContainer2.Location = new System.Drawing.Point(3, 15); this.splitContainer2.Name = "splitContainer2"; // // splitContainer2.Panel1 // this.splitContainer2.Panel1.Controls.Add(this.tab3_QRBar); // // splitContainer2.Panel2 // this.splitContainer2.Panel2.AutoScroll = true; this.splitContainer2.Panel2.Controls.Add(this.cbtrimmfgpart); this.splitContainer2.Panel2.Controls.Add(this.tfnoofcartons); this.splitContainer2.Panel2.Controls.Add(this.label10); this.splitContainer2.Panel2.Controls.Add(this.cbprintcartonlabel); this.splitContainer2.Panel2.Controls.Add(this.lMRecPartNumber); this.splitContainer2.Panel2.Controls.Add(this.lMRecQty); this.splitContainer2.Panel2.Controls.Add(this.lMRecMfgPart); this.splitContainer2.Panel2.Controls.Add(this.lMExpireDate); this.splitContainer2.Panel2.Controls.Add(this.lMDateCode); this.splitContainer2.Panel2.Controls.Add(this.lMLotNumber); this.splitContainer2.Panel2.Controls.Add(this.pbdnpartnumber); this.splitContainer2.Panel2.Controls.Add(this.ldnpartnumber); this.splitContainer2.Panel2.Controls.Add(this.tfdnpartnumber); this.splitContainer2.Panel2.Controls.Add(this.cbSmartScan); this.splitContainer2.Panel2.Controls.Add(this.cbAutoPrint); this.splitContainer2.Panel2.Controls.Add(this.label5); this.splitContainer2.Panel2.Controls.Add(this.tfsite); this.splitContainer2.Panel2.Controls.Add(this.pbexpiredate); this.splitContainer2.Panel2.Controls.Add(this.pblotnumber); this.splitContainer2.Panel2.Controls.Add(this.pbrecmfgpart); this.splitContainer2.Panel2.Controls.Add(this.pbrecqty); this.splitContainer2.Panel2.Controls.Add(this.pbmfgdate); this.splitContainer2.Panel2.Controls.Add(this.pbdatecode); this.splitContainer2.Panel2.Controls.Add(this.tfrecmfgrpart); this.splitContainer2.Panel2.Controls.Add(this.lrecmfgpart); this.splitContainer2.Panel2.Controls.Add(this.tfexpiredate); this.splitContainer2.Panel2.Controls.Add(this.tfmfgdate); this.splitContainer2.Panel2.Controls.Add(this.tfnooflabels); this.splitContainer2.Panel2.Controls.Add(this.tfhdndate); this.splitContainer2.Panel2.Controls.Add(this.label21); this.splitContainer2.Panel2.Controls.Add(this.lmfgdate); this.splitContainer2.Panel2.Controls.Add(this.label16); this.splitContainer2.Panel2.Controls.Add(this.label20); this.splitContainer2.Panel2.Controls.Add(this.cbprintertype); this.splitContainer2.Panel2.Controls.Add(this.label15); this.splitContainer2.Panel2.Controls.Add(this.cbport); this.splitContainer2.Panel2.Controls.Add(this.tfdnqty); this.splitContainer2.Panel2.Controls.Add(this.label13); this.splitContainer2.Panel2.Controls.Add(this.tfcumqty); this.splitContainer2.Panel2.Controls.Add(this.label12); this.splitContainer2.Panel2.Controls.Add(this.tfdatecode); this.splitContainer2.Panel2.Controls.Add(this.tfmfgpart); this.splitContainer2.Panel2.Controls.Add(this.tfrirno); this.splitContainer2.Panel2.Controls.Add(this.tfrecqty); this.splitContainer2.Panel2.Controls.Add(this.tflotno); this.splitContainer2.Panel2.Controls.Add(this.tfpartno); this.splitContainer2.Panel2.Controls.Add(this.tfvendor); this.splitContainer2.Panel2.Controls.Add(this.ldatecode); this.splitContainer2.Panel2.Controls.Add(this.lexpiredate); this.splitContainer2.Panel2.Controls.Add(this.label8); this.splitContainer2.Panel2.Controls.Add(this.label7); this.splitContainer2.Panel2.Controls.Add(this.lrecqty); this.splitContainer2.Panel2.Controls.Add(this.llotnumber); this.splitContainer2.Panel2.Controls.Add(this.label4); this.splitContainer2.Panel2.Controls.Add(this.label3); this.splitContainer2.Panel2.Controls.Add(this.button1); this.splitContainer2.Size = new System.Drawing.Size(921, 260); this.splitContainer2.SplitterDistance = 269; this.splitContainer2.TabIndex = 0; // // tab3_QRBar // this.tab3_QRBar.Controls.Add(this.tabPage6_NewQRBar); this.tab3_QRBar.Controls.Add(this.tabPage5_OldQRBar); this.tab3_QRBar.Dock = System.Windows.Forms.DockStyle.Fill; this.tab3_QRBar.Location = new System.Drawing.Point(0, 0); this.tab3_QRBar.Name = "tab3_QRBar"; this.tab3_QRBar.SelectedIndex = 0; this.tab3_QRBar.Size = new System.Drawing.Size(269, 260); this.tab3_QRBar.TabIndex = 6; // // tabPage5_OldQRBar // this.tabPage5_OldQRBar.Controls.Add(this.bStop); this.tabPage5_OldQRBar.Controls.Add(this.bEnableScan); this.tabPage5_OldQRBar.Controls.Add(this.tfscanarea); this.tabPage5_OldQRBar.Controls.Add(this.bDisableScan); this.tabPage5_OldQRBar.Controls.Add(this.bStart); this.tabPage5_OldQRBar.Controls.Add(this.label22); this.tabPage5_OldQRBar.Location = new System.Drawing.Point(4, 22); this.tabPage5_OldQRBar.Name = "tabPage5_OldQRBar"; this.tabPage5_OldQRBar.Padding = new System.Windows.Forms.Padding(3); this.tabPage5_OldQRBar.Size = new System.Drawing.Size(261, 234); this.tabPage5_OldQRBar.TabIndex = 0; this.tabPage5_OldQRBar.Text = "Old QR Bar"; this.tabPage5_OldQRBar.UseVisualStyleBackColor = true; // // bStop // this.bStop.Enabled = false; this.bStop.Location = new System.Drawing.Point(87, 2); this.bStop.Name = "bStop"; this.bStop.Size = new System.Drawing.Size(78, 20); this.bStop.TabIndex = 1; this.bStop.Text = "Stop"; this.bStop.UseVisualStyleBackColor = true; this.bStop.Click += new System.EventHandler(this.bStop_Click); // // bEnableScan // this.bEnableScan.Location = new System.Drawing.Point(171, 23); this.bEnableScan.Name = "bEnableScan"; this.bEnableScan.Size = new System.Drawing.Size(78, 20); this.bEnableScan.TabIndex = 5; this.bEnableScan.Text = "Enable"; this.bEnableScan.UseVisualStyleBackColor = true; this.bEnableScan.Visible = false; // // tfscanarea // this.tfscanarea.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.tfscanarea.Location = new System.Drawing.Point(1, 51); this.tfscanarea.Multiline = true; this.tfscanarea.Name = "tfscanarea"; this.tfscanarea.Size = new System.Drawing.Size(256, 180); this.tfscanarea.TabIndex = 3; // // bDisableScan // this.bDisableScan.Location = new System.Drawing.Point(87, 23); this.bDisableScan.Name = "bDisableScan"; this.bDisableScan.Size = new System.Drawing.Size(78, 20); this.bDisableScan.TabIndex = 4; this.bDisableScan.Text = "Disable"; this.bDisableScan.UseVisualStyleBackColor = true; this.bDisableScan.Visible = false; // // bStart // this.bStart.Location = new System.Drawing.Point(6, 2); this.bStart.Name = "bStart"; this.bStart.Size = new System.Drawing.Size(78, 20); this.bStart.TabIndex = 0; this.bStart.Text = "Start"; this.bStart.UseVisualStyleBackColor = true; this.bStart.Click += new System.EventHandler(this.button2_Click); // // label22 // this.label22.AutoSize = true; this.label22.Location = new System.Drawing.Point(7, 29); this.label22.Name = "label22"; this.label22.Size = new System.Drawing.Size(59, 12); this.label22.TabIndex = 2; this.label22.Text = "Scan Area"; // // tabPage6_NewQRBar // this.tabPage6_NewQRBar.Controls.Add(this.txt0ListKeyMsg); this.tabPage6_NewQRBar.Controls.Add(this.btn6_StopQR); this.tabPage6_NewQRBar.Controls.Add(this.btn5_startQR); this.tabPage6_NewQRBar.Controls.Add(this.label9); this.tabPage6_NewQRBar.Location = new System.Drawing.Point(4, 22); this.tabPage6_NewQRBar.Name = "tabPage6_NewQRBar"; this.tabPage6_NewQRBar.Padding = new System.Windows.Forms.Padding(3); this.tabPage6_NewQRBar.Size = new System.Drawing.Size(261, 234); this.tabPage6_NewQRBar.TabIndex = 1; this.tabPage6_NewQRBar.Text = "New QR Bar"; this.tabPage6_NewQRBar.UseVisualStyleBackColor = true; // // txt0ListKeyMsg // this.txt0ListKeyMsg.ContextMenuStrip = this.contextMenuStrip1; this.txt0ListKeyMsg.FormattingEnabled = true; this.txt0ListKeyMsg.ItemHeight = 12; this.txt0ListKeyMsg.Location = new System.Drawing.Point(3, 72); this.txt0ListKeyMsg.Name = "txt0ListKeyMsg"; this.txt0ListKeyMsg.Size = new System.Drawing.Size(252, 160); this.txt0ListKeyMsg.TabIndex = 11; // // btn6_StopQR // this.btn6_StopQR.Enabled = false; this.btn6_StopQR.Location = new System.Drawing.Point(142, 11); this.btn6_StopQR.Name = "btn6_StopQR"; this.btn6_StopQR.Size = new System.Drawing.Size(85, 36); this.btn6_StopQR.TabIndex = 7; this.btn6_StopQR.Text = "Stop"; this.btn6_StopQR.UseVisualStyleBackColor = true; this.btn6_StopQR.Click += new System.EventHandler(this.btn6_StopQR_Click); // // btn5_startQR // this.btn5_startQR.Location = new System.Drawing.Point(36, 11); this.btn5_startQR.Name = "btn5_startQR"; this.btn5_startQR.Size = new System.Drawing.Size(85, 36); this.btn5_startQR.TabIndex = 6; this.btn5_startQR.Text = "Start"; this.btn5_startQR.UseVisualStyleBackColor = true; this.btn5_startQR.Click += new System.EventHandler(this.btn5_startQR_Click); // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(6, 57); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(59, 12); this.label9.TabIndex = 8; this.label9.Text = "Scan Area"; // // cbtrimmfgpart // this.cbtrimmfgpart.AutoSize = true; this.cbtrimmfgpart.Checked = true; this.cbtrimmfgpart.CheckState = System.Windows.Forms.CheckState.Checked; this.cbtrimmfgpart.Enabled = false; this.cbtrimmfgpart.Location = new System.Drawing.Point(554, 66); this.cbtrimmfgpart.Name = "cbtrimmfgpart"; this.cbtrimmfgpart.Size = new System.Drawing.Size(102, 16); this.cbtrimmfgpart.TabIndex = 62; this.cbtrimmfgpart.Text = "Trim MFG Part"; this.cbtrimmfgpart.UseVisualStyleBackColor = true; // // tfnoofcartons // this.tfnoofcartons.Location = new System.Drawing.Point(439, 27); this.tfnoofcartons.Name = "tfnoofcartons"; this.tfnoofcartons.Size = new System.Drawing.Size(32, 21); this.tfnoofcartons.TabIndex = 61; this.tfnoofcartons.Text = "1"; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(353, 28); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(95, 12); this.label10.TabIndex = 60; this.label10.Text = "No.Of Carton(s)"; // // cbprintcartonlabel // this.cbprintcartonlabel.AutoSize = true; this.cbprintcartonlabel.Checked = true; this.cbprintcartonlabel.CheckState = System.Windows.Forms.CheckState.Checked; this.cbprintcartonlabel.Location = new System.Drawing.Point(554, 45); this.cbprintcartonlabel.Name = "cbprintcartonlabel"; this.cbprintcartonlabel.Size = new System.Drawing.Size(132, 16); this.cbprintcartonlabel.TabIndex = 9; this.cbprintcartonlabel.Text = "Print Carton Label"; this.cbprintcartonlabel.UseVisualStyleBackColor = true; // // lMRecPartNumber // this.lMRecPartNumber.AutoSize = true; this.lMRecPartNumber.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lMRecPartNumber.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(0))))); this.lMRecPartNumber.Location = new System.Drawing.Point(264, 109); this.lMRecPartNumber.Name = "lMRecPartNumber"; this.lMRecPartNumber.Size = new System.Drawing.Size(15, 20); this.lMRecPartNumber.TabIndex = 59; this.lMRecPartNumber.Text = "*"; // // lMRecQty // this.lMRecQty.AutoSize = true; this.lMRecQty.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lMRecQty.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(0))))); this.lMRecQty.Location = new System.Drawing.Point(6, 177); this.lMRecQty.Name = "lMRecQty"; this.lMRecQty.Size = new System.Drawing.Size(15, 20); this.lMRecQty.TabIndex = 58; this.lMRecQty.Text = "*"; // // lMRecMfgPart // this.lMRecMfgPart.AutoSize = true; this.lMRecMfgPart.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lMRecMfgPart.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(0))))); this.lMRecMfgPart.Location = new System.Drawing.Point(264, 134); this.lMRecMfgPart.Name = "lMRecMfgPart"; this.lMRecMfgPart.Size = new System.Drawing.Size(15, 20); this.lMRecMfgPart.TabIndex = 57; this.lMRecMfgPart.Text = "*"; this.lMRecMfgPart.Visible = false; // // lMExpireDate // this.lMExpireDate.AutoSize = true; this.lMExpireDate.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lMExpireDate.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(0))))); this.lMExpireDate.Location = new System.Drawing.Point(264, 154); this.lMExpireDate.Name = "lMExpireDate"; this.lMExpireDate.Size = new System.Drawing.Size(15, 20); this.lMExpireDate.TabIndex = 56; this.lMExpireDate.Text = "*"; this.lMExpireDate.Visible = false; // // lMDateCode // this.lMDateCode.AutoSize = true; this.lMDateCode.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lMDateCode.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(0))))); this.lMDateCode.Location = new System.Drawing.Point(6, 132); this.lMDateCode.Name = "lMDateCode"; this.lMDateCode.Size = new System.Drawing.Size(15, 20); this.lMDateCode.TabIndex = 55; this.lMDateCode.Text = "*"; this.lMDateCode.Visible = false; // // lMLotNumber // this.lMLotNumber.AutoSize = true; this.lMLotNumber.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lMLotNumber.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(0))))); this.lMLotNumber.Location = new System.Drawing.Point(264, 178); this.lMLotNumber.Name = "lMLotNumber"; this.lMLotNumber.Size = new System.Drawing.Size(15, 20); this.lMLotNumber.TabIndex = 54; this.lMLotNumber.Text = "*"; this.lMLotNumber.Visible = false; // // pbdnpartnumber // this.pbdnpartnumber.Image = global::WHOperation.Properties.Resources.bdelete; this.pbdnpartnumber.Location = new System.Drawing.Point(541, 105); this.pbdnpartnumber.Name = "pbdnpartnumber"; this.pbdnpartnumber.Size = new System.Drawing.Size(29, 18); this.pbdnpartnumber.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.pbdnpartnumber.TabIndex = 53; this.pbdnpartnumber.TabStop = false; // // ldnpartnumber // this.ldnpartnumber.AutoSize = true; this.ldnpartnumber.Location = new System.Drawing.Point(275, 108); this.ldnpartnumber.Name = "ldnpartnumber"; this.ldnpartnumber.Size = new System.Drawing.Size(95, 12); this.ldnpartnumber.TabIndex = 22; this.ldnpartnumber.Text = "Rec Part Number"; // // tfdnpartnumber // this.tfdnpartnumber.Location = new System.Drawing.Point(386, 105); this.tfdnpartnumber.Name = "tfdnpartnumber"; this.tfdnpartnumber.Size = new System.Drawing.Size(151, 21); this.tfdnpartnumber.TabIndex = 23; // // cbSmartScan // this.cbSmartScan.AutoSize = true; this.cbSmartScan.Checked = true; this.cbSmartScan.CheckState = System.Windows.Forms.CheckState.Checked; this.cbSmartScan.Location = new System.Drawing.Point(554, 28); this.cbSmartScan.Name = "cbSmartScan"; this.cbSmartScan.Size = new System.Drawing.Size(84, 16); this.cbSmartScan.TabIndex = 8; this.cbSmartScan.Text = "Smart Scan"; this.cbSmartScan.UseVisualStyleBackColor = true; this.cbSmartScan.CheckedChanged += new System.EventHandler(this.cbSmartScan_CheckedChanged); // // cbAutoPrint // this.cbAutoPrint.AutoSize = true; this.cbAutoPrint.Checked = true; this.cbAutoPrint.CheckState = System.Windows.Forms.CheckState.Checked; this.cbAutoPrint.Location = new System.Drawing.Point(554, 9); this.cbAutoPrint.Name = "cbAutoPrint"; this.cbAutoPrint.Size = new System.Drawing.Size(84, 16); this.cbAutoPrint.TabIndex = 7; this.cbAutoPrint.Text = "Auto Print"; this.cbAutoPrint.UseVisualStyleBackColor = true; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(17, 108); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(29, 12); this.label5.TabIndex = 20; this.label5.Text = "Site"; // // tfsite // this.tfsite.Location = new System.Drawing.Point(116, 108); this.tfsite.Name = "tfsite"; this.tfsite.Size = new System.Drawing.Size(100, 21); this.tfsite.TabIndex = 21; // // pbexpiredate // this.pbexpiredate.Image = global::WHOperation.Properties.Resources.bdelete; this.pbexpiredate.Location = new System.Drawing.Point(492, 150); this.pbexpiredate.Name = "pbexpiredate"; this.pbexpiredate.Size = new System.Drawing.Size(29, 18); this.pbexpiredate.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.pbexpiredate.TabIndex = 47; this.pbexpiredate.TabStop = false; // // pblotnumber // this.pblotnumber.Image = global::WHOperation.Properties.Resources.bdelete; this.pblotnumber.Location = new System.Drawing.Point(523, 174); this.pblotnumber.Name = "pblotnumber"; this.pblotnumber.Size = new System.Drawing.Size(29, 18); this.pblotnumber.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.pblotnumber.TabIndex = 46; this.pblotnumber.TabStop = false; // // pbrecmfgpart // this.pbrecmfgpart.Image = global::WHOperation.Properties.Resources.bdelete; this.pbrecmfgpart.Location = new System.Drawing.Point(541, 129); this.pbrecmfgpart.Name = "pbrecmfgpart"; this.pbrecmfgpart.Size = new System.Drawing.Size(29, 18); this.pbrecmfgpart.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.pbrecmfgpart.TabIndex = 45; this.pbrecmfgpart.TabStop = false; // // pbrecqty // this.pbrecqty.Image = global::WHOperation.Properties.Resources.bdelete; this.pbrecqty.Location = new System.Drawing.Point(224, 175); this.pbrecqty.Name = "pbrecqty"; this.pbrecqty.Size = new System.Drawing.Size(29, 18); this.pbrecqty.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.pbrecqty.TabIndex = 44; this.pbrecqty.TabStop = false; // // pbmfgdate // this.pbmfgdate.Image = global::WHOperation.Properties.Resources.bdelete; this.pbmfgdate.Location = new System.Drawing.Point(224, 150); this.pbmfgdate.Name = "pbmfgdate"; this.pbmfgdate.Size = new System.Drawing.Size(29, 18); this.pbmfgdate.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.pbmfgdate.TabIndex = 43; this.pbmfgdate.TabStop = false; // // pbdatecode // this.pbdatecode.Image = global::WHOperation.Properties.Resources.bdelete; this.pbdatecode.Location = new System.Drawing.Point(224, 129); this.pbdatecode.Name = "pbdatecode"; this.pbdatecode.Size = new System.Drawing.Size(29, 18); this.pbdatecode.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.pbdatecode.TabIndex = 42; this.pbdatecode.TabStop = false; // // tfrecmfgrpart // this.tfrecmfgrpart.Location = new System.Drawing.Point(386, 129); this.tfrecmfgrpart.Name = "tfrecmfgrpart"; this.tfrecmfgrpart.Size = new System.Drawing.Size(151, 21); this.tfrecmfgrpart.TabIndex = 27; // // lrecmfgpart // this.lrecmfgpart.AutoSize = true; this.lrecmfgpart.Location = new System.Drawing.Point(275, 132); this.lrecmfgpart.Name = "lrecmfgpart"; this.lrecmfgpart.Size = new System.Drawing.Size(125, 12); this.lrecmfgpart.TabIndex = 26; this.lrecmfgpart.Text = "(2) Rec.Mfgr Part No"; // // tfexpiredate // this.tfexpiredate.Location = new System.Drawing.Point(386, 150); this.tfexpiredate.MaxLength = 10; this.tfexpiredate.Name = "tfexpiredate"; this.tfexpiredate.Size = new System.Drawing.Size(100, 21); this.tfexpiredate.TabIndex = 31; // // tfmfgdate // this.tfmfgdate.Location = new System.Drawing.Point(116, 150); this.tfmfgdate.MaxLength = 10; this.tfmfgdate.Name = "tfmfgdate"; this.tfmfgdate.Size = new System.Drawing.Size(100, 21); this.tfmfgdate.TabIndex = 29; // // tfnooflabels // this.tfnooflabels.Location = new System.Drawing.Point(439, 7); this.tfnooflabels.MaxLength = 3; this.tfnooflabels.Name = "tfnooflabels"; this.tfnooflabels.Size = new System.Drawing.Size(33, 21); this.tfnooflabels.TabIndex = 5; this.tfnooflabels.Text = "1"; // // tfhdndate // this.tfhdndate.Location = new System.Drawing.Point(116, 81); this.tfhdndate.Name = "tfhdndate"; this.tfhdndate.ReadOnly = true; this.tfhdndate.Size = new System.Drawing.Size(100, 21); this.tfhdndate.TabIndex = 19; // // label21 // this.label21.AutoSize = true; this.label21.Location = new System.Drawing.Point(353, 10); this.label21.Name = "label21"; this.label21.Size = new System.Drawing.Size(77, 12); this.label21.TabIndex = 4; this.label21.Text = "No.Of Labels"; // // lmfgdate // this.lmfgdate.AutoSize = true; this.lmfgdate.Location = new System.Drawing.Point(17, 153); this.lmfgdate.Name = "lmfgdate"; this.lmfgdate.Size = new System.Drawing.Size(77, 12); this.lmfgdate.TabIndex = 28; this.lmfgdate.Text = "(3) Mfg Date"; // // label16 // this.label16.AutoSize = true; this.label16.Location = new System.Drawing.Point(166, 10); this.label16.Name = "label16"; this.label16.Size = new System.Drawing.Size(77, 12); this.label16.TabIndex = 2; this.label16.Text = "Printer Type"; // // label20 // this.label20.AutoSize = true; this.label20.Location = new System.Drawing.Point(17, 84); this.label20.Name = "label20"; this.label20.Size = new System.Drawing.Size(47, 12); this.label20.TabIndex = 18; this.label20.Text = "DN Date"; // // cbprintertype // this.cbprintertype.FormattingEnabled = true; this.cbprintertype.Items.AddRange(new object[] { "TEC 200 dpi", "TEC, 300 dpi"}); this.cbprintertype.Location = new System.Drawing.Point(241, 6); this.cbprintertype.Name = "cbprintertype"; this.cbprintertype.Size = new System.Drawing.Size(101, 20); this.cbprintertype.TabIndex = 3; // // label15 // this.label15.AutoSize = true; this.label15.Location = new System.Drawing.Point(17, 10); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(71, 12); this.label15.TabIndex = 0; this.label15.Text = "Select Port"; // // cbport // this.cbport.FormattingEnabled = true; this.cbport.Items.AddRange(new object[] { "LPT1", "COM1"}); this.cbport.Location = new System.Drawing.Point(91, 6); this.cbport.Name = "cbport"; this.cbport.Size = new System.Drawing.Size(69, 20); this.cbport.TabIndex = 1; // // tfdnqty // this.tfdnqty.Enabled = false; this.tfdnqty.Location = new System.Drawing.Point(116, 200); this.tfdnqty.Name = "tfdnqty"; this.tfdnqty.Size = new System.Drawing.Size(100, 21); this.tfdnqty.TabIndex = 37; // // label13 // this.label13.AutoSize = true; this.label13.Location = new System.Drawing.Point(17, 203); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(41, 12); this.label13.TabIndex = 36; this.label13.Text = "DN Qty"; // // tfcumqty // this.tfcumqty.Enabled = false; this.tfcumqty.Location = new System.Drawing.Point(386, 200); this.tfcumqty.Name = "tfcumqty"; this.tfcumqty.Size = new System.Drawing.Size(100, 21); this.tfcumqty.TabIndex = 39; this.tfcumqty.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.tfcumqty.Visible = false; // // label12 // this.label12.AutoSize = true; this.label12.Location = new System.Drawing.Point(275, 203); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(89, 12); this.label12.TabIndex = 38; this.label12.Text = "Cumulative Qty"; this.label12.Visible = false; // // tfdatecode // this.tfdatecode.Location = new System.Drawing.Point(116, 129); this.tfdatecode.MaxLength = 10; this.tfdatecode.Name = "tfdatecode"; this.tfdatecode.Size = new System.Drawing.Size(100, 21); this.tfdatecode.TabIndex = 25; // // tfmfgpart // this.tfmfgpart.Location = new System.Drawing.Point(386, 81); this.tfmfgpart.Name = "tfmfgpart"; this.tfmfgpart.ReadOnly = true; this.tfmfgpart.Size = new System.Drawing.Size(151, 21); this.tfmfgpart.TabIndex = 17; // // tfrirno // this.tfrirno.Location = new System.Drawing.Point(116, 57); this.tfrirno.Name = "tfrirno"; this.tfrirno.ReadOnly = true; this.tfrirno.Size = new System.Drawing.Size(100, 21); this.tfrirno.TabIndex = 15; // // tfrecqty // this.tfrecqty.Location = new System.Drawing.Point(116, 174); this.tfrecqty.Name = "tfrecqty"; this.tfrecqty.Size = new System.Drawing.Size(100, 21); this.tfrecqty.TabIndex = 33; this.tfrecqty.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // tflotno // this.tflotno.Location = new System.Drawing.Point(386, 174); this.tflotno.Name = "tflotno"; this.tflotno.Size = new System.Drawing.Size(131, 21); this.tflotno.TabIndex = 35; // // tfpartno // this.tfpartno.Location = new System.Drawing.Point(386, 57); this.tfpartno.Name = "tfpartno"; this.tfpartno.ReadOnly = true; this.tfpartno.Size = new System.Drawing.Size(151, 21); this.tfpartno.TabIndex = 13; // // tfvendor // this.tfvendor.Location = new System.Drawing.Point(116, 33); this.tfvendor.Name = "tfvendor"; this.tfvendor.ReadOnly = true; this.tfvendor.Size = new System.Drawing.Size(100, 21); this.tfvendor.TabIndex = 11; // // ldatecode // this.ldatecode.AutoSize = true; this.ldatecode.Location = new System.Drawing.Point(17, 132); this.ldatecode.Name = "ldatecode"; this.ldatecode.Size = new System.Drawing.Size(83, 12); this.ldatecode.TabIndex = 24; this.ldatecode.Text = "(1) Date Code"; // // lexpiredate // this.lexpiredate.AutoSize = true; this.lexpiredate.Location = new System.Drawing.Point(275, 153); this.lexpiredate.Name = "lexpiredate"; this.lexpiredate.Size = new System.Drawing.Size(95, 12); this.lexpiredate.TabIndex = 30; this.lexpiredate.Text = "(4) Expire Date"; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(275, 84); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(95, 12); this.label8.TabIndex = 16; this.label8.Text = "PO QPL Part No."; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(17, 60); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(65, 12); this.label7.TabIndex = 14; this.label7.Text = "RIR Number"; // // lrecqty // this.lrecqty.AutoSize = true; this.lrecqty.Location = new System.Drawing.Point(17, 177); this.lrecqty.Name = "lrecqty"; this.lrecqty.Size = new System.Drawing.Size(77, 12); this.lrecqty.TabIndex = 32; this.lrecqty.Text = "(5) Rec. Qty"; // // llotnumber // this.llotnumber.AutoSize = true; this.llotnumber.Location = new System.Drawing.Point(275, 177); this.llotnumber.Name = "llotnumber"; this.llotnumber.Size = new System.Drawing.Size(89, 12); this.llotnumber.TabIndex = 34; this.llotnumber.Text = "(6) Lot Number"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(275, 60); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(71, 12); this.label4.TabIndex = 12; this.label4.Text = "Part Number"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(17, 37); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(41, 12); this.label3.TabIndex = 10; this.label3.Text = "Vendor"; // // button1 // this.button1.Location = new System.Drawing.Point(481, 6); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(68, 21); this.button1.TabIndex = 6; this.button1.Text = "Print"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // panel4 // this.panel4.Location = new System.Drawing.Point(50, 29); this.panel4.Name = "panel4"; this.panel4.Size = new System.Drawing.Size(506, 190); this.panel4.TabIndex = 1; // // lStatus // this.lStatus.AutoSize = true; this.lStatus.Location = new System.Drawing.Point(815, 0); this.lStatus.Name = "lStatus"; this.lStatus.Size = new System.Drawing.Size(11, 12); this.lStatus.TabIndex = 0; this.lStatus.Text = "."; // // panel1 // this.panel1.Controls.Add(this.label6); this.panel1.Controls.Add(this.tftodndate); this.panel1.Controls.Add(this.bGo); this.panel1.Controls.Add(this.splitContainer1); this.panel1.Controls.Add(this.tabControl1); this.panel1.Controls.Add(this.cbfiltertype); this.panel1.Controls.Add(this.textBox2); this.panel1.Controls.Add(this.groupBox3); this.panel1.Controls.Add(this.label2); this.panel1.Controls.Add(this.cbsystem); this.panel1.Controls.Add(this.label17); this.panel1.Controls.Add(this.tfdndate); this.panel1.Controls.Add(this.label14); this.panel1.Controls.Add(this.label1); this.panel1.Controls.Add(this.tfdnno); this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; this.panel1.Location = new System.Drawing.Point(0, 0); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(1028, 575); this.panel1.TabIndex = 0; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(475, 17); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(11, 12); this.label6.TabIndex = 24; this.label6.Text = "-"; // // tftodndate // this.tftodndate.CustomFormat = "MM/dd/yy"; this.tftodndate.Format = System.Windows.Forms.DateTimePickerFormat.Custom; this.tftodndate.Location = new System.Drawing.Point(491, 13); this.tftodndate.Name = "tftodndate"; this.tftodndate.Size = new System.Drawing.Size(98, 21); this.tftodndate.TabIndex = 23; this.tftodndate.Value = new System.DateTime(2013, 6, 21, 10, 23, 0, 0); // // bGo // this.bGo.Location = new System.Drawing.Point(592, 10); this.bGo.Name = "bGo"; this.bGo.Size = new System.Drawing.Size(40, 21); this.bGo.TabIndex = 22; this.bGo.Text = "Go"; this.bGo.UseVisualStyleBackColor = true; this.bGo.Click += new System.EventHandler(this.bGo_Click); // // splitContainer1 // this.splitContainer1.Location = new System.Drawing.Point(12, 41); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.dgDNNumber); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.tabControl2); this.splitContainer1.Size = new System.Drawing.Size(953, 178); this.splitContainer1.SplitterDistance = 201; this.splitContainer1.TabIndex = 21; // // dgDNNumber // this.dgDNNumber.AllowUserToAddRows = false; this.dgDNNumber.AllowUserToDeleteRows = false; this.dgDNNumber.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dgDNNumber.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.DNNumber}); this.dgDNNumber.Location = new System.Drawing.Point(9, 8); this.dgDNNumber.Name = "dgDNNumber"; this.dgDNNumber.Size = new System.Drawing.Size(180, 167); this.dgDNNumber.TabIndex = 0; // // DNNumber // this.DNNumber.HeaderText = "DNNumber"; this.DNNumber.Name = "DNNumber"; // // tabControl2 // this.tabControl2.Controls.Add(this.tabPage3); this.tabControl2.Controls.Add(this.tabPage4); this.tabControl2.Location = new System.Drawing.Point(3, 3); this.tabControl2.Name = "tabControl2"; this.tabControl2.SelectedIndex = 0; this.tabControl2.Size = new System.Drawing.Size(741, 173); this.tabControl2.TabIndex = 1; // // tabPage3 // this.tabPage3.Controls.Add(this.dataGridView1); this.tabPage3.Location = new System.Drawing.Point(4, 22); this.tabPage3.Name = "tabPage3"; this.tabPage3.Padding = new System.Windows.Forms.Padding(3); this.tabPage3.Size = new System.Drawing.Size(733, 147); this.tabPage3.TabIndex = 0; this.tabPage3.Text = "Pending"; this.tabPage3.UseVisualStyleBackColor = true; // // tabPage4 // this.tabPage4.Controls.Add(this.dgComplete); this.tabPage4.Location = new System.Drawing.Point(4, 22); this.tabPage4.Name = "tabPage4"; this.tabPage4.Padding = new System.Windows.Forms.Padding(3); this.tabPage4.Size = new System.Drawing.Size(733, 147); this.tabPage4.TabIndex = 1; this.tabPage4.Text = "Complete"; this.tabPage4.UseVisualStyleBackColor = true; // // dgComplete // this.dgComplete.AllowUserToAddRows = false; this.dgComplete.AllowUserToDeleteRows = false; this.dgComplete.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dgComplete.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.dataGridViewTextBoxColumn4, this.dataGridViewTextBoxColumn5, this.dataGridViewTextBoxColumn6, this.dataGridViewTextBoxColumn7, this.dataGridViewTextBoxColumn8, this.dataGridViewTextBoxColumn9, this.dataGridViewTextBoxColumn20}); this.dgComplete.Dock = System.Windows.Forms.DockStyle.Fill; this.dgComplete.Location = new System.Drawing.Point(3, 3); this.dgComplete.MultiSelect = false; this.dgComplete.Name = "dgComplete"; this.dgComplete.ReadOnly = true; this.dgComplete.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dgComplete.Size = new System.Drawing.Size(727, 141); this.dgComplete.TabIndex = 1; // // dataGridViewTextBoxColumn4 // this.dataGridViewTextBoxColumn4.HeaderText = "PartNumber"; this.dataGridViewTextBoxColumn4.Name = "dataGridViewTextBoxColumn4"; this.dataGridViewTextBoxColumn4.ReadOnly = true; this.dataGridViewTextBoxColumn4.Width = 130; // // dataGridViewTextBoxColumn5 // this.dataGridViewTextBoxColumn5.HeaderText = "PONumber"; this.dataGridViewTextBoxColumn5.Name = "dataGridViewTextBoxColumn5"; this.dataGridViewTextBoxColumn5.ReadOnly = true; this.dataGridViewTextBoxColumn5.Width = 65; // // dataGridViewTextBoxColumn6 // this.dataGridViewTextBoxColumn6.HeaderText = "PO QPL-Part No"; this.dataGridViewTextBoxColumn6.Name = "dataGridViewTextBoxColumn6"; this.dataGridViewTextBoxColumn6.ReadOnly = true; this.dataGridViewTextBoxColumn6.Width = 130; // // dataGridViewTextBoxColumn7 // this.dataGridViewTextBoxColumn7.HeaderText = "ASN MFG P/N"; this.dataGridViewTextBoxColumn7.Name = "dataGridViewTextBoxColumn7"; this.dataGridViewTextBoxColumn7.ReadOnly = true; this.dataGridViewTextBoxColumn7.Width = 110; // // dataGridViewTextBoxColumn8 // this.dataGridViewTextBoxColumn8.HeaderText = "RIR-No"; this.dataGridViewTextBoxColumn8.Name = "dataGridViewTextBoxColumn8"; this.dataGridViewTextBoxColumn8.ReadOnly = true; // // dataGridViewTextBoxColumn9 // this.dataGridViewTextBoxColumn9.HeaderText = "DNQty"; this.dataGridViewTextBoxColumn9.Name = "dataGridViewTextBoxColumn9"; this.dataGridViewTextBoxColumn9.ReadOnly = true; this.dataGridViewTextBoxColumn9.Width = 45; // // dataGridViewTextBoxColumn20 // this.dataGridViewTextBoxColumn20.HeaderText = "PrintedQty"; this.dataGridViewTextBoxColumn20.Name = "dataGridViewTextBoxColumn20"; this.dataGridViewTextBoxColumn20.ReadOnly = true; this.dataGridViewTextBoxColumn20.Width = 80; // // contextMenuStrip1 // this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.clearToolStripMenuItem, this.reStartToolStripMenuItem}); this.contextMenuStrip1.Name = "contextMenuStrip1"; this.contextMenuStrip1.Size = new System.Drawing.Size(119, 48); // // clearToolStripMenuItem // this.clearToolStripMenuItem.Name = "clearToolStripMenuItem"; this.clearToolStripMenuItem.Size = new System.Drawing.Size(118, 22); this.clearToolStripMenuItem.Text = "Clear"; this.clearToolStripMenuItem.Click += new System.EventHandler(this.clearToolStripMenuItem_Click); // // reStartToolStripMenuItem // this.reStartToolStripMenuItem.Name = "reStartToolStripMenuItem"; this.reStartToolStripMenuItem.Size = new System.Drawing.Size(118, 22); this.reStartToolStripMenuItem.Text = "ReStart"; this.reStartToolStripMenuItem.Click += new System.EventHandler(this.reStartToolStripMenuItem_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1028, 575); this.Controls.Add(this.panel1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "PIMS Data Capture"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing_1); this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.tabControl1.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.groupBox4.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataGridView3)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pb1)).EndInit(); this.tabPage2.ResumeLayout(false); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.splitContainer2.Panel1.ResumeLayout(false); this.splitContainer2.Panel2.ResumeLayout(false); this.splitContainer2.Panel2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).EndInit(); this.splitContainer2.ResumeLayout(false); this.tab3_QRBar.ResumeLayout(false); this.tabPage5_OldQRBar.ResumeLayout(false); this.tabPage5_OldQRBar.PerformLayout(); this.tabPage6_NewQRBar.ResumeLayout(false); this.tabPage6_NewQRBar.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pbdnpartnumber)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pbexpiredate)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pblotnumber)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pbrecmfgpart)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pbrecqty)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pbmfgdate)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pbdatecode)).EndInit(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); this.splitContainer1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dgDNNumber)).EndInit(); this.tabControl2.ResumeLayout(false); this.tabPage3.ResumeLayout(false); this.tabPage4.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dgComplete)).EndInit(); this.contextMenuStrip1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.TextBox tfdnno; private System.Windows.Forms.Label label1; private System.Windows.Forms.DataGridView dataGridView1; private System.Windows.Forms.Label label14; private System.Windows.Forms.DateTimePicker tfdndate; private System.Windows.Forms.Label label17; private System.Windows.Forms.TextBox cbsystem; private System.Windows.Forms.Label label2; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.ComboBox cbfiltertype; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.GroupBox groupBox4; private System.Windows.Forms.DataGridView dataGridView3; private System.Windows.Forms.DataGridViewTextBoxColumn TempID; private System.Windows.Forms.PictureBox pb1; private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.SplitContainer splitContainer2; private System.Windows.Forms.Button bStop; private System.Windows.Forms.Label label22; private System.Windows.Forms.Button bStart; public System.Windows.Forms.TextBox tfscanarea; private System.Windows.Forms.CheckBox cbSmartScan; private System.Windows.Forms.CheckBox cbAutoPrint; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox tfsite; private System.Windows.Forms.PictureBox pbexpiredate; private System.Windows.Forms.PictureBox pblotnumber; private System.Windows.Forms.PictureBox pbrecmfgpart; private System.Windows.Forms.PictureBox pbrecqty; private System.Windows.Forms.PictureBox pbmfgdate; private System.Windows.Forms.PictureBox pbdatecode; private System.Windows.Forms.TextBox tfrecmfgrpart; private System.Windows.Forms.Label lrecmfgpart; private System.Windows.Forms.TextBox tfexpiredate; private System.Windows.Forms.TextBox tfmfgdate; private System.Windows.Forms.TextBox tfnooflabels; private System.Windows.Forms.TextBox tfhdndate; private System.Windows.Forms.Label label21; private System.Windows.Forms.Label lmfgdate; private System.Windows.Forms.Label label16; private System.Windows.Forms.Label label20; private System.Windows.Forms.ComboBox cbprintertype; private System.Windows.Forms.Label label15; private System.Windows.Forms.ComboBox cbport; private System.Windows.Forms.TextBox tfdnqty; private System.Windows.Forms.Label label13; private System.Windows.Forms.TextBox tfcumqty; private System.Windows.Forms.Label label12; private System.Windows.Forms.TextBox tfdatecode; private System.Windows.Forms.TextBox tfmfgpart; private System.Windows.Forms.TextBox tfrirno; private System.Windows.Forms.TextBox tfrecqty; private System.Windows.Forms.TextBox tflotno; private System.Windows.Forms.TextBox tfpartno; private System.Windows.Forms.TextBox tfvendor; private System.Windows.Forms.Label ldatecode; private System.Windows.Forms.Label lexpiredate; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label lrecqty; private System.Windows.Forms.Label llotnumber; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button button1; private System.Windows.Forms.Label lStatus; private System.Windows.Forms.Panel panel4; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.SplitContainer splitContainer1; private System.Windows.Forms.DataGridView dgDNNumber; private System.Windows.Forms.DataGridViewTextBoxColumn DNNumber; private System.Windows.Forms.Button bGo; private System.Windows.Forms.Button bEnableScan; private System.Windows.Forms.Button bDisableScan; private System.Windows.Forms.CheckBox cbprintcartonlabel; private System.Windows.Forms.DateTimePicker tftodndate; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label ldnpartnumber; private System.Windows.Forms.TextBox tfdnpartnumber; private System.Windows.Forms.PictureBox pbdnpartnumber; private System.Windows.Forms.Label lMLotNumber; private System.Windows.Forms.Label lMDateCode; private System.Windows.Forms.Label lMExpireDate; private System.Windows.Forms.Label lMRecMfgPart; private System.Windows.Forms.TabControl tabControl2; private System.Windows.Forms.TabPage tabPage3; private System.Windows.Forms.TabPage tabPage4; private System.Windows.Forms.DataGridView dgComplete; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn4; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn5; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn6; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn7; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn8; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn9; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn20; private System.Windows.Forms.Label lMRecPartNumber; private System.Windows.Forms.Label lMRecQty; private System.Windows.Forms.DataGridViewTextBoxColumn DNNo; private System.Windows.Forms.DataGridViewTextBoxColumn POLine; private System.Windows.Forms.DataGridViewTextBoxColumn Vendor; private System.Windows.Forms.DataGridViewTextBoxColumn PartNumber; private System.Windows.Forms.DataGridViewTextBoxColumn MFGPartNo; private System.Windows.Forms.DataGridViewTextBoxColumn RIRNo; private System.Windows.Forms.DataGridViewTextBoxColumn PONumber; private System.Windows.Forms.DataGridViewTextBoxColumn ASNMFGPN; private System.Windows.Forms.DataGridViewTextBoxColumn DNQty; private System.Windows.Forms.DataGridViewTextBoxColumn DNDate; private System.Windows.Forms.DataGridViewTextBoxColumn DNSite; private System.Windows.Forms.DataGridViewTextBoxColumn t_urg; private System.Windows.Forms.DataGridViewTextBoxColumn t_loc; private System.Windows.Forms.DataGridViewTextBoxColumn t_msd; private System.Windows.Forms.DataGridViewTextBoxColumn t_cust_part; private System.Windows.Forms.DataGridViewTextBoxColumn t_shelf_life; private System.Windows.Forms.DataGridViewTextBoxColumn t_wt; private System.Windows.Forms.DataGridViewTextBoxColumn t_wt_ind; private System.Windows.Forms.DataGridViewTextBoxColumn t_conn; private System.Windows.Forms.DataGridViewTextBoxColumn PrintedQty; private System.Windows.Forms.DataGridViewTextBoxColumn RowID; private System.Windows.Forms.TextBox tfnoofcartons; private System.Windows.Forms.Label label10; private System.Windows.Forms.CheckBox cbtrimmfgpart; private System.Windows.Forms.TabControl tab3_QRBar; private System.Windows.Forms.TabPage tabPage5_OldQRBar; private System.Windows.Forms.TabPage tabPage6_NewQRBar; private System.Windows.Forms.Button btn6_StopQR; private System.Windows.Forms.Button btn5_startQR; private System.Windows.Forms.Label label9; private System.Windows.Forms.ListBox txt0ListKeyMsg; private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; private System.Windows.Forms.ToolStripMenuItem clearToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem reStartToolStripMenuItem; } }
//----------------------------------------------------------------------- // <copyright file="ActorPublisher.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.Reflection; using System.Runtime.Serialization; using Akka.Actor; using Akka.Annotations; using Akka.Event; using Akka.Pattern; using Akka.Util; using Reactive.Streams; namespace Akka.Streams.Implementation { /// <summary> /// TBD /// </summary> [Serializable] internal sealed class SubscribePending { /// <summary> /// TBD /// </summary> public static readonly SubscribePending Instance = new SubscribePending(); private SubscribePending() { } } /// <summary> /// TBD /// </summary> [Serializable] internal sealed class RequestMore : IDeadLetterSuppression { /// <summary> /// TBD /// </summary> public readonly IActorSubscription Subscription; /// <summary> /// TBD /// </summary> public readonly long Demand; /// <summary> /// TBD /// </summary> /// <param name="subscription">TBD</param> /// <param name="demand">TBD</param> public RequestMore(IActorSubscription subscription, long demand) { Subscription = subscription; Demand = demand; } } /// <summary> /// TBD /// </summary> [Serializable] internal sealed class Cancel : IDeadLetterSuppression { /// <summary> /// TBD /// </summary> public readonly IActorSubscription Subscription; /// <summary> /// TBD /// </summary> /// <param name="subscription">TBD</param> public Cancel(IActorSubscription subscription) { Subscription = subscription; } } /// <summary> /// TBD /// </summary> [Serializable] internal sealed class ExposedPublisher : IDeadLetterSuppression { /// <summary> /// TBD /// </summary> public readonly IActorPublisher Publisher; /// <summary> /// TBD /// </summary> /// <param name="publisher">TBD</param> public ExposedPublisher(IActorPublisher publisher) { Publisher = publisher; } } /// <summary> /// TBD /// </summary> [Serializable] public class NormalShutdownException : IllegalStateException { /// <summary> /// Initializes a new instance of the <see cref="NormalShutdownException"/> class. /// </summary> /// <param name="message">The message that describes the error.</param> public NormalShutdownException(string message) : base(message) { } #if SERIALIZATION /// <summary> /// Initializes a new instance of the <see cref="NormalShutdownException"/> class. /// </summary> /// <param name="info">The <see cref="SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="StreamingContext" /> that contains contextual information about the source or destination.</param> protected NormalShutdownException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif } /// <summary> /// TBD /// </summary> public interface IActorPublisher : IUntypedPublisher { /// <summary> /// TBD /// </summary> /// <param name="reason">TBD</param> void Shutdown(Exception reason); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> IEnumerable<IUntypedSubscriber> TakePendingSubscribers(); } /// <summary> /// TBD /// </summary> public static class ActorPublisher { /// <summary> /// TBD /// </summary> public const string NormalShutdownReasonMessage = "Cannot subscribe to shut-down Publisher"; /// <summary> /// TBD /// </summary> public static readonly NormalShutdownException NormalShutdownReason = new NormalShutdownException(NormalShutdownReasonMessage); } /// <summary> /// INTERNAL API /// /// When you instantiate this class, or its subclasses, you MUST send an ExposedPublisher message to the wrapped /// ActorRef! If you don't need to subclass, prefer the apply() method on the companion object which takes care of this. /// </summary> /// <typeparam name="TOut">TBD</typeparam> [InternalApi] public class ActorPublisher<TOut> : IActorPublisher, IPublisher<TOut> { /// <summary> /// TBD /// </summary> protected readonly IActorRef Impl; // The subscriber of an subscription attempt is first placed in this list of pending subscribers. // The actor will call takePendingSubscribers to remove it from the list when it has received the // SubscribePending message. The AtomicReference is set to null by the shutdown method, which is // called by the actor from postStop. Pending (unregistered) subscription attempts are denied by // the shutdown method. Subscription attempts after shutdown can be denied immediately. private readonly AtomicReference<ImmutableList<ISubscriber<TOut>>> _pendingSubscribers = new AtomicReference<ImmutableList<ISubscriber<TOut>>>(ImmutableList<ISubscriber<TOut>>.Empty); private volatile Exception _shutdownReason; /// <summary> /// TBD /// </summary> protected virtual object WakeUpMessage => SubscribePending.Instance; /// <summary> /// TBD /// </summary> /// <param name="impl">TBD</param> public ActorPublisher(IActorRef impl) { Impl = impl; } /// <summary> /// TBD /// </summary> /// <param name="subscriber">TBD</param> /// <exception cref="ArgumentNullException">TBD</exception> public void Subscribe(ISubscriber<TOut> subscriber) { if (subscriber == null) throw new ArgumentNullException(nameof(subscriber)); while (true) { var current = _pendingSubscribers.Value; if (current == null) { ReportSubscribeFailure(subscriber); break; } if (_pendingSubscribers.CompareAndSet(current, current.Add(subscriber))) { Impl.Tell(WakeUpMessage); break; } } } void IUntypedPublisher.Subscribe(IUntypedSubscriber subscriber) => Subscribe(UntypedSubscriber.ToTyped<TOut>(subscriber)); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public IEnumerable<ISubscriber<TOut>> TakePendingSubscribers() { var pending = _pendingSubscribers.GetAndSet(ImmutableList<ISubscriber<TOut>>.Empty); return pending ?? ImmutableList<ISubscriber<TOut>>.Empty; } IEnumerable<IUntypedSubscriber> IActorPublisher.TakePendingSubscribers() => TakePendingSubscribers().Select(UntypedSubscriber.FromTyped); /// <summary> /// TBD /// </summary> /// <param name="reason">TBD</param> public void Shutdown(Exception reason) { _shutdownReason = reason; var pending = _pendingSubscribers.GetAndSet(null); if (pending != null) { foreach (var subscriber in pending.Reverse()) ReportSubscribeFailure(subscriber); } } private void ReportSubscribeFailure(ISubscriber<TOut> subscriber) { try { if (_shutdownReason == null) { ReactiveStreamsCompliance.TryOnSubscribe(subscriber, CancelledSubscription.Instance); ReactiveStreamsCompliance.TryOnComplete(subscriber); } else if (_shutdownReason is ISpecViolation) { // ok, not allowed to call OnError } else { ReactiveStreamsCompliance.TryOnSubscribe(subscriber, CancelledSubscription.Instance); ReactiveStreamsCompliance.TryOnError(subscriber, _shutdownReason); } } catch (Exception exception) { if (!(exception is ISpecViolation)) throw; } } } /// <summary> /// TBD /// </summary> public interface IActorSubscription : ISubscription { } /// <summary> /// TBD /// </summary> public static class ActorSubscription { /// <summary> /// TBD /// </summary> /// <param name="implementor">TBD</param> /// <param name="subscriber">TBD</param> /// <returns>TBD</returns> internal static IActorSubscription Create(IActorRef implementor, IUntypedSubscriber subscriber) { var subscribedType = subscriber.GetType().GetGenericArguments().First(); // assumes type is UntypedSubscriberWrapper var subscriptionType = typeof(ActorSubscription<>).MakeGenericType(subscribedType); return (IActorSubscription) Activator.CreateInstance(subscriptionType, implementor, UntypedSubscriber.ToTyped(subscriber)); } /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> /// <param name="implementor">TBD</param> /// <param name="subscriber">TBD</param> /// <returns>TBD</returns> public static IActorSubscription Create<T>(IActorRef implementor, ISubscriber<T> subscriber) => new ActorSubscription<T>(implementor, subscriber); } /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> public class ActorSubscription<T> : IActorSubscription { /// <summary> /// TBD /// </summary> public readonly IActorRef Implementor; /// <summary> /// TBD /// </summary> public readonly ISubscriber<T> Subscriber; /// <summary> /// TBD /// </summary> /// <param name="implementor">TBD</param> /// <param name="subscriber">TBD</param> public ActorSubscription(IActorRef implementor, ISubscriber<T> subscriber) { Implementor = implementor; Subscriber = subscriber; } /// <summary> /// TBD /// </summary> /// <param name="n">TBD</param> public void Request(long n) => Implementor.Tell(new RequestMore(this, n)); /// <summary> /// TBD /// </summary> public void Cancel() => Implementor.Tell(new Cancel(this)); } /// <summary> /// TBD /// </summary> /// <typeparam name="TIn">TBD</typeparam> public class ActorSubscriptionWithCursor<TIn> : ActorSubscription<TIn>, ISubscriptionWithCursor<TIn> { /// <summary> /// TBD /// </summary> /// <param name="implementor">TBD</param> /// <param name="subscriber">TBD</param> public ActorSubscriptionWithCursor(IActorRef implementor, ISubscriber<TIn> subscriber) : base(implementor, subscriber) { IsActive = true; TotalDemand = 0; Cursor = 0; } ISubscriber<TIn> ISubscriptionWithCursor<TIn>.Subscriber => Subscriber; /// <summary> /// TBD /// </summary> /// <param name="element">TBD</param> public void Dispatch(object element) => ReactiveStreamsCompliance.TryOnNext(Subscriber, (TIn)element); bool ISubscriptionWithCursor<TIn>.IsActive { get { return IsActive; } set { IsActive = value; } } /// <summary> /// TBD /// </summary> public bool IsActive { get; private set; } /// <summary> /// TBD /// </summary> public int Cursor { get; private set; } long ISubscriptionWithCursor<TIn>.TotalDemand { get { return TotalDemand; } set { TotalDemand = value; } } /// <summary> /// TBD /// </summary> public long TotalDemand { get; private set; } /// <summary> /// TBD /// </summary> /// <param name="element">TBD</param> public void Dispatch(TIn element) => ReactiveStreamsCompliance.TryOnNext(Subscriber, element); int ICursor.Cursor { get { return Cursor; } set { Cursor = value; } } } }
namespace StockSharp.Algo.Import { using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; using Ecng.Common; using Ecng.ComponentModel; using Ecng.Serialization; using StockSharp.Algo; using StockSharp.Algo.Storages; using StockSharp.Localization; using DataType = StockSharp.Messages.DataType; /// <summary> /// Settings of import. /// </summary> [DisplayNameLoc(LocalizedStrings.Str2842Key)] [TypeConverter(typeof(ExpandableObjectConverter))] public class ImportSettings : NotifiableObject, IPersistable { /// <summary> /// Initializes a new instance of the <see cref="ImportSettings"/>. /// </summary> public ImportSettings() { DataType = DataType.TimeFrame(TimeSpan.FromMinutes(1)); Directory = string.Empty; IncludeSubDirectories = false; FileMask = "*.csv"; SkipFromHeader = 0; ColumnSeparator = ","; TimeZone = TimeZoneInfo.Utc; UpdateDuplicateSecurities = true; IgnoreNonIdSecurities = true; } private DataType _dataType; /// <summary> /// Data type info. /// </summary> [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.DataTypeKey, Description = LocalizedStrings.DataTypeKey, GroupName = LocalizedStrings.CommonKey, Order = 0)] public DataType DataType { get => _dataType; set { if (_dataType == value) return; _dataType = value ?? throw new ArgumentNullException(nameof(value)); AllFields = FieldMappingRegistry.CreateFields(value); SelectedFields = AllFields.Where(f => f.IsRequired).Select((f, i) => { f.Order = i; return f.GetOrClone(); }).ToArray(); NotifyChanged(); } } private string _fileName; /// <summary> /// Full path to CSV file. /// </summary> [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str2002Key, Description = LocalizedStrings.Str2843Key, GroupName = LocalizedStrings.CommonKey, Order = 1)] [Editor(typeof(IFileBrowserEditor), typeof(IFileBrowserEditor))] public string FileName { get => _fileName; set { _fileName = value?.Trim(); NotifyChanged(); } } private string _directory; /// <summary> /// Data directory. /// </summary> [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str2237Key, Description = LocalizedStrings.Str2237Key + LocalizedStrings.Dot, GroupName = LocalizedStrings.CommonKey, Order = 2)] [Editor(typeof(IFolderBrowserEditor), typeof(IFolderBrowserEditor))] public string Directory { get => _directory; set { _directory = value?.Trim(); NotifyChanged(); } } private string _fileMask = "*"; /// <summary> /// File mask that uses for scanning in directory. For example, candles_*.csv. /// </summary> [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.FileMaskKey, Description = LocalizedStrings.FileMaskDescriptionKey, GroupName = LocalizedStrings.CommonKey, Order = 3)] public string FileMask { get => _fileMask; set { if (value.IsEmpty()) throw new ArgumentNullException(nameof(value)); _fileMask = value; NotifyChanged(); } } private bool _includeSubDirectories; /// <summary> /// Include subdirectories. /// </summary> [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.SubDirectoriesKey, Description = LocalizedStrings.SubDirectoriesIncludeKey, GroupName = LocalizedStrings.CommonKey, Order = 4)] public bool IncludeSubDirectories { get => _includeSubDirectories; set { _includeSubDirectories = value; NotifyChanged(); } } private string _columnSeparator = ","; /// <summary> /// Column separator. Tabulation is denoted by TAB. /// </summary> [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str2844Key, Description = LocalizedStrings.Str2845Key, GroupName = LocalizedStrings.CommonKey, Order = 5)] public string ColumnSeparator { get => _columnSeparator; set { if (value.IsEmpty()) throw new ArgumentNullException(nameof(value)); _columnSeparator = value; NotifyChanged(); } } private int _skipFromHeader; /// <summary> /// Number of lines to be skipped from the beginning of the file (if they contain meta information). /// </summary> [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str2846Key, Description = LocalizedStrings.Str2847Key, GroupName = LocalizedStrings.CommonKey, Order = 6)] public int SkipFromHeader { get => _skipFromHeader; set { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), value, LocalizedStrings.Str1219); _skipFromHeader = value; NotifyChanged(); } } private TimeZoneInfo _timeZone; /// <summary> /// Time zone. /// </summary> [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.TimeZoneKey, Description = LocalizedStrings.TimeZoneKey + LocalizedStrings.Dot, GroupName = LocalizedStrings.CommonKey, Order = 7)] public TimeZoneInfo TimeZone { get => _timeZone; set { _timeZone = value ?? throw new ArgumentNullException(nameof(value)); NotifyChanged(); } } private TimeSpan _interval; /// <summary> /// Interval. /// </summary> [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str175Key, Description = LocalizedStrings.IntervalDataUpdatesKey, GroupName = LocalizedStrings.CommonKey, Order = 8)] [TimeSpanEditor(Mask = TimeSpanEditorMask.Days | TimeSpanEditorMask.Hours | TimeSpanEditorMask.Minutes)] public TimeSpan Interval { get => _interval; set { if (value < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(value), value, LocalizedStrings.Str940); _interval = value; NotifyChanged(); } } private IExtendedInfoStorageItem _extendedStorage; /// <summary> /// Extended information. /// </summary> [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.ExtendedInfoKey, Description = LocalizedStrings.ExtendedInfoImportKey, GroupName = LocalizedStrings.SecuritiesKey, Order = 40)] public IExtendedInfoStorageItem ExtendedStorage { get => _extendedStorage; set { if (_extendedStorage == value) return; SelectedFields = SelectedFields.Except(ExtendedFields).ToArray(); AllFields = AllFields.Except(ExtendedFields).ToArray(); _extendedStorage = value; if (_extendedStorage != null) AllFields = AllFields.Concat(FieldMappingRegistry.CreateExtendedFields(_extendedStorage)).ToArray(); NotifyChanged(); } } private bool _updateDuplicateSecurities; /// <summary> /// Update duplicate securities if they already exists. /// </summary> [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.DuplicatesKey, Description = LocalizedStrings.UpdateDuplicateSecuritiesKey, GroupName = LocalizedStrings.SecuritiesKey, Order = 40)] public bool UpdateDuplicateSecurities { get => _updateDuplicateSecurities; set { _updateDuplicateSecurities = value; NotifyChanged(); } } private bool _ignoreNonIdSecurities; /// <summary> /// Ignore securities without identifiers. /// </summary> [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.IgnoreNonIdSecuritiesKey, Description = LocalizedStrings.IgnoreNonIdSecuritiesDescKey, GroupName = LocalizedStrings.SecuritiesKey, Order = 41)] public bool IgnoreNonIdSecurities { get => _ignoreNonIdSecurities; set { _ignoreNonIdSecurities = value; NotifyChanged(); } } //private void InitExtendedFields() //{ // UnSelectedFields.RemoveRange(UnSelectedFields.Where(f => f.IsExtended).ToArray()); // SelectedFields.RemoveRange(SelectedFields.Where(f => f.IsExtended).ToArray()); // UnSelectedFields.AddRange(Settings.ExtendedFields); //} /// <summary> /// All fields. /// </summary> [Browsable(false)] public IEnumerable<FieldMapping> AllFields { get; private set; } /// <summary> /// Extended fields. /// </summary> [Browsable(false)] public IEnumerable<FieldMapping> ExtendedFields => AllFields.Where(f => f.IsExtended); private IEnumerable<FieldMapping> _selectedFields = Enumerable.Empty<FieldMapping>(); /// <summary> /// Selected fields. /// </summary> [Browsable(false)] public IEnumerable<FieldMapping> SelectedFields { get => _selectedFields; set { _selectedFields = value ?? throw new ArgumentNullException(nameof(value)); NotifyChanged(); } } /// <summary> /// Find files for importing. /// </summary> /// <returns>File list.</returns> public IEnumerable<string> GetFiles() { return !FileName.IsEmpty() ? new[] { FileName } : System.IO.Directory.GetFiles(Directory, FileMask, IncludeSubDirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); } /// <summary> /// Load settings. /// </summary> /// <param name="storage">Settings storage.</param> public void Load(SettingsStorage storage) { DataType = storage.GetValue<SettingsStorage>(nameof(DataType)).Load<DataType>(); var extendedStorage = storage.GetValue<string>(nameof(ExtendedStorage)); if (!extendedStorage.IsEmpty()) ExtendedStorage = ServicesRegistry.ExtendedInfoStorage.Get(extendedStorage); SelectedFields = LoadSelectedFields(storage.GetValue<SettingsStorage[]>("Fields") ?? storage.GetValue<SettingsStorage[]>(nameof(SelectedFields))); FileName = storage.GetValue<string>(nameof(FileName)); Directory = storage.GetValue(nameof(Directory), Directory); FileMask = storage.GetValue(nameof(FileMask), FileMask); IncludeSubDirectories = storage.GetValue(nameof(IncludeSubDirectories), IncludeSubDirectories); ColumnSeparator = storage.GetValue(nameof(ColumnSeparator), ColumnSeparator); SkipFromHeader = storage.GetValue(nameof(SkipFromHeader), SkipFromHeader); TimeZone = storage.GetValue(nameof(TimeZone), TimeZone); UpdateDuplicateSecurities = storage.GetValue(nameof(UpdateDuplicateSecurities), UpdateDuplicateSecurities); IgnoreNonIdSecurities = storage.GetValue(nameof(IgnoreNonIdSecurities), IgnoreNonIdSecurities); Interval = storage.GetValue(nameof(Interval), Interval); } /// <summary> /// Save settings. /// </summary> /// <param name="storage">Settings storage.</param> public void Save(SettingsStorage storage) { storage.SetValue(nameof(DataType), DataType.Save()); storage.SetValue(nameof(ExtendedStorage), ExtendedStorage?.StorageName); storage.SetValue(nameof(SelectedFields), SelectedFields.Select(f => f.Save()).ToArray()); storage.SetValue(nameof(FileName), FileName); storage.SetValue(nameof(Directory), Directory); storage.SetValue(nameof(FileMask), FileMask); storage.SetValue(nameof(IncludeSubDirectories), IncludeSubDirectories); storage.SetValue(nameof(ColumnSeparator), ColumnSeparator); storage.SetValue(nameof(SkipFromHeader), SkipFromHeader); storage.SetValue(nameof(TimeZone), TimeZone); storage.SetValue(nameof(UpdateDuplicateSecurities), UpdateDuplicateSecurities); storage.SetValue(nameof(IgnoreNonIdSecurities), IgnoreNonIdSecurities); storage.SetValue(nameof(Interval), Interval); } private IEnumerable<FieldMapping> LoadSelectedFields(IEnumerable<SettingsStorage> storages) { var selectedFields = new List<FieldMapping>(); foreach (var fieldSettings in storages) { var fieldName = fieldSettings.GetValue<string>(nameof(FieldMapping.Name)); var field = AllFields.FirstOrDefault(f => f.Name.EqualsIgnoreCase(fieldName)); if (field == null) continue; field = field.GetOrClone(); field.Load(fieldSettings); selectedFields.Add(field); } return selectedFields; } /// <inheritdoc /> public override string ToString() { var msgType = DataType.MessageType; if (DataType == DataType.Securities) return LocalizedStrings.Securities; else if (DataType == DataType.Level1) return LocalizedStrings.Level1; else if (DataType == DataType.MarketDepth) return LocalizedStrings.MarketDepths; else if (DataType == DataType.PositionChanges) return LocalizedStrings.Str972; else if (DataType.IsCandles) return LocalizedStrings.Candles; else if (DataType == DataType.OrderLog) return LocalizedStrings.OrderLog; else if (DataType == DataType.Ticks) return LocalizedStrings.Ticks; else if (DataType == DataType.Transactions) return LocalizedStrings.Transactions; else throw new ArgumentOutOfRangeException(nameof(DataType.MessageType), msgType, LocalizedStrings.Str1219); } /// <summary> /// Fill <see cref="CsvImporter"/>. /// </summary> /// <param name="parser">Messages parser from text file in CSV format.</param> public void FillParser(CsvParser parser) { if (parser == null) throw new ArgumentNullException(nameof(parser)); parser.ColumnSeparator = ColumnSeparator; parser.SkipFromHeader = SkipFromHeader; parser.TimeZone = TimeZone; parser.ExtendedInfoStorageItem = ExtendedStorage; parser.IgnoreNonIdSecurities = IgnoreNonIdSecurities; } /// <summary> /// Fill <see cref="CsvImporter"/>. /// </summary> /// <param name="importer">Messages importer from text file in CSV format into storage.</param> public void FillImporter(CsvImporter importer) { FillParser(importer); importer.UpdateDuplicateSecurities = UpdateDuplicateSecurities; } } }
// Amplify Shader Editor - Visual Shader Editing Tool // Copyright (c) Amplify Creations, Lda <info@amplify.pt> using UnityEngine; using UnityEditor; using System; namespace AmplifyShaderEditor { [Serializable] [NodeAttributes( "Matrix4X4", "Constants", "Matrix4X4 property" )] public sealed class Matrix4X4Node : PropertyNode { [SerializeField] private Matrix4x4 m_defaultValue = Matrix4x4.identity; [SerializeField] private Matrix4x4 m_materialValue = Matrix4x4.identity; public Matrix4X4Node() : base() { } public Matrix4X4Node( int uniqueId, float x, float y, float width, float height ) : base( uniqueId, x, y, width, height ) { } protected override void CommonInit( int uniqueId ) { base.CommonInit( uniqueId ); AddOutputPort( WirePortDataType.FLOAT4x4, Constants.EmptyPortValue ); m_insideSize.Set( Constants.FLOAT_DRAW_WIDTH_FIELD_SIZE * 4 + Constants.FLOAT_WIDTH_SPACING * 3, Constants.FLOAT_DRAW_HEIGHT_FIELD_SIZE * 4 + Constants.FLOAT_WIDTH_SPACING * 3 + Constants.OUTSIDE_WIRE_MARGIN ); m_defaultValue = new Matrix4x4(); m_materialValue = new Matrix4x4(); m_drawPreview = false; m_precisionString = UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, m_outputPorts[ 0 ].DataType ); } public override void CopyDefaultsToMaterial() { m_materialValue = m_defaultValue; } public override void DrawSubProperties() { EditorGUILayout.LabelField( Constants.DefaultValueLabel ); for ( int row = 0; row < 4; row++ ) { EditorGUILayout.BeginHorizontal(); for ( int column = 0; column < 4; column++ ) { m_defaultValue[ row, column ] = EditorGUILayoutFloatField( string.Empty, m_defaultValue[ row, column ], GUILayout.MaxWidth( 55 ) ); } EditorGUILayout.EndHorizontal(); } } public override void DrawMaterialProperties() { if ( m_materialMode ) EditorGUI.BeginChangeCheck(); EditorGUILayout.LabelField( Constants.MaterialValueLabel ); for ( int row = 0; row < 4; row++ ) { EditorGUILayout.BeginHorizontal(); for ( int column = 0; column < 4; column++ ) { m_materialValue[ row, column ] = EditorGUILayoutFloatField( string.Empty, m_materialValue[ row, column ], GUILayout.MaxWidth( 55 ) ); } EditorGUILayout.EndHorizontal(); } if ( m_materialMode && EditorGUI.EndChangeCheck() ) m_requireMaterialUpdate = true; } public override void Draw( DrawInfo drawInfo ) { base.Draw( drawInfo ); if ( m_isVisible ) { m_propertyDrawPos.position = m_remainingBox.position; bool currMode = m_materialMode && m_currentParameterType != PropertyType.Constant; Matrix4x4 value = currMode ? m_materialValue : m_defaultValue; m_propertyDrawPos.width = drawInfo.InvertedZoom * Constants.FLOAT_DRAW_WIDTH_FIELD_SIZE; m_propertyDrawPos.height = drawInfo.InvertedZoom * Constants.FLOAT_DRAW_HEIGHT_FIELD_SIZE; EditorGUI.BeginChangeCheck(); for ( int row = 0; row < 4; row++ ) { for ( int column = 0; column < 4; column++ ) { m_propertyDrawPos.position = m_remainingBox.position + Vector2.Scale( m_propertyDrawPos.size, new Vector2( column, row ) ) + new Vector2( Constants.FLOAT_WIDTH_SPACING * drawInfo.InvertedZoom * column, Constants.FLOAT_WIDTH_SPACING * drawInfo.InvertedZoom * row ); value[ row, column ] = EditorGUIFloatField( m_propertyDrawPos, string.Empty, value[ row, column ], UIUtils.MainSkin.textField ); } } if ( currMode ) { m_materialValue = value; } else { m_defaultValue = value; } if ( EditorGUI.EndChangeCheck() ) { m_requireMaterialUpdate = m_materialMode; BeginDelayedDirtyProperty(); } } } public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar ) { base.GenerateShaderForOutput( outputId, ref dataCollector, ignoreLocalvar ); m_precisionString = UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, m_outputPorts[ 0 ].DataType ); if ( m_currentParameterType != PropertyType.Constant ) return PropertyData; Matrix4x4 value = m_defaultValue; return m_precisionString+"(" + value[ 0, 0 ] + "," + value[ 0, 1 ] + "," + value[ 0, 2 ] + "," + value[ 0, 3 ] + "," + +value[ 1, 0 ] + "," + value[ 1, 1 ] + "," + value[ 1, 2 ] + "," + value[ 1, 3 ] + "," + +value[ 2, 0 ] + "," + value[ 2, 1 ] + "," + value[ 2, 2 ] + "," + value[ 2, 3 ] + "," + +value[ 3, 0 ] + "," + value[ 3, 1 ] + "," + value[ 3, 2 ] + "," + value[ 3, 3 ] + ")"; } public override void UpdateMaterial( Material mat ) { base.UpdateMaterial( mat ); if ( UIUtils.IsProperty( m_currentParameterType ) ) { mat.SetMatrix( m_propertyName, m_materialValue ); } } public override void SetMaterialMode( Material mat , bool fetchMaterialValues ) { base.SetMaterialMode( mat , fetchMaterialValues ); if ( fetchMaterialValues && m_materialMode && UIUtils.IsProperty( m_currentParameterType ) && mat.HasProperty( m_propertyName ) ) { m_materialValue = mat.GetMatrix( m_propertyName ); } } public override void ForceUpdateFromMaterial( Material material ) { if ( UIUtils.IsProperty( m_currentParameterType ) && material.HasProperty( m_propertyName ) ) m_materialValue = material.GetMatrix( m_propertyName ); } public override void ReadFromString( ref string[] nodeParams ) { base.ReadFromString( ref nodeParams ); string[] matrixVals = GetCurrentParam( ref nodeParams ).Split( IOUtils.VECTOR_SEPARATOR ); if ( matrixVals.Length == 16 ) { m_defaultValue[ 0, 0 ] = Convert.ToSingle( matrixVals[ 0 ] ); m_defaultValue[ 0, 1 ] = Convert.ToSingle( matrixVals[ 1 ] ); m_defaultValue[ 0, 2 ] = Convert.ToSingle( matrixVals[ 2 ] ); m_defaultValue[ 0, 3 ] = Convert.ToSingle( matrixVals[ 3 ] ); m_defaultValue[ 1, 0 ] = Convert.ToSingle( matrixVals[ 4 ] ); m_defaultValue[ 1, 1 ] = Convert.ToSingle( matrixVals[ 5 ] ); m_defaultValue[ 1, 2 ] = Convert.ToSingle( matrixVals[ 6 ] ); m_defaultValue[ 1, 3 ] = Convert.ToSingle( matrixVals[ 7 ] ); m_defaultValue[ 2, 0 ] = Convert.ToSingle( matrixVals[ 8 ] ); m_defaultValue[ 2, 1 ] = Convert.ToSingle( matrixVals[ 9 ] ); m_defaultValue[ 2, 2 ] = Convert.ToSingle( matrixVals[ 10 ] ); m_defaultValue[ 2, 3 ] = Convert.ToSingle( matrixVals[ 11 ] ); m_defaultValue[ 3, 0 ] = Convert.ToSingle( matrixVals[ 12 ] ); m_defaultValue[ 3, 1 ] = Convert.ToSingle( matrixVals[ 13 ] ); m_defaultValue[ 3, 2 ] = Convert.ToSingle( matrixVals[ 14 ] ); m_defaultValue[ 3, 3 ] = Convert.ToSingle( matrixVals[ 15 ] ); } else { UIUtils.ShowMessage( "Incorrect number of matrix4x4 values", MessageSeverity.Error ); } } public override void WriteToString( ref string nodeInfo, ref string connectionsInfo ) { base.WriteToString( ref nodeInfo, ref connectionsInfo ); IOUtils.AddFieldValueToString( ref nodeInfo, m_defaultValue[ 0, 0 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 0, 1 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 0, 2 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 0, 3 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 1, 0 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 1, 1 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 1, 2 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 1, 3 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 2, 0 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 2, 1 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 2, 2 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 2, 3 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 3, 0 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 3, 1 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 3, 2 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 3, 3 ].ToString() ); } public override void ReadAdditionalClipboardData( ref string[] nodeParams ) { base.ReadAdditionalClipboardData( ref nodeParams ); m_materialValue = IOUtils.StringToMatrix4x4( GetCurrentParam( ref nodeParams ) ); } public override void WriteAdditionalClipboardData( ref string nodeInfo ) { base.WriteAdditionalClipboardData( ref nodeInfo ); IOUtils.AddFieldValueToString( ref nodeInfo, IOUtils.Matrix4x4ToString( m_materialValue ) ); } public override string GetPropertyValStr() { return ( m_materialMode && m_currentParameterType != PropertyType.Constant ) ? m_materialValue[ 0, 0 ].ToString( Mathf.Abs( m_materialValue[ 0, 0 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_materialValue[ 0, 1 ].ToString( Mathf.Abs( m_materialValue[ 0, 1 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_materialValue[ 0, 2 ].ToString( Mathf.Abs( m_materialValue[ 0, 2 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_materialValue[ 0, 3 ].ToString( Mathf.Abs( m_materialValue[ 0, 3 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.MATRIX_DATA_SEPARATOR + m_materialValue[ 1, 0 ].ToString( Mathf.Abs( m_materialValue[ 1, 0 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_materialValue[ 1, 1 ].ToString( Mathf.Abs( m_materialValue[ 1, 1 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_materialValue[ 1, 2 ].ToString( Mathf.Abs( m_materialValue[ 1, 2 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_materialValue[ 1, 3 ].ToString( Mathf.Abs( m_materialValue[ 1, 3 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.MATRIX_DATA_SEPARATOR + m_materialValue[ 2, 0 ].ToString( Mathf.Abs( m_materialValue[ 2, 0 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_materialValue[ 2, 1 ].ToString( Mathf.Abs( m_materialValue[ 2, 1 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_materialValue[ 2, 2 ].ToString( Mathf.Abs( m_materialValue[ 2, 2 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_materialValue[ 2, 3 ].ToString( Mathf.Abs( m_materialValue[ 2, 3 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.MATRIX_DATA_SEPARATOR + m_materialValue[ 3, 0 ].ToString( Mathf.Abs( m_materialValue[ 3, 0 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_materialValue[ 3, 1 ].ToString( Mathf.Abs( m_materialValue[ 3, 1 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_materialValue[ 3, 2 ].ToString( Mathf.Abs( m_materialValue[ 3, 2 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_materialValue[ 3, 3 ].ToString( Mathf.Abs( m_materialValue[ 3, 3 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) : m_defaultValue[ 0, 0 ].ToString( Mathf.Abs( m_defaultValue[ 0, 0 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 0, 1 ].ToString( Mathf.Abs( m_defaultValue[ 0, 1 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 0, 2 ].ToString( Mathf.Abs( m_defaultValue[ 0, 2 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 0, 3 ].ToString( Mathf.Abs( m_defaultValue[ 0, 3 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.MATRIX_DATA_SEPARATOR + m_defaultValue[ 1, 0 ].ToString( Mathf.Abs( m_defaultValue[ 1, 0 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 1, 1 ].ToString( Mathf.Abs( m_defaultValue[ 1, 1 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 1, 2 ].ToString( Mathf.Abs( m_defaultValue[ 1, 2 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 1, 3 ].ToString( Mathf.Abs( m_defaultValue[ 1, 3 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.MATRIX_DATA_SEPARATOR + m_defaultValue[ 2, 0 ].ToString( Mathf.Abs( m_defaultValue[ 2, 0 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 2, 1 ].ToString( Mathf.Abs( m_defaultValue[ 2, 1 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 2, 2 ].ToString( Mathf.Abs( m_defaultValue[ 2, 2 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 2, 3 ].ToString( Mathf.Abs( m_defaultValue[ 2, 3 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.MATRIX_DATA_SEPARATOR + m_defaultValue[ 3, 0 ].ToString( Mathf.Abs( m_defaultValue[ 3, 0 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 3, 1 ].ToString( Mathf.Abs( m_defaultValue[ 3, 1 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 3, 2 ].ToString( Mathf.Abs( m_defaultValue[ 3, 2 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ) + IOUtils.VECTOR_SEPARATOR + m_defaultValue[ 3, 3 ].ToString( Mathf.Abs( m_defaultValue[ 3, 3 ] ) > 1000 ? Constants.PropertyBigMatrixFormatLabel : Constants.PropertyMatrixFormatLabel ); } } }
// Copyright 2015-2016 Google Inc. All Rights Reserved. // Licensed under the Apache License Version 2.0. using Google.Apis.Compute.v1.Data; using System.Collections; using System.Collections.Generic; using System.Management.Automation; namespace Google.PowerShell.ComputeEngine { /// <summary> /// This abstract class describes all of the information needed to create an instance template description. /// It is extended by AddGceInstanceTemplateCmdlet, which sends an instance template description to the /// server, and by GceInstanceDescriptionCmdlet to provide a unifed set of parameters for instances and /// instance templates. /// </summary> public abstract class GceTemplateDescriptionCmdlet : GceConcurrentCmdlet { /// <summary> /// The name of the instance or instance template. /// </summary> public abstract string Name { get; set; } /// <summary> /// The name of the machine type for the instances. /// </summary> public abstract string MachineType { get; set; } /// <summary> /// Enables instances to send and receive packets for IP addresses other than their own. Switch on if /// this instance will be used as an IP gateway or it will be set as the next-hop in a Route /// resource. /// </summary> public abstract SwitchParameter CanIpForward { get; set; } /// <summary> /// Human readable description. /// </summary> public abstract string Description { get; set; } /// <summary> /// The the image used to create the boot disk. Use Get-GceImage to get one of these. /// </summary> public abstract Image BootDiskImage { get; set; } /// <summary> /// An existing disk to attach. It will be attached in read-only mode. /// </summary> public abstract Disk[] ExtraDisk { get; set; } /// <summary> /// An AttachedDisk object specifying a disk to attach. Do not specify `-BootDiskImage` or /// `-BootDiskSnapshot` if this is a boot disk. You can build one using New-GceAttachedDiskConfig. /// </summary> public abstract AttachedDisk[] Disk { get; set; } /// <summary> /// <para type="description"> /// The keys and values of the Metadata of this instance. /// </para> /// </summary> public abstract IDictionary Metadata { get; set; } /// <summary> /// The name of the network to use. If not specified, it is global/networks/default. /// </summary> public abstract string Network { get; set; } /// <summary> /// If set, the instance will not have an external ip address. /// </summary> public abstract SwitchParameter NoExternalIp { get; set; } /// <summary> /// If set, the instance will be preemptible, and AutomaticRestart will be false. /// </summary> public abstract SwitchParameter Preemptible { get; set; } /// <summary> /// If set, the instance will not restart when shut down by Google Compute Engine. /// </summary> public abstract bool AutomaticRestart { get; set; } /// <summary> /// If set, the instance will terminate rather than migrate when the host undergoes maintenance. /// </summary> public abstract SwitchParameter TerminateOnMaintenance { get; set; } /// <summary> /// The ServiceAccount used to specify access tokens. Use New-GceServiceAccountConfig to build one. /// </summary> public abstract ServiceAccount[] ServiceAccount { get; set; } /// <summary> /// A tag of this instance. /// </summary> public abstract string[] Tag { get; set; } /// <summary> /// Builds a network interface given the Network and NoExternalIp parameters. /// </summary> /// <returns> /// The NetworkInsterface object to use in the instance template description. /// </returns> protected virtual NetworkInterface BuildNetworkInterfaces() { var accessConfigs = new List<AccessConfig>(); if (!NoExternalIp) { accessConfigs.Add(new AccessConfig { Name = "External NAT", Type = "ONE_TO_ONE_NAT" }); } string networkUri = Network; if (string.IsNullOrEmpty(networkUri)) { networkUri = "default"; } if (!networkUri.Contains("global/networks")) { networkUri = $"global/networks/{networkUri}"; } return new NetworkInterface { Network = networkUri, AccessConfigs = accessConfigs }; } /// <summary> /// Creates a list of AttachedDisk objects form Disk, BootDiskImage, and ExtraDis. /// </summary> /// <returns> /// A list of AttachedDisk objects to be used in the instance template description. /// </returns> protected virtual IList<AttachedDisk> BuildAttachedDisks() { var disks = new List<AttachedDisk>(); if (Disk != null) { disks.AddRange(Disk); } if (BootDiskImage != null) { disks.Add(new AttachedDisk { Boot = true, AutoDelete = true, InitializeParams = new AttachedDiskInitializeParams { SourceImage = BootDiskImage.SelfLink } }); } if (ExtraDisk != null) { foreach (Disk disk in ExtraDisk) { disks.Add(new AttachedDisk { Source = disk.SelfLink, Mode = "READ_ONLY" }); } } return disks; } /// <summary> /// Builds an InstanceTemplate from parameter values. /// </summary> /// <returns> /// An InstanceTemplate to be sent to Google Compute Engine as part of a insert instance template /// request. /// </returns> protected InstanceTemplate BuildInstanceTemplate() { return new InstanceTemplate { Name = Name, Description = Description, Properties = new InstanceProperties { CanIpForward = CanIpForward, Description = Description, Disks = BuildAttachedDisks(), MachineType = MachineType, Metadata = InstanceMetadataPSConverter.BuildMetadata(Metadata), NetworkInterfaces = new List<NetworkInterface> { BuildNetworkInterfaces() }, Scheduling = new Scheduling { AutomaticRestart = AutomaticRestart && !Preemptible, Preemptible = Preemptible, OnHostMaintenance = TerminateOnMaintenance ? "TERMINATE" : "MIGRATE" }, ServiceAccounts = ServiceAccount, Tags = new Tags { Items = Tag } } }; } } /// <summary> /// Base cmdlet class indicating what parameters are needed to describe an instance. Used by /// NewGceInstanceConfigCmdlet and AdGceInstanceCmdlet to provide a unifed way to build an instance /// description. /// </summary> public abstract class GceInstanceDescriptionCmdlet : GceTemplateDescriptionCmdlet { /// <summary> /// The persistant disk to use as a boot disk. Use Get-GceDisk to get one of these. /// </summary> public abstract Disk BootDisk { get; set; } /// <summary> /// <para type="description"> /// The static ip address this instance will have. /// </para> /// </summary> protected abstract string Address { get; set; } /// <summary> /// Extend the parent BuildAttachedDisks by optionally appending a disk from the BootDisk attribute. /// </summary> /// <returns> /// A list of AttachedDisk objects to be used in the instance description. /// </returns> protected override IList<AttachedDisk> BuildAttachedDisks() { IList<AttachedDisk> disks = base.BuildAttachedDisks(); if (BootDisk != null) { disks.Add(new AttachedDisk { Boot = true, AutoDelete = false, Source = BootDisk.SelfLink }); } return disks; } /// <summary> /// Extends the parent BuildnetworkInterfaces by adding the static address to the network interface. /// </summary> /// <returns> /// The NetworkInsterface object to use in the instance description. /// </returns> protected override NetworkInterface BuildNetworkInterfaces() { NetworkInterface networkInterface = base.BuildNetworkInterfaces(); networkInterface.NetworkIP = Address; return networkInterface; } /// <summary> /// Builds the instance description based on the cmdlet parameters. /// </summary> /// <returns> /// An Instance object to be sent to Google Compute Engine as part of an insert instance request. /// </returns> protected Instance BuildInstance() { return new Instance { Name = Name, CanIpForward = CanIpForward, Description = Description, Disks = BuildAttachedDisks(), MachineType = MachineType, Metadata = InstanceMetadataPSConverter.BuildMetadata(Metadata), NetworkInterfaces = new List<NetworkInterface> { BuildNetworkInterfaces() }, Scheduling = new Scheduling { AutomaticRestart = AutomaticRestart && !Preemptible, Preemptible = Preemptible, OnHostMaintenance = TerminateOnMaintenance ? "TERMINATE" : "MIGRATE" }, ServiceAccounts = ServiceAccount, Tags = new Tags { Items = Tag } }; } } }
// <copyright file="LUTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // Copyright (c) 2009-2010 Math.NET // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Complex; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex.Factorization { #if NOSYSNUMERICS using Complex = Numerics.Complex; #else using Complex = System.Numerics.Complex; #endif /// <summary> /// LU factorization tests for a dense matrix. /// </summary> [TestFixture, Category("LAFactorization")] public class LUTests { /// <summary> /// Can factorize identity matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(10)] [TestCase(100)] public void CanFactorizeIdentity(int order) { var matrixI = DenseMatrix.CreateIdentity(order); var factorLU = matrixI.LU(); // Check lower triangular part. var matrixL = factorLU.L; Assert.AreEqual(matrixI.RowCount, matrixL.RowCount); Assert.AreEqual(matrixI.ColumnCount, matrixL.ColumnCount); for (var i = 0; i < matrixL.RowCount; i++) { for (var j = 0; j < matrixL.ColumnCount; j++) { Assert.AreEqual(i == j ? Complex.One : Complex.Zero, matrixL[i, j]); } } // Check upper triangular part. var matrixU = factorLU.U; Assert.AreEqual(matrixI.RowCount, matrixU.RowCount); Assert.AreEqual(matrixI.ColumnCount, matrixU.ColumnCount); for (var i = 0; i < matrixU.RowCount; i++) { for (var j = 0; j < matrixU.ColumnCount; j++) { Assert.AreEqual(i == j ? Complex.One : Complex.Zero, matrixU[i, j]); } } } /// <summary> /// LU factorization fails with a non-square matrix. /// </summary> [Test] public void LUFailsWithNonSquareMatrix() { var matrix = new DenseMatrix(3, 2); Assert.That(() => matrix.LU(), Throws.ArgumentException); } /// <summary> /// Identity determinant is one. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(10)] [TestCase(100)] public void IdentityDeterminantIsOne(int order) { var matrixI = DenseMatrix.CreateIdentity(order); var lu = matrixI.LU(); Assert.AreEqual(Complex.One, lu.Determinant); } /// <summary> /// Can factorize a random square matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanFactorizeRandomMatrix(int order) { var matrixX = Matrix<Complex>.Build.Random(order, order, 1); var factorLU = matrixX.LU(); var matrixL = factorLU.L; var matrixU = factorLU.U; // Make sure the factors have the right dimensions. Assert.AreEqual(order, matrixL.RowCount); Assert.AreEqual(order, matrixL.ColumnCount); Assert.AreEqual(order, matrixU.RowCount); Assert.AreEqual(order, matrixU.ColumnCount); // Make sure the L factor is lower triangular. for (var i = 0; i < matrixL.RowCount; i++) { Assert.AreEqual(Complex.One, matrixL[i, i]); for (var j = i + 1; j < matrixL.ColumnCount; j++) { Assert.AreEqual(Complex.Zero, matrixL[i, j]); } } // Make sure the U factor is upper triangular. for (var i = 0; i < matrixL.RowCount; i++) { for (var j = 0; j < i; j++) { Assert.AreEqual(Complex.Zero, matrixU[i, j]); } } // Make sure the LU factor times it's transpose is the original matrix. var matrixXfromLU = matrixL * matrixU; var permutationInverse = factorLU.P.Inverse(); matrixXfromLU.PermuteRows(permutationInverse); for (var i = 0; i < matrixXfromLU.RowCount; i++) { for (var j = 0; j < matrixXfromLU.ColumnCount; j++) { AssertHelpers.AlmostEqualRelative(matrixX[i, j], matrixXfromLU[i, j], 9); } } } /// <summary> /// Can solve a system of linear equations for a random vector (Ax=b). /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomVector(int order) { var matrixA = Matrix<Complex>.Build.Random(order, order, 1); var matrixACopy = matrixA.Clone(); var factorLU = matrixA.LU(); var vectorb = Vector<Complex>.Build.Random(order, 1); var resultx = factorLU.Solve(vectorb); Assert.AreEqual(matrixA.ColumnCount, resultx.Count); var matrixBReconstruct = matrixA * resultx; // Check the reconstruction. for (var i = 0; i < order; i++) { AssertHelpers.AlmostEqual(vectorb[i], matrixBReconstruct[i], 10); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B). /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomMatrix(int order) { var matrixA = Matrix<Complex>.Build.Random(order, order, 1); var matrixACopy = matrixA.Clone(); var factorLU = matrixA.LU(); var matrixB = Matrix<Complex>.Build.Random(order, order, 1); var matrixX = factorLU.Solve(matrixB); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA * matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { AssertHelpers.AlmostEqual(matrixB[i, j], matrixBReconstruct[i, j], 10); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve for a random vector into a result vector. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomVectorWhenResultVectorGiven(int order) { var matrixA = Matrix<Complex>.Build.Random(order, order, 1); var matrixACopy = matrixA.Clone(); var factorLU = matrixA.LU(); var vectorb = Vector<Complex>.Build.Random(order, 1); var vectorbCopy = vectorb.Clone(); var resultx = new DenseVector(order); factorLU.Solve(vectorb, resultx); Assert.AreEqual(vectorb.Count, resultx.Count); var matrixBReconstruct = matrixA * resultx; // Check the reconstruction. for (var i = 0; i < vectorb.Count; i++) { AssertHelpers.AlmostEqual(vectorb[i], matrixBReconstruct[i], 10); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure b didn't change. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorbCopy[i], vectorb[i]); } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix. /// </summary> /// <param name="order">Matrix row number.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomMatrixWhenResultMatrixGiven(int order) { var matrixA = Matrix<Complex>.Build.Random(order, order, 1); var matrixACopy = matrixA.Clone(); var factorLU = matrixA.LU(); var matrixB = Matrix<Complex>.Build.Random(order, order, 1); var matrixBCopy = matrixB.Clone(); var matrixX = new DenseMatrix(order, order); factorLU.Solve(matrixB, matrixX); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA * matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { AssertHelpers.AlmostEqual(matrixB[i, j], matrixBReconstruct[i, j], 10); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure B didn't change. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]); } } } /// <summary> /// Can inverse a matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanInverse(int order) { var matrixA = Matrix<Complex>.Build.Random(order, order, 1); var matrixACopy = matrixA.Clone(); var factorLU = matrixA.LU(); var matrixAInverse = factorLU.Inverse(); // The inverse dimension is equal A Assert.AreEqual(matrixAInverse.RowCount, matrixAInverse.RowCount); Assert.AreEqual(matrixAInverse.ColumnCount, matrixAInverse.ColumnCount); var matrixIdentity = matrixA * matrixAInverse; // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Check if multiplication of A and AI produced identity matrix. for (var i = 0; i < matrixIdentity.RowCount; i++) { AssertHelpers.AlmostEqualRelative(matrixIdentity[i, i], Complex.One, 9); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Threading.Tasks.Tests { public static partial class CancellationTokenTests { [Fact] public static void CancellationTokenRegister_Exceptions() { CancellationToken token = new CancellationToken(); Assert.Throws<ArgumentNullException>(() => token.Register(null)); Assert.Throws<ArgumentNullException>(() => token.Register(null, false)); Assert.Throws<ArgumentNullException>(() => token.Register(null, null)); } [Fact] public static void CancellationTokenEquality() { //simple empty token comparisons Assert.Equal(new CancellationToken(), new CancellationToken()); //inflated empty token comparisons CancellationToken inflated_empty_CT1 = new CancellationToken(); bool temp1 = inflated_empty_CT1.CanBeCanceled; // inflate the CT CancellationToken inflated_empty_CT2 = new CancellationToken(); bool temp2 = inflated_empty_CT2.CanBeCanceled; // inflate the CT Assert.Equal(inflated_empty_CT1, new CancellationToken()); Assert.Equal(new CancellationToken(), inflated_empty_CT1); Assert.Equal(inflated_empty_CT1, inflated_empty_CT2); // inflated pre-set token comparisons CancellationToken inflated_defaultSet_CT1 = new CancellationToken(true); bool temp3 = inflated_defaultSet_CT1.CanBeCanceled; // inflate the CT CancellationToken inflated_defaultSet_CT2 = new CancellationToken(true); bool temp4 = inflated_defaultSet_CT2.CanBeCanceled; // inflate the CT Assert.Equal(inflated_defaultSet_CT1, new CancellationToken(true)); Assert.Equal(inflated_defaultSet_CT1, inflated_defaultSet_CT2); // Things that are not equal Assert.NotEqual(inflated_empty_CT1, inflated_defaultSet_CT2); Assert.NotEqual(inflated_empty_CT1, new CancellationToken(true)); Assert.NotEqual(new CancellationToken(true), inflated_empty_CT1); } [Fact] public static void CancellationToken_GetHashCode() { CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken ct = cts.Token; int hash1 = cts.GetHashCode(); int hash2 = cts.Token.GetHashCode(); int hash3 = ct.GetHashCode(); Assert.Equal(hash1, hash2); Assert.Equal(hash2, hash3); CancellationToken defaultUnsetToken1 = new CancellationToken(); CancellationToken defaultUnsetToken2 = new CancellationToken(); int hashDefaultUnset1 = defaultUnsetToken1.GetHashCode(); int hashDefaultUnset2 = defaultUnsetToken2.GetHashCode(); Assert.Equal(hashDefaultUnset1, hashDefaultUnset2); CancellationToken defaultSetToken1 = new CancellationToken(true); CancellationToken defaultSetToken2 = new CancellationToken(true); int hashDefaultSet1 = defaultSetToken1.GetHashCode(); int hashDefaultSet2 = defaultSetToken2.GetHashCode(); Assert.Equal(hashDefaultSet1, hashDefaultSet2); Assert.NotEqual(hash1, hashDefaultUnset1); Assert.NotEqual(hash1, hashDefaultSet1); Assert.NotEqual(hashDefaultUnset1, hashDefaultSet1); } [Fact] public static void CancellationToken_EqualityAndDispose() { //hashcode. Assert.Throws<ObjectDisposedException>( () => { CancellationTokenSource cts = new CancellationTokenSource(); cts.Dispose(); cts.Token.GetHashCode(); }); //x.Equals(y) Assert.Throws<ObjectDisposedException>( () => { CancellationTokenSource cts = new CancellationTokenSource(); cts.Dispose(); cts.Token.Equals(new CancellationToken()); }); //x.Equals(y) Assert.Throws<ObjectDisposedException>( () => { CancellationTokenSource cts = new CancellationTokenSource(); cts.Dispose(); new CancellationToken().Equals(cts.Token); }); //x==y Assert.Throws<ObjectDisposedException>( () => { CancellationTokenSource cts = new CancellationTokenSource(); cts.Dispose(); bool result = cts.Token == new CancellationToken(); }); //x==y Assert.Throws<ObjectDisposedException>( () => { CancellationTokenSource cts = new CancellationTokenSource(); cts.Dispose(); bool result = new CancellationToken() == cts.Token; }); //x!=y Assert.Throws<ObjectDisposedException>( () => { CancellationTokenSource cts = new CancellationTokenSource(); cts.Dispose(); bool result = cts.Token != new CancellationToken(); }); //x!=y Assert.Throws<ObjectDisposedException>( () => { CancellationTokenSource cts = new CancellationTokenSource(); cts.Dispose(); bool result = new CancellationToken() != cts.Token; }); } [Fact] public static void TokenSourceDispose() { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; CancellationTokenRegistration preDisposeRegistration = token.Register(() => { }); //WaitHandle and Dispose WaitHandle wh = token.WaitHandle; //ok Assert.NotNull(wh); tokenSource.Dispose(); // Regression test: allow ctr.Dispose() to succeed when the backing cts has already been disposed. try { preDisposeRegistration.Dispose(); } catch { Assert.True(false, string.Format("TokenSourceDispose: > ctr.Dispose() failed when referring to a disposed CTS")); } bool cr = tokenSource.IsCancellationRequested; //this is ok after dispose. tokenSource.Dispose(); //Repeat calls to Dispose should be ok. } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Relies on quirked behavior to not throw in token.Register when already disposed")] [Fact] public static void TokenSourceDispose_Negative() { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; CancellationTokenRegistration preDisposeRegistration = token.Register(() => { }); //WaitHandle and Dispose tokenSource.Dispose(); Assert.Throws<ObjectDisposedException>(() => token.WaitHandle); Assert.Throws<ObjectDisposedException>(() =>tokenSource.Token); //shouldn't throw token.Register(() => { }); // Allow ctr.Dispose() to succeed when the backing cts has already been disposed. preDisposeRegistration.Dispose(); //shouldn't throw CancellationTokenSource.CreateLinkedTokenSource(new[] { token, token }); } /// <summary> /// Test passive signalling. /// /// Gets a token, then polls on its ThrowIfCancellationRequested property. /// </summary> /// <returns></returns> [Fact] public static void CancellationTokenPassiveListening() { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; Assert.False(token.IsCancellationRequested, "CancellationTokenPassiveListening: Cancellation should not have occurred yet."); tokenSource.Cancel(); Assert.True(token.IsCancellationRequested, "CancellationTokenPassiveListening: Cancellation should now have occurred."); } /// <summary> /// Test active signalling. /// /// Gets a token, registers a notification callback and ensure it is called. /// </summary> /// <returns></returns> [Fact] public static void CancellationTokenActiveListening() { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; bool signalReceived = false; token.Register(() => signalReceived = true); Assert.False(signalReceived, "CancellationTokenActiveListening: Cancellation should not have occurred yet."); tokenSource.Cancel(); Assert.True(signalReceived, "CancellationTokenActiveListening: Cancellation should now have occurred and caused a signal."); } private static event EventHandler AddAndRemoveDelegates_TestEvent; [Fact] public static void AddAndRemoveDelegates() { //Test various properties of callbacks: // 1. the same handler can be added multiple times // 2. removing a handler only removes one instance of a repeat // 3. after some add and removes, everything appears to be correct // 4. The behaviour matches the behaviour of a regular Event(Multicast-delegate). CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; List<string> output = new List<string>(); Action action1 = () => output.Add("action1"); Action action2 = () => output.Add("action2"); CancellationTokenRegistration reg1 = token.Register(action1); CancellationTokenRegistration reg2 = token.Register(action2); CancellationTokenRegistration reg3 = token.Register(action2); CancellationTokenRegistration reg4 = token.Register(action1); reg2.Dispose(); reg3.Dispose(); reg4.Dispose(); tokenSource.Cancel(); Assert.Equal(1, output.Count); Assert.Equal("action1", output[0]); // and prove this is what normal events do... output.Clear(); EventHandler handler1 = (sender, obj) => output.Add("handler1"); EventHandler handler2 = (sender, obj) => output.Add("handler2"); AddAndRemoveDelegates_TestEvent += handler1; AddAndRemoveDelegates_TestEvent += handler2; AddAndRemoveDelegates_TestEvent += handler2; AddAndRemoveDelegates_TestEvent += handler1; AddAndRemoveDelegates_TestEvent -= handler2; AddAndRemoveDelegates_TestEvent -= handler2; AddAndRemoveDelegates_TestEvent -= handler1; AddAndRemoveDelegates_TestEvent(null, EventArgs.Empty); Assert.Equal(1, output.Count); Assert.Equal("handler1", output[0]); } /// <summary> /// Test late enlistment. /// /// If a handler is added to a 'canceled' cancellation token, the handler is called immediately. /// </summary> /// <returns></returns> [Fact] public static void CancellationTokenLateEnlistment() { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; bool signalReceived = false; tokenSource.Cancel(); //Signal //Late enlist.. should fire the delegate synchronously token.Register(() => signalReceived = true); Assert.True(signalReceived, "CancellationTokenLateEnlistment: The signal should have been received even after late enlistment."); } /// <summary> /// Test the wait handle exposed by the cancellation token /// /// The signal occurs on a separate thread, and should happen after the wait begins. /// </summary> /// <returns></returns> [Fact] public static void CancellationTokenWaitHandle_SignalAfterWait() { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; Task.Run( () => { tokenSource.Cancel(); //Signal }); token.WaitHandle.WaitOne(); Assert.True(token.IsCancellationRequested, "CancellationTokenWaitHandle_SignalAfterWait: the token should have been canceled."); } /// <summary> /// Test the wait handle exposed by the cancellation token /// /// The signal occurs on a separate thread, and should happen after the wait begins. /// </summary> /// <returns></returns> [Fact] public static void CancellationTokenWaitHandle_SignalBeforeWait() { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; tokenSource.Cancel(); token.WaitHandle.WaitOne(); // the wait handle should already be set. Assert.True(token.IsCancellationRequested, "CancellationTokenWaitHandle_SignalBeforeWait: the token should have been canceled."); } /// <summary> /// Test that WaitAny can be used with a CancellationToken.WaitHandle /// </summary> /// <returns></returns> [Fact] public static void CancellationTokenWaitHandle_WaitAny() { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; CancellationToken tokenNoSource = new CancellationToken(); tokenSource.Cancel(); WaitHandle.WaitAny(new[] { token.WaitHandle, tokenNoSource.WaitHandle }); //make sure the dummy tokens has a valid WaitHanle Assert.True(token.IsCancellationRequested, "CancellationTokenWaitHandle_WaitAny: The token should have been canceled."); } [Fact] public static void CreateLinkedTokenSource_Simple_TwoToken() { CancellationTokenSource signal1 = new CancellationTokenSource(); CancellationTokenSource signal2 = new CancellationTokenSource(); //Neither token is signalled. CancellationTokenSource combined = CancellationTokenSource.CreateLinkedTokenSource(signal1.Token, signal2.Token); Assert.False(combined.IsCancellationRequested, "CreateLinkedToken_Simple_TwoToken: The combined token should start unsignalled"); signal1.Cancel(); Assert.True(combined.IsCancellationRequested, "CreateLinkedToken_Simple_TwoToken: The combined token should now be signalled"); } [Fact] public static void CreateLinkedTokenSource_Simple_MultiToken() { CancellationTokenSource signal1 = new CancellationTokenSource(); CancellationTokenSource signal2 = new CancellationTokenSource(); CancellationTokenSource signal3 = new CancellationTokenSource(); //Neither token is signalled. CancellationTokenSource combined = CancellationTokenSource.CreateLinkedTokenSource(new[] { signal1.Token, signal2.Token, signal3.Token }); Assert.False(combined.IsCancellationRequested, "CreateLinkedToken_Simple_MultiToken: The combined token should start unsignalled"); signal1.Cancel(); Assert.True(combined.IsCancellationRequested, "CreateLinkedToken_Simple_MultiToken: The combined token should now be signalled"); } [Fact] public static void CreateLinkedToken_SourceTokenAlreadySignalled() { //creating a combined token, when a source token is already signalled. CancellationTokenSource signal1 = new CancellationTokenSource(); CancellationTokenSource signal2 = new CancellationTokenSource(); signal1.Cancel(); //early signal. CancellationTokenSource combined = CancellationTokenSource.CreateLinkedTokenSource(signal1.Token, signal2.Token); Assert.True(combined.IsCancellationRequested, "CreateLinkedToken_SourceTokenAlreadySignalled: The combined token should immediately be in the signalled state."); } [Fact] public static void CreateLinkedToken_MultistepComposition_SourceTokenAlreadySignalled() { //two-step composition CancellationTokenSource signal1 = new CancellationTokenSource(); signal1.Cancel(); //early signal. CancellationTokenSource signal2 = new CancellationTokenSource(); CancellationTokenSource combined1 = CancellationTokenSource.CreateLinkedTokenSource(signal1.Token, signal2.Token); CancellationTokenSource signal3 = new CancellationTokenSource(); CancellationTokenSource combined2 = CancellationTokenSource.CreateLinkedTokenSource(signal3.Token, combined1.Token); Assert.True(combined2.IsCancellationRequested, "CreateLinkedToken_MultistepComposition_SourceTokenAlreadySignalled: The 2-step combined token should immediately be in the signalled state."); } [Fact] public static void CallbacksOrderIsLifo() { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; List<string> callbackOutput = new List<string>(); token.Register(() => callbackOutput.Add("Callback1")); token.Register(() => callbackOutput.Add("Callback2")); tokenSource.Cancel(); Assert.Equal("Callback2", callbackOutput[0]); Assert.Equal("Callback1", callbackOutput[1]); } [Fact] public static void Enlist_EarlyAndLate() { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; CancellationTokenSource earlyEnlistedTokenSource = new CancellationTokenSource(); token.Register(() => earlyEnlistedTokenSource.Cancel()); tokenSource.Cancel(); Assert.Equal(true, earlyEnlistedTokenSource.IsCancellationRequested); CancellationTokenSource lateEnlistedTokenSource = new CancellationTokenSource(); token.Register(() => lateEnlistedTokenSource.Cancel()); Assert.Equal(true, lateEnlistedTokenSource.IsCancellationRequested); } /// <summary> /// This test from donnya. Thanks Donny. /// </summary> /// <returns></returns> [Fact] public static void WaitAll() { Debug.WriteLine("WaitAll: Testing CancellationTokenTests.WaitAll, If Join does not work, then a deadlock will occur."); CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationTokenSource signal2 = new CancellationTokenSource(); ManualResetEvent mre = new ManualResetEvent(false); ManualResetEvent mre2 = new ManualResetEvent(false); Task t = new Task(() => { WaitHandle.WaitAll(new WaitHandle[] { tokenSource.Token.WaitHandle, signal2.Token.WaitHandle, mre }); mre2.Set(); }); t.Start(); tokenSource.Cancel(); signal2.Cancel(); mre.Set(); mre2.WaitOne(); t.Wait(); //true if the Join succeeds.. otherwise a deadlock will occur. } [Fact] public static void BehaviourAfterCancelSignalled() { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; token.Register(() => { }); tokenSource.Cancel(); } [Fact] public static void Cancel_ThrowOnFirstException() { ManualResetEvent mre_CancelHasBeenEnacted = new ManualResetEvent(false); CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; // Main test body ArgumentException caughtException = null; token.Register(() => { throw new InvalidOperationException(); }); token.Register(() => { throw new ArgumentException(); }); // !!NOTE: Due to LIFO ordering, this delegate should be the only one to run. Task.Run(() => { try { tokenSource.Cancel(true); } catch (ArgumentException ex) { caughtException = ex; } catch (Exception ex) { Assert.True(false, string.Format("Cancel_ThrowOnFirstException: The wrong exception type was thrown. ex=" + ex)); } mre_CancelHasBeenEnacted.Set(); }); mre_CancelHasBeenEnacted.WaitOne(); Assert.NotNull(caughtException); } [Fact] public static void Cancel_DontThrowOnFirstException() { ManualResetEvent mre_CancelHasBeenEnacted = new ManualResetEvent(false); CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; // Main test body AggregateException caughtException = null; token.Register(() => { throw new ArgumentException(); }); token.Register(() => { throw new InvalidOperationException(); }); Task.Run( () => { try { tokenSource.Cancel(false); } catch (AggregateException ex) { caughtException = ex; } mre_CancelHasBeenEnacted.Set(); } ); mre_CancelHasBeenEnacted.WaitOne(); Assert.NotNull(caughtException); Assert.Equal(2, caughtException.InnerExceptions.Count); Assert.True(caughtException.InnerExceptions[0] is InvalidOperationException, "Cancel_ThrowOnFirstException: Due to LIFO call order, the first inner exception should be an InvalidOperationException."); Assert.True(caughtException.InnerExceptions[1] is ArgumentException, "Cancel_ThrowOnFirstException: Due to LIFO call order, the second inner exception should be an ArgumentException."); } [Fact] public static void CancellationRegistration_RepeatDispose() { Exception caughtException = null; CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken ct = cts.Token; CancellationTokenRegistration registration = ct.Register(() => { }); try { registration.Dispose(); registration.Dispose(); } catch (Exception ex) { caughtException = ex; } Assert.Null(caughtException); } [Fact] public static void CancellationTokenRegistration_EqualityAndHashCode() { CancellationTokenSource outerCTS = new CancellationTokenSource(); { // different registrations on 'different' default tokens CancellationToken ct1 = new CancellationToken(); CancellationToken ct2 = new CancellationToken(); CancellationTokenRegistration ctr1 = ct1.Register(() => outerCTS.Cancel()); CancellationTokenRegistration ctr2 = ct2.Register(() => outerCTS.Cancel()); Assert.True(ctr1.Equals(ctr2), "CancellationTokenRegistration_EqualityAndHashCode: [1]The two registrations should compare equal, as they are both dummies."); Assert.True(ctr1 == ctr2, "CancellationTokenRegistration_EqualityAndHashCode: [2]The two registrations should compare equal, as they are both dummies."); Assert.False(ctr1 != ctr2, "CancellationTokenRegistration_EqualityAndHashCode: [3]The two registrations should compare equal, as they are both dummies."); Assert.True(ctr1.GetHashCode() == ctr2.GetHashCode(), "CancellationTokenRegistration_EqualityAndHashCode: [4]The two registrations should have the same hashcode, as they are both dummies."); } { // different registrations on the same already cancelled token CancellationTokenSource cts = new CancellationTokenSource(); cts.Cancel(); CancellationToken ct = cts.Token; CancellationTokenRegistration ctr1 = ct.Register(() => outerCTS.Cancel()); CancellationTokenRegistration ctr2 = ct.Register(() => outerCTS.Cancel()); Assert.True(ctr1.Equals(ctr2), "CancellationTokenRegistration_EqualityAndHashCode: [1]The two registrations should compare equal, as they are both dummies due to CTS being already canceled."); Assert.True(ctr1 == ctr2, "CancellationTokenRegistration_EqualityAndHashCode: [2]The two registrations should compare equal, as they are both dummies due to CTS being already canceled."); Assert.False(ctr1 != ctr2, "CancellationTokenRegistration_EqualityAndHashCode: [3]The two registrations should compare equal, as they are both dummies due to CTS being already canceled."); Assert.True(ctr1.GetHashCode() == ctr2.GetHashCode(), "CancellationTokenRegistration_EqualityAndHashCode: [4]The two registrations should have the same hashcode, as they are both dummies due to CTS being already canceled."); } { // different registrations on one real token CancellationTokenSource cts1 = new CancellationTokenSource(); CancellationTokenRegistration ctr1 = cts1.Token.Register(() => outerCTS.Cancel()); CancellationTokenRegistration ctr2 = cts1.Token.Register(() => outerCTS.Cancel()); Assert.False(ctr1.Equals(ctr2), "CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not compare equal."); Assert.False(ctr1 == ctr2, "CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not compare equal."); Assert.True(ctr1 != ctr2, "CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not compare equal."); Assert.False(ctr1.GetHashCode() == ctr2.GetHashCode(), "CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not have the same hashcode."); CancellationTokenRegistration ctr1copy = ctr1; Assert.True(ctr1 == ctr1copy, "The two registrations should be equal."); } { // registrations on different real tokens. // different registrations on one token CancellationTokenSource cts1 = new CancellationTokenSource(); CancellationTokenSource cts2 = new CancellationTokenSource(); CancellationTokenRegistration ctr1 = cts1.Token.Register(() => outerCTS.Cancel()); CancellationTokenRegistration ctr2 = cts2.Token.Register(() => outerCTS.Cancel()); Assert.False(ctr1.Equals(ctr2), "CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not compare equal."); Assert.False(ctr1 == ctr2, "CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not compare equal."); Assert.True(ctr1 != ctr2, "CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not compare equal."); Assert.False(ctr1.GetHashCode() == ctr2.GetHashCode(), "CancellationTokenRegistration_EqualityAndHashCode: The two registrations should not have the same hashcode."); CancellationTokenRegistration ctr1copy = ctr1; Assert.True(ctr1.Equals(ctr1copy), "The two registrations should be equal."); } } [Fact] public static void CancellationTokenLinking_ODEinTarget() { CancellationTokenSource cts1 = new CancellationTokenSource(); CancellationTokenSource cts2 = CancellationTokenSource.CreateLinkedTokenSource(cts1.Token, new CancellationToken()); Exception caughtException = null; cts2.Token.Register(() => { throw new ObjectDisposedException("myException"); }); try { cts1.Cancel(true); } catch (Exception ex) { caughtException = ex; } Assert.True( caughtException is AggregateException && caughtException.InnerException is ObjectDisposedException && caughtException.InnerException.Message.Contains("myException"), "CancellationTokenLinking_ODEinTarget: The users ODE should be caught. Actual:" + caughtException); } [Fact] public static void ThrowIfCancellationRequested() { OperationCanceledException caughtEx = null; CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken ct = cts.Token; ct.ThrowIfCancellationRequested(); // no exception should occur cts.Cancel(); try { ct.ThrowIfCancellationRequested(); } catch (OperationCanceledException oce) { caughtEx = oce; } Assert.NotNull(caughtEx); Assert.Equal(ct, caughtEx.CancellationToken); } /// <summary> /// ensure that calling ctr.Dipose() from within a cancellation callback will not deadlock. /// </summary> /// <returns></returns> [Fact] public static void DeregisterFromWithinACallbackIsSafe_BasicTest() { Debug.WriteLine("CancellationTokenTests.Bug720327_DeregisterFromWithinACallbackIsSafe_BasicTest()"); Debug.WriteLine(" - this method should complete immediately. Delay to complete indicates a deadlock failure."); CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken ct = cts.Token; CancellationTokenRegistration ctr1 = ct.Register(() => { }); ct.Register(() => { ctr1.Dispose(); }); cts.Cancel(); Debug.WriteLine(" - Completed OK."); } // regression test // Disposing a linkedCTS would previously throw if a source CTS had been // disposed already. (it is an error for a user to get in this situation, but we decided to allow it to work). [Fact] public static void ODEWhenDisposingLinkedCTS() { try { // User passes a cancellation token (CT) to component A. CancellationTokenSource userTokenSource = new CancellationTokenSource(); CancellationToken userToken = userTokenSource.Token; // Component A implements "timeout", by creating its own cancellation token source (CTS) and invoking cts.Cancel() when the timeout timer fires. CancellationTokenSource cts2 = new CancellationTokenSource(); CancellationToken cts2Token = cts2.Token; // Component A creates a linked token source representing the CT from the user and the "timeout" CT. var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cts2Token, userToken); // User calls Cancel() on his CTS and then Dispose() userTokenSource.Cancel(); userTokenSource.Dispose(); // Component B correctly cancels the operation, returns to component A. // ... // Component A now disposes the linked CTS => ObjectDisposedException is thrown by cts.Dispose() because the user CTS was already disposed. linkedTokenSource.Dispose(); } catch (Exception ex) { if (ex is ObjectDisposedException) { Assert.True(false, string.Format("Bug901737_ODEWhenDisposingLinkedCTS: - ODE Occurred!")); } else { Assert.True(false, string.Format("Bug901737_ODEWhenDisposingLinkedCTS: - Exception Occurred (not an ODE!!): " + ex)); } } } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] static void FinalizeHelper(DisposeTracker disposeTracker) { new DerivedCTS(disposeTracker); } // Several tests for deriving custom user types from CancellationTokenSource [Fact] public static void DerivedCancellationTokenSource() { // Verify that a derived CTS is functional { CancellationTokenSource c = new DerivedCTS(null); CancellationToken token = c.Token; var task = Task.Factory.StartNew(() => c.Cancel()); task.Wait(); Assert.True(token.IsCancellationRequested, "DerivedCancellationTokenSource: The token should have been cancelled."); } // Verify that callback list on a derived CTS is functional { CancellationTokenSource c = new DerivedCTS(null); CancellationToken token = c.Token; int callbackRan = 0; token.Register(() => Interlocked.Increment(ref callbackRan)); var task = Task.Factory.StartNew(() => c.Cancel()); task.Wait(); SpinWait.SpinUntil(() => callbackRan > 0, 1000); Assert.True(callbackRan == 1, "DerivedCancellationTokenSource: Expected the callback to run once. Instead, it ran " + callbackRan + " times."); } // Test the Dispose path for a class derived from CancellationTokenSource { var disposeTracker = new DisposeTracker(); CancellationTokenSource c = new DerivedCTS(disposeTracker); Assert.True(c.Token.CanBeCanceled, "DerivedCancellationTokenSource: The token should be cancellable."); c.Dispose(); // Dispose() should have prevented the finalizer from running. Give the finalizer a chance to run. If this // results in Dispose(false) getting called, we'll catch the issue. GC.Collect(); GC.WaitForPendingFinalizers(); Assert.True(disposeTracker.DisposeTrueCalled, "DerivedCancellationTokenSource: Dispose(true) should have been called."); Assert.False(disposeTracker.DisposeFalseCalled, "DerivedCancellationTokenSource: Dispose(false) should not have been called."); } // Test the finalization code path for a class derived from CancellationTokenSource { var disposeTracker = new DisposeTracker(); FinalizeHelper(disposeTracker); // Wait until the DerivedCTS object is finalized SpinWait.SpinUntil(() => { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); return disposeTracker.DisposeTrueCalled; }, 500); Assert.False(disposeTracker.DisposeTrueCalled, "DerivedCancellationTokenSource: Dispose(true) should not have been called."); Assert.True(disposeTracker.DisposeFalseCalled, "DerivedCancellationTokenSource: Dispose(false) should have been called."); } // Verify that Dispose(false) is a no-op on the CTS. Dispose(false) should only release any unmanaged resources, and // CTS does not currently hold any unmanaged resources. { var disposeTracker = new DisposeTracker(); DerivedCTS c = new DerivedCTS(disposeTracker); c.DisposeUnmanaged(); // No exception expected - the CancellationTokenSource should be valid Assert.True(c.Token.CanBeCanceled, "DerivedCancellationTokenSource: The token should still be cancellable."); Assert.False(disposeTracker.DisposeTrueCalled, "DerivedCancellationTokenSource: Dispose(true) should not have been called."); Assert.True(disposeTracker.DisposeFalseCalled, "DerivedCancellationTokenSource: Dispose(false) should have run."); } } // Several tests for deriving custom user types from CancellationTokenSource [Fact] public static void DerivedCancellationTokenSource_Negative() { // Test the Dispose path for a class derived from CancellationTokenSource { var disposeTracker = new DisposeTracker(); CancellationTokenSource c = new DerivedCTS(disposeTracker); c.Dispose(); // Dispose() should have prevented the finalizer from running. Give the finalizer a chance to run. If this // results in Dispose(false) getting called, we'll catch the issue. GC.Collect(); GC.WaitForPendingFinalizers(); Assert.Throws<ObjectDisposedException>( () => { // Accessing the Token property should throw an ObjectDisposedException if (c.Token.CanBeCanceled) Assert.True(false, string.Format("DerivedCancellationTokenSource: Accessing the Token property should throw an ObjectDisposedException, but it did not.")); else Assert.True(false, string.Format("DerivedCancellationTokenSource: Accessing the Token property should throw an ObjectDisposedException, but it did not.")); }); } } [Fact] public static void CancellationTokenSourceWithTimer() { TimeSpan bigTimeSpan = new TimeSpan(2000, 0, 0, 0, 0); TimeSpan reasonableTimeSpan = new TimeSpan(0, 0, 1); CancellationTokenSource cts = new CancellationTokenSource(); cts.Dispose(); // // Test out some int-based timeout logic // cts = new CancellationTokenSource(-1); // should be an infinite timeout CancellationToken token = cts.Token; ManualResetEventSlim mres = new ManualResetEventSlim(false); CancellationTokenRegistration ctr = token.Register(() => mres.Set()); Assert.False(token.IsCancellationRequested, "CancellationTokenSourceWithTimer: Cancellation signaled on infinite timeout (int)!"); cts.CancelAfter(1000000); Assert.False(token.IsCancellationRequested, "CancellationTokenSourceWithTimer: Cancellation signaled on super-long timeout (int) !"); cts.CancelAfter(1); Debug.WriteLine("CancellationTokenSourceWithTimer: > About to wait on cancellation that should occur soon (int)... if we hang, something bad happened"); mres.Wait(); cts.Dispose(); // // Test out some TimeSpan-based timeout logic // TimeSpan prettyLong = new TimeSpan(1, 0, 0); cts = new CancellationTokenSource(prettyLong); token = cts.Token; mres = new ManualResetEventSlim(false); ctr = token.Register(() => mres.Set()); Assert.False(token.IsCancellationRequested, "CancellationTokenSourceWithTimer: Cancellation signaled on super-long timeout (TimeSpan,1)!"); cts.CancelAfter(prettyLong); Assert.False(token.IsCancellationRequested, "CancellationTokenSourceWithTimer: Cancellation signaled on super-long timeout (TimeSpan,2) !"); cts.CancelAfter(new TimeSpan(1000)); Debug.WriteLine("CancellationTokenSourceWithTimer: > About to wait on cancellation that should occur soon (TimeSpan)... if we hang, something bad happened"); mres.Wait(); cts.Dispose(); } [Fact] public static void CancellationTokenSourceWithTimer_Negative() { TimeSpan bigTimeSpan = new TimeSpan(2000, 0, 0, 0, 0); TimeSpan reasonableTimeSpan = new TimeSpan(0, 0, 1); // // Test exception logic // Assert.Throws<ArgumentOutOfRangeException>( () => { new CancellationTokenSource(-2); }); Assert.Throws<ArgumentOutOfRangeException>( () => { new CancellationTokenSource(bigTimeSpan); }); CancellationTokenSource cts = new CancellationTokenSource(); Assert.Throws<ArgumentOutOfRangeException>( () => { cts.CancelAfter(-2); }); Assert.Throws<ArgumentOutOfRangeException>( () => { cts.CancelAfter(bigTimeSpan); }); cts.Dispose(); Assert.Throws<ObjectDisposedException>( () => { cts.CancelAfter(1); }); Assert.Throws<ObjectDisposedException>( () => { cts.CancelAfter(reasonableTimeSpan); }); } [Fact] public static void EnlistWithSyncContext_BeforeCancel() { ManualResetEvent mre_CancelHasBeenEnacted = new ManualResetEvent(false); //synchronization helper CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; // Install a SynchronizationContext... SynchronizationContext prevailingSyncCtx = SynchronizationContext.Current; TestingSynchronizationContext testContext = new TestingSynchronizationContext(); SetSynchronizationContext(testContext); // Main test body // register a null delegate, but use the currently registered syncContext. // the testSyncContext will track that it was used when the delegate is invoked. token.Register(() => { }, true); Task.Run( () => { tokenSource.Cancel(); mre_CancelHasBeenEnacted.Set(); } ); mre_CancelHasBeenEnacted.WaitOne(); Assert.True(testContext.DidSendOccur, "EnlistWithSyncContext_BeforeCancel: the delegate should have been called via Send to SyncContext."); //Cleanup. SetSynchronizationContext(prevailingSyncCtx); } [Fact] public static void EnlistWithSyncContext_BeforeCancel_ThrowingExceptionInSyncContextDelegate() { ManualResetEvent mre_CancelHasBeenEnacted = new ManualResetEvent(false); //synchronization helper CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; // Install a SynchronizationContext... SynchronizationContext prevailingSyncCtx = SynchronizationContext.Current; TestingSynchronizationContext testContext = new TestingSynchronizationContext(); SetSynchronizationContext(testContext); // Main test body AggregateException caughtException = null; // register a null delegate, but use the currently registered syncContext. // the testSyncContext will track that it was used when the delegate is invoked. token.Register(() => { throw new ArgumentException(); }, true); Task.Run( () => { try { tokenSource.Cancel(); } catch (AggregateException ex) { caughtException = ex; } mre_CancelHasBeenEnacted.Set(); } ); mre_CancelHasBeenEnacted.WaitOne(); Assert.True(testContext.DidSendOccur, "EnlistWithSyncContext_BeforeCancel_ThrowingExceptionInSyncContextDelegate: the delegate should have been called via Send to SyncContext."); Assert.NotNull(caughtException); Assert.Equal(1, caughtException.InnerExceptions.Count); Assert.True(caughtException.InnerExceptions[0] is ArgumentException, "EnlistWithSyncContext_BeforeCancel_ThrowingExceptionInSyncContextDelegate: The inner exception should be an ArgumentException."); //Cleanup. SetSynchronizationContext(prevailingSyncCtx); } [Fact] public static void EnlistWithSyncContext_BeforeCancel_ThrowingExceptionInSyncContextDelegate_ThrowOnFirst() { ManualResetEvent mre_CancelHasBeenEnacted = new ManualResetEvent(false); //synchronization helper CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; // Install a SynchronizationContext... SynchronizationContext prevailingSyncCtx = SynchronizationContext.Current; TestingSynchronizationContext testContext = new TestingSynchronizationContext(); SetSynchronizationContext(testContext); // Main test body ArgumentException caughtException = null; // register a null delegate, but use the currently registered syncContext. // the testSyncContext will track that it was used when the delegate is invoked. token.Register(() => { throw new ArgumentException(); }, true); Task.Run( () => { try { tokenSource.Cancel(true); } catch (ArgumentException ex) { caughtException = ex; } mre_CancelHasBeenEnacted.Set(); } ); mre_CancelHasBeenEnacted.WaitOne(); Assert.True(testContext.DidSendOccur, "EnlistWithSyncContext_BeforeCancel_ThrowingExceptionInSyncContextDelegate_ThrowOnFirst: the delegate should have been called via Send to SyncContext."); Assert.NotNull(caughtException); //Cleanup SetSynchronizationContext(prevailingSyncCtx); } // Test that we marshal exceptions back if we run callbacks on a sync context. // (This assumes that a syncContext.Send() may not be doing the marshalling itself). [Fact] public static void SyncContextWithExceptionThrowingCallback() { Exception caughtEx1 = null; AggregateException caughtEx2 = null; SynchronizationContext prevailingSyncCtx = SynchronizationContext.Current; SetSynchronizationContext(new ThreadCrossingSynchronizationContext()); // -- Test 1 -- // CancellationTokenSource cts = new CancellationTokenSource(); cts.Token.Register( () => { throw new Exception("testEx1"); }, true); try { cts.Cancel(true); //throw on first exception } catch (Exception ex) { caughtEx1 = (AggregateException)ex; } Assert.NotNull(caughtEx1); // -- Test 2 -- // cts = new CancellationTokenSource(); cts.Token.Register( () => { throw new ArgumentException("testEx2"); }, true); try { cts.Cancel(false); //do not throw on first exception } catch (AggregateException ex) { caughtEx2 = (AggregateException)ex; } Assert.NotNull(caughtEx2); Assert.Equal(1, caughtEx2.InnerExceptions.Count); // clean up SetSynchronizationContext(prevailingSyncCtx); } [Fact] public static void Bug720327_DeregisterFromWithinACallbackIsSafe_SyncContextTest() { Debug.WriteLine("* CancellationTokenTests.Bug720327_DeregisterFromWithinACallbackIsSafe_SyncContextTest()"); Debug.WriteLine(" - this method should complete immediately. Delay to complete indicates a deadlock failure."); //Install our syncContext. SynchronizationContext prevailingSyncCtx = SynchronizationContext.Current; ThreadCrossingSynchronizationContext threadCrossingSyncCtx = new ThreadCrossingSynchronizationContext(); SetSynchronizationContext(threadCrossingSyncCtx); CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken ct = cts.Token; CancellationTokenRegistration ctr1 = ct.Register(() => { }); CancellationTokenRegistration ctr2 = ct.Register(() => { }); CancellationTokenRegistration ctr3 = ct.Register(() => { }); CancellationTokenRegistration ctr4 = ct.Register(() => { }); ct.Register(() => { ctr1.Dispose(); }, true); // with a custom syncContext ct.Register(() => { ctr2.Dispose(); }, false); // without ct.Register(() => { ctr3.Dispose(); }, true); // with a custom syncContext ct.Register(() => { ctr4.Dispose(); }, false); // without cts.Cancel(); Debug.WriteLine(" - Completed OK."); //cleanup SetSynchronizationContext(prevailingSyncCtx); } #region Helper Classes and Methods private class TestingSynchronizationContext : SynchronizationContext { public bool DidSendOccur = false; override public void Send(SendOrPostCallback d, Object state) { //Note: another idea was to install this syncContext on the executing thread. //unfortunately, the ExecutionContext business gets in the way and reestablishes a default SyncContext. DidSendOccur = true; base.Send(d, state); // call the delegate with our syncContext installed. } } /// <summary> /// This syncContext uses a different thread to run the work /// This is similar to how WindowsFormsSynchronizationContext works. /// </summary> private class ThreadCrossingSynchronizationContext : SynchronizationContext { public bool DidSendOccur = false; override public void Send(SendOrPostCallback d, Object state) { Exception marshalledException = null; Task t = new Task( (passedInState) => { //Debug.WriteLine(" threadCrossingSyncContext..running callback delegate on threadID = " + Thread.CurrentThread.ManagedThreadId); try { d(passedInState); } catch (Exception e) { marshalledException = e; } }, state); t.Start(); t.Wait(); //t.Start(state); //t.Join(); if (marshalledException != null) throw new AggregateException("DUMMY: ThreadCrossingSynchronizationContext.Send captured and propogated an exception", marshalledException); } } /// <summary> /// A test class derived from CancellationTokenSource /// </summary> internal class DerivedCTS : CancellationTokenSource { private DisposeTracker _disposeTracker; public DerivedCTS(DisposeTracker disposeTracker) { _disposeTracker = disposeTracker; } protected override void Dispose(bool disposing) { // Dispose any derived class state. DerivedCTS simply records that Dispose() has been called. if (_disposeTracker != null) { if (disposing) { _disposeTracker.DisposeTrueCalled = true; } else { _disposeTracker.DisposeFalseCalled = true; } } // Dispose the state in the CancellationTokenSource base class base.Dispose(disposing); } /// <summary> /// A helper method to call Dispose(false). That allows us to easily simulate finalization of CTS, while still maintaining /// a reference to the CTS. /// </summary> public void DisposeUnmanaged() { Dispose(false); } ~DerivedCTS() { Dispose(false); } } /// <summary> /// A simple class to track whether Dispose(bool) method has been called and if so, what was the bool flag. /// </summary> internal class DisposeTracker { public bool DisposeTrueCalled = false; public bool DisposeFalseCalled = false; } public static void SetSynchronizationContext(SynchronizationContext sc) { SynchronizationContext.SetSynchronizationContext(sc); } #endregion } }
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 DemoREST.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Configuration; namespace newtelligence.DasBlog.Web.Core { /// <summary> /// AGB, 10 June 2008 /// TitleMapperModuleSectionHandler - moving exlusions from <see cref="TitleMapperModule.HttpHandlerStrings"/> /// to a configuration section. If the section is not in the Web.config - will fallback to using the /// string array as before. /// </summary> public class TitleMapperModuleSectionHandler : ConfigurationSection { public TitleMapperModuleSectionHandler() { } /// <summary> /// Private instance for the custom configuration section. /// </summary> private static TitleMapperModuleSectionHandler _instance = TryGetConfigurationSection(); /// <summary> /// Singleton access to the section. Since this class will never be used remotely it's stafe to use the /// static member pattern for a Singleton. /// </summary> public static TitleMapperModuleSectionHandler Settings { get { return _instance; } } /// <summary> /// Helper method to try and load the section during object initialization /// </summary> /// <returns></returns> private static TitleMapperModuleSectionHandler TryGetConfigurationSection() { TitleMapperModuleSectionHandler settings; try { settings = ConfigurationManager.GetSection("newtelligence.DasBlog.TitleMapper") as TitleMapperModuleSectionHandler; } catch { settings = new TitleMapperModuleSectionHandler(); settings.Exclusions = new ExclusionCollection(); //count will be zero } return settings; } // Declare a collection element represented // in the configuration file by the sub-section // <exclusions> <add .../> </exclusions> // Note: the "IsDefaultCollection = false" // instructs the .NET Framework to build a nested // section like <exclusions> ...</exclusions>. // Note: Use a private member as the store so we can create // a safe Count=0 collection if the section was not loaded. private ExclusionCollection _exclusions; [ConfigurationProperty("exclusions", IsDefaultCollection = false)] public ExclusionCollection Exclusions { get { _exclusions = base["exclusions"] as ExclusionCollection; if (_exclusions == null) _exclusions = new ExclusionCollection(); return _exclusions; } set { _exclusions = value; } } } // Define the ExclusionCollection that contains ExclusionElements. public class ExclusionCollection : ConfigurationElementCollection { public ExclusionCollection() { //ExclusionElement exclusion = (ExclusionElement)CreateNewElement(); //// Add the element to the collection. //Add(exclusion); } public override ConfigurationElementCollectionType CollectionType { get { return ConfigurationElementCollectionType.AddRemoveClearMap; } } protected override ConfigurationElement CreateNewElement() { return new ExclusionElement(); } protected override ConfigurationElement CreateNewElement(string path) { return new ExclusionElement(path); } protected override Object GetElementKey(ConfigurationElement element) { return ((ExclusionElement)element).Path; } public new string AddElementName { get { return base.AddElementName; } set { base.AddElementName = value; } } public new string ClearElementName { get { return base.ClearElementName; } set { base.AddElementName = value; } } public new string RemoveElementName { get { return base.RemoveElementName; } } public new int Count { get { return base.Count; } } public ExclusionElement this[int index] { get { return (ExclusionElement)BaseGet(index); } set { if (BaseGet(index) != null) { BaseRemoveAt(index); } BaseAdd(index, value); } } new public ExclusionElement this[string path] { get { return (ExclusionElement)BaseGet(path); } } public int IndexOf(ExclusionElement exclusion) { return BaseIndexOf(exclusion); } public void Add(ExclusionElement exclusion) { BaseAdd(exclusion); } protected override void BaseAdd(ConfigurationElement element) { BaseAdd(element, false); } public void Remove(ExclusionElement exclusion) { if (BaseIndexOf(exclusion) >= 0) BaseRemove(exclusion.Path); } public void RemoveAt(int index) { BaseRemoveAt(index); } public void Remove(string path) { BaseRemove(path); } public void Clear() { BaseClear(); // Add custom code here. } } // Define the ExclusionElement. public class ExclusionElement : ConfigurationElement { public ExclusionElement(String path) { Path = path; } public ExclusionElement() { } [ConfigurationProperty("path", DefaultValue = "", IsRequired = true, IsKey = true)] public string Path { get { return (string)this["path"]; } set { this["path"] = value; } } public override int GetHashCode() { return this.Path.GetHashCode(); } public override bool Equals(object compareTo) { if (compareTo is ExclusionElement) return this.Path.Equals(((ExclusionElement)compareTo).Path, StringComparison.OrdinalIgnoreCase); else return false; } } }
//----------------------------------------------------------------------- // <copyright file="NameValueListBase.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>This is the base class from which readonly name/value</summary> //----------------------------------------------------------------------- using System; using System.ComponentModel; using Csla.Properties; using Csla.Core; using Csla.Serialization.Mobile; namespace Csla { /// <summary> /// This is the base class from which readonly name/value /// collections should be derived. /// </summary> /// <typeparam name="K">Type of the key values.</typeparam> /// <typeparam name="V">Type of the values.</typeparam> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [Serializable] public abstract class NameValueListBase<K, V> : Core.ReadOnlyBindingList<NameValueListBase<K, V>.NameValuePair>, ICloneable, Core.IBusinessObject, Server.IDataPortalTarget, IUseApplicationContext { /// <summary> /// Gets the current ApplicationContext /// </summary> protected ApplicationContext ApplicationContext { get; private set; } ApplicationContext Core.IUseApplicationContext.ApplicationContext { get => ApplicationContext; set { ApplicationContext = value; Initialize(); } } #region Core Implementation /// <summary> /// Returns the value corresponding to the /// specified key. /// </summary> /// <param name="key">Key value for which to retrieve a value.</param> public V Value(K key) { foreach (NameValuePair item in this) if (item.Key.Equals(key)) return item.Value; return default(V); } /// <summary> /// Returns the key corresponding to the /// first occurance of the specified value /// in the list. /// </summary> /// <param name="value">Value for which to retrieve the key.</param> public K Key(V value) { foreach (NameValuePair item in this) if (item.Value.Equals(value)) return item.Key; return default(K); } /// <summary> /// Gets a value indicating whether the list contains the /// specified key. /// </summary> /// <param name="key">Key value for which to search.</param> public bool ContainsKey(K key) { foreach (NameValuePair item in this) if (item.Key.Equals(key)) return true; return false; } /// <summary> /// Gets a value indicating whether the list contains the /// specified value. /// </summary> /// <param name="value">Value for which to search.</param> public bool ContainsValue(V value) { foreach (NameValuePair item in this) if (item.Value.Equals(value)) return true; return false; } /// <summary> /// Get the item for the first matching /// value in the collection. /// </summary> /// <param name="value"> /// Value to search for in the list. /// </param> /// <returns>Item from the list.</returns> public NameValuePair GetItemByValue(V value) { foreach (NameValuePair item in this) { if (item != null && item.Value.Equals(value)) { return item; } } return null; } /// <summary> /// Get the item for the first matching /// key in the collection. /// </summary> /// <param name="key"> /// Key to search for in the list. /// </param> /// <returns>Item from the list.</returns> public NameValuePair GetItemByKey(K key) { foreach (NameValuePair item in this) { if (item != null && item.Key.Equals(key)) { return item; } } return null; } #endregion /// <summary> /// Creates an instance of the type. /// </summary> protected NameValueListBase() { } #region Initialize /// <summary> /// Override this method to set up event handlers so user /// code in a partial class can respond to events raised by /// generated code. /// </summary> protected virtual void Initialize() { /* allows subclass to initialize events before any other activity occurs */ } #endregion #region NameValuePair class /// <summary> /// Contains a key and value pair. /// </summary> [Serializable()] public class NameValuePair : MobileObject { private K _key; private V _value; #if (ANDROID || IOS) || NETFX_CORE /// <summary> /// Creates an instance of the type. /// </summary> public NameValuePair() { } #else private NameValuePair() { } #endif /// <summary> /// The Key or Name value. /// </summary> public K Key { get { return _key; } } /// <summary> /// The Value corresponding to the key/name. /// </summary> public V Value { get { return _value; } } /// <summary> /// Creates an instance of the type. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public NameValuePair(K key, V value) { _key = key; _value = value; } /// <summary> /// Returns a string representation of the /// value for this item. /// </summary> public override string ToString() { return _value.ToString(); } /// <summary> /// Override this method to manually get custom field /// values from the serialization stream. /// </summary> /// <param name="info">Serialization info.</param> /// <param name="mode">Serialization mode.</param> protected override void OnGetState(SerializationInfo info, StateMode mode) { base.OnGetState(info, mode); info.AddValue("NameValuePair._key", _key); info.AddValue("NameValuePair._value", _value); } /// <summary> /// Override this method to manually set custom field /// values into the serialization stream. /// </summary> /// <param name="info">Serialization info.</param> /// <param name="mode">Serialization mode.</param> protected override void OnSetState(SerializationInfo info, StateMode mode) { base.OnSetState(info, mode); _key = info.GetValue<K>("NameValuePair._key"); _value = info.GetValue<V>("NameValuePair._value"); } } #endregion #region ICloneable object ICloneable.Clone() { return GetClone(); } /// <summary> /// Creates a clone of the object. /// </summary> /// <returns>A new object containing the exact data of the original object.</returns> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual object GetClone() { return Core.ObjectCloner.GetInstance(ApplicationContext).Clone(this); } /// <summary> /// Creates a clone of the object. /// </summary> public NameValueListBase<K, V> Clone() { return (NameValueListBase<K, V>)GetClone(); } #endregion #region Data Access private void DataPortal_Update() { throw new NotSupportedException(Resources.UpdateNotSupportedException); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "criteria")] [Delete] private void DataPortal_Delete(object criteria) { throw new NotSupportedException(Resources.DeleteNotSupportedException); } /// <summary> /// Called by the server-side DataPortal prior to calling the /// requested DataPortal_XYZ method. /// </summary> /// <param name="e">The DataPortalContext object passed to the DataPortal.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void DataPortal_OnDataPortalInvoke(DataPortalEventArgs e) { } /// <summary> /// Called by the server-side DataPortal after calling the /// requested DataPortal_XYZ method. /// </summary> /// <param name="e">The DataPortalContext object passed to the DataPortal.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void DataPortal_OnDataPortalInvokeComplete(DataPortalEventArgs e) { } /// <summary> /// Called by the server-side DataPortal if an exception /// occurs during data access. /// </summary> /// <param name="e">The DataPortalContext object passed to the DataPortal.</param> /// <param name="ex">The Exception thrown during data access.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void DataPortal_OnDataPortalException(DataPortalEventArgs e, Exception ex) { } #endregion #region IDataPortalTarget Members void Csla.Server.IDataPortalTarget.CheckRules() { } void Csla.Server.IDataPortalTarget.MarkAsChild() { } void Csla.Server.IDataPortalTarget.MarkNew() { } void Csla.Server.IDataPortalTarget.MarkOld() { } void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalInvoke(DataPortalEventArgs e) { this.DataPortal_OnDataPortalInvoke(e); } void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalInvokeComplete(DataPortalEventArgs e) { this.DataPortal_OnDataPortalInvokeComplete(e); } void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalException(DataPortalEventArgs e, Exception ex) { this.DataPortal_OnDataPortalException(e, ex); } void Csla.Server.IDataPortalTarget.Child_OnDataPortalInvoke(DataPortalEventArgs e) { } void Csla.Server.IDataPortalTarget.Child_OnDataPortalInvokeComplete(DataPortalEventArgs e) { } void Csla.Server.IDataPortalTarget.Child_OnDataPortalException(DataPortalEventArgs e, Exception ex) { } #endregion } }
// ------------------------------------------------------------------------------ // Copyright (c) 2015 Microsoft Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.OneDrive.Sdk { using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The type Item. /// </summary> [DataContract] public partial class Item { /// <summary> /// Gets or sets content. /// </summary> [DataMember(Name = "content", EmitDefaultValue = false, IsRequired = false)] public Stream Content { get; set; } /// <summary> /// Gets or sets created by. /// </summary> [DataMember(Name = "createdBy", EmitDefaultValue = false, IsRequired = false)] public IdentitySet CreatedBy { get; set; } /// <summary> /// Gets or sets created date time. /// </summary> [DataMember(Name = "createdDateTime", EmitDefaultValue = false, IsRequired = false)] public DateTimeOffset? CreatedDateTime { get; set; } /// <summary> /// Gets or sets c tag. /// </summary> [DataMember(Name = "cTag", EmitDefaultValue = false, IsRequired = false)] public string CTag { get; set; } /// <summary> /// Gets or sets description. /// </summary> [DataMember(Name = "description", EmitDefaultValue = false, IsRequired = false)] public string Description { get; set; } /// <summary> /// Gets or sets e tag. /// </summary> [DataMember(Name = "eTag", EmitDefaultValue = false, IsRequired = false)] public string ETag { get; set; } /// <summary> /// Gets or sets id. /// </summary> [DataMember(Name = "id", EmitDefaultValue = false, IsRequired = false)] public string Id { get; set; } /// <summary> /// Gets or sets last modified by. /// </summary> [DataMember(Name = "lastModifiedBy", EmitDefaultValue = false, IsRequired = false)] public IdentitySet LastModifiedBy { get; set; } /// <summary> /// Gets or sets last modified date time. /// </summary> [DataMember(Name = "lastModifiedDateTime", EmitDefaultValue = false, IsRequired = false)] public DateTimeOffset? LastModifiedDateTime { get; set; } /// <summary> /// Gets or sets name. /// </summary> [DataMember(Name = "name", EmitDefaultValue = false, IsRequired = false)] public string Name { get; set; } /// <summary> /// Gets or sets parent reference. /// </summary> [DataMember(Name = "parentReference", EmitDefaultValue = false, IsRequired = false)] public ItemReference ParentReference { get; set; } /// <summary> /// Gets or sets size. /// </summary> [DataMember(Name = "size", EmitDefaultValue = false, IsRequired = false)] public Int64? Size { get; set; } /// <summary> /// Gets or sets web url. /// </summary> [DataMember(Name = "webUrl", EmitDefaultValue = false, IsRequired = false)] public string WebUrl { get; set; } /// <summary> /// Gets or sets audio. /// </summary> [DataMember(Name = "audio", EmitDefaultValue = false, IsRequired = false)] public Audio Audio { get; set; } /// <summary> /// Gets or sets deleted. /// </summary> [DataMember(Name = "deleted", EmitDefaultValue = false, IsRequired = false)] public Deleted Deleted { get; set; } /// <summary> /// Gets or sets file. /// </summary> [DataMember(Name = "file", EmitDefaultValue = false, IsRequired = false)] public File File { get; set; } /// <summary> /// Gets or sets file system info. /// </summary> [DataMember(Name = "fileSystemInfo", EmitDefaultValue = false, IsRequired = false)] public FileSystemInfo FileSystemInfo { get; set; } /// <summary> /// Gets or sets folder. /// </summary> [DataMember(Name = "folder", EmitDefaultValue = false, IsRequired = false)] public Folder Folder { get; set; } /// <summary> /// Gets or sets image. /// </summary> [DataMember(Name = "image", EmitDefaultValue = false, IsRequired = false)] public Image Image { get; set; } /// <summary> /// Gets or sets location. /// </summary> [DataMember(Name = "location", EmitDefaultValue = false, IsRequired = false)] public Location Location { get; set; } /// <summary> /// Gets or sets open with. /// </summary> [DataMember(Name = "openWith", EmitDefaultValue = false, IsRequired = false)] public OpenWithSet OpenWith { get; set; } /// <summary> /// Gets or sets photo. /// </summary> [DataMember(Name = "photo", EmitDefaultValue = false, IsRequired = false)] public Photo Photo { get; set; } /// <summary> /// Gets or sets search result. /// </summary> [DataMember(Name = "searchResult", EmitDefaultValue = false, IsRequired = false)] public SearchResult SearchResult { get; set; } /// <summary> /// Gets or sets special folder. /// </summary> [DataMember(Name = "specialFolder", EmitDefaultValue = false, IsRequired = false)] public SpecialFolder SpecialFolder { get; set; } /// <summary> /// Gets or sets video. /// </summary> [DataMember(Name = "video", EmitDefaultValue = false, IsRequired = false)] public Video Video { get; set; } /// <summary> /// Gets or sets permissions. /// </summary> [DataMember(Name = "permissions", EmitDefaultValue = false, IsRequired = false)] [JsonConverter(typeof(InterfaceConverter<PermissionsCollectionPage>))] public IPermissionsCollectionPage Permissions { get; set; } /// <summary> /// Gets or sets versions. /// </summary> [DataMember(Name = "versions", EmitDefaultValue = false, IsRequired = false)] [JsonConverter(typeof(InterfaceConverter<VersionsCollectionPage>))] public IVersionsCollectionPage Versions { get; set; } /// <summary> /// Gets or sets children. /// </summary> [DataMember(Name = "children", EmitDefaultValue = false, IsRequired = false)] [JsonConverter(typeof(InterfaceConverter<ChildrenCollectionPage>))] public IChildrenCollectionPage Children { get; set; } /// <summary> /// Gets or sets thumbnails. /// </summary> [DataMember(Name = "thumbnails", EmitDefaultValue = false, IsRequired = false)] [JsonConverter(typeof(InterfaceConverter<ThumbnailsCollectionPage>))] public IThumbnailsCollectionPage Thumbnails { get; set; } /// <summary> /// Gets or sets additional data. /// </summary> [JsonExtensionData(ReadData = true)] public IDictionary<string, object> AdditionalData { get; set; } } }
using System; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using OmniSharp.FileWatching; using OmniSharp.Models; using OmniSharp.Models.UpdateBuffer; using OmniSharp.Services; using TestUtility; using Xunit; using Xunit.Abstractions; namespace OmniSharp.Tests { public class BufferManagerFacts : AbstractTestFixture { public BufferManagerFacts(ITestOutputHelper output) : base(output) { } [Fact] public async Task UpdateBufferIgnoresVoidRequests() { using (var host = CreateOmniSharpHost(new TestFile("test.cs", "class C {}"))) { Assert.Single(host.Workspace.CurrentSolution.Projects); Assert.Single(host.Workspace.CurrentSolution.Projects.ElementAt(0).Documents); await host.Workspace.BufferManager.UpdateBufferAsync(new Request() { }); Assert.Single(host.Workspace.CurrentSolution.Projects); Assert.Single(host.Workspace.CurrentSolution.Projects.ElementAt(0).Documents); await host.Workspace.BufferManager.UpdateBufferAsync(new Request() { FileName = "", Buffer = "enum E {}" }); Assert.Single(host.Workspace.CurrentSolution.Projects); Assert.Single(host.Workspace.CurrentSolution.Projects.ElementAt(0).Documents); } } [Fact] public async Task UpdateBufferIgnoresNonCsFilePathsThatDontMatchAProjectPath() { var workspace = GetWorkspaceWithProjects(); await workspace.BufferManager.UpdateBufferAsync(new Request() { FileName = Path.Combine("some", " path.fs"), Buffer = "enum E {}" }); var documents = workspace.GetDocuments(Path.Combine("some", "path.fs")); Assert.Empty(documents); } [Fact] public async Task UpdateBufferFindsProjectBasedOnPath() { var workspace = GetWorkspaceWithProjects(); await workspace.BufferManager.UpdateBufferAsync(new Request() { FileName = Path.Combine("src", "newFile.cs"), Buffer = "enum E {}" }); var documents = workspace.GetDocuments(Path.Combine("src", "newFile.cs")); Assert.Equal(2, documents.Count()); foreach (var document in documents) { Assert.Equal(Path.Combine("src", "project.json"), document.Project.FilePath); } } [Fact] public async Task UpdateBufferReadsFromDisk() { const string newCode = "public class MyClass {}"; var fileName = Path.GetTempPath() + Guid.NewGuid().ToString() + ".cs"; var testFile = new TestFile(fileName, string.Empty); using (var host = CreateOmniSharpHost(testFile)) { File.WriteAllText(fileName, newCode); var request = new UpdateBufferRequest { FileName = fileName, FromDisk = true }; await host.Workspace.BufferManager.UpdateBufferAsync(request); var document = host.Workspace.GetDocument(fileName); var text = await document.GetTextAsync(); Assert.Equal(newCode, text.ToString()); } } [Fact] public async Task UpdateBufferFindsProjectBasedOnNearestPath() { var workspace = new OmniSharpWorkspace( new HostServicesAggregator( Enumerable.Empty<IHostServicesProvider>(), new LoggerFactory()), new LoggerFactory(), new ManualFileSystemWatcher()); TestHelpers.AddProjectToWorkspace(workspace, filePath: Path.Combine("src", "root", "foo.csproj"), frameworks: null, testFiles: new[] { new TestFile(Path.Combine("src", "root", "foo.cs"), "class C1 {}") }); TestHelpers.AddProjectToWorkspace(workspace, filePath: Path.Combine("src", "root", "foo", "bar", "insane.csproj"), frameworks: null, testFiles: new[] { new TestFile(Path.Combine("src", "root", "foo", "bar", "nested", "code.cs"), "class C2 {}") }); await workspace.BufferManager.UpdateBufferAsync(new Request() { FileName = Path.Combine("src", "root", "bar.cs"), Buffer = "enum E {}" }); var documents = workspace.GetDocuments(Path.Combine("src", "root", "bar.cs")); Assert.Single(documents); Assert.Equal(Path.Combine("src", "root", "foo.csproj"), documents.ElementAt(0).Project.FilePath); Assert.Equal(2, documents.ElementAt(0).Project.Documents.Count()); await workspace.BufferManager.UpdateBufferAsync(new Request() { FileName = Path.Combine("src", "root", "foo", "bar", "nested", "paths", "dance.cs"), Buffer = "enum E {}" }); documents = workspace.GetDocuments(Path.Combine("src", "root", "foo", "bar", "nested", "paths", "dance.cs")); Assert.Single(documents); Assert.Equal(Path.Combine("src", "root", "foo", "bar", "insane.csproj"), documents.ElementAt(0).Project.FilePath); Assert.Equal(2, documents.ElementAt(0).Project.Documents.Count()); } [Fact] public async Task UpdateRequestHandleSerialChanges() { var workspace = GetWorkspaceWithProjects(); await workspace.BufferManager.UpdateBufferAsync(new Request() { FileName = Path.Combine("src", "a.cs"), ApplyChangesTogether = false, Changes = new LinePositionSpanTextChange[] { // class C {} -> interface C {} new LinePositionSpanTextChange() { StartLine = 0, StartColumn = 0, EndLine = 0, EndColumn = 5, NewText = "interface" }, // interface C {} -> interface I {} // note: this change is relative to the previous // change having been applied new LinePositionSpanTextChange() { StartLine = 0, StartColumn = 10, EndLine = 0, EndColumn = 11, NewText = "I" } } }); var document = workspace.GetDocument(Path.Combine("src", "a.cs")); var text = await document.GetTextAsync(); Assert.Equal("interface I {}", text.ToString()); } private static OmniSharpWorkspace GetWorkspaceWithProjects() { var workspace = new OmniSharpWorkspace( new HostServicesAggregator( Enumerable.Empty<IHostServicesProvider>(), new LoggerFactory()), new LoggerFactory(), new ManualFileSystemWatcher()); TestHelpers.AddProjectToWorkspace(workspace, filePath: Path.Combine("src", "project.json"), frameworks: new[] { "dnx451", "dnxcore50" }, testFiles: new[] { new TestFile(Path.Combine("src", "a.cs"), "class C {}") }); TestHelpers.AddProjectToWorkspace(workspace, filePath: Path.Combine("test", "project.json"), frameworks: new[] { "dnx451", "dnxcore50" }, testFiles: new[] { new TestFile(Path.Combine("test", "b.cs"), "class C {}") }); Assert.Equal(4, workspace.CurrentSolution.Projects.Count()); foreach (var project in workspace.CurrentSolution.Projects) { Assert.Single(project.Documents); } return workspace; } [Fact] public async Task UpdateRequestHandleBulkChanges() { var testFileName = "test.cs"; var testCode = @"using System; using System.Collections.Generic; using System.Linq; namespace N { class C { List<string> P { get; set; } } } "; var expectedCode = @"using System.Collections.Generic; namespace N { class C { List<string> P { get; set; } } } "; using (var host = CreateOmniSharpHost(new TestFile(testFileName, testCode))) { await host.Workspace.BufferManager.UpdateBufferAsync(new Request() { FileName = testFileName, ApplyChangesTogether = true, Changes = new LinePositionSpanTextChange[] { // Remove `using System;` new LinePositionSpanTextChange() { StartLine = 0, StartColumn = 0, EndLine = 1, EndColumn = 0, NewText = "" }, // Remove `using System.Linq;` new LinePositionSpanTextChange() { StartLine = 2, StartColumn = 0, EndLine = 3, EndColumn = 0, NewText = "" } } }); var document = host.Workspace.GetDocument(testFileName); var text = await document.GetTextAsync(); Assert.Equal(expectedCode, text.ToString()); } } } }
// // System.Web.UI.WebControls.ButtonColumn.cs // // Authors: // Gaurav Vaish (gvaish@iitk.ac.in) // Andreas Nahr (ClassDevelopment@A-SoftTech.com) // // (C) Gaurav Vaish (2002) // (C) 2003 Andreas Nahr // // // 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.ComponentModel; using System.Web; using System.Web.UI; namespace System.Web.UI.WebControls { public class ButtonColumn : DataGridColumn { private PropertyDescriptor textFieldDescriptor; public ButtonColumn(): base() { } public override void Initialize() { base.Initialize(); textFieldDescriptor = null; } public override void InitializeCell(TableCell cell, int columnIndex, ListItemType itemType) { base.InitializeCell(cell, columnIndex, itemType); if (Enum.IsDefined(typeof(ListItemType), itemType) && itemType != ListItemType.Footer && itemType != ListItemType.Header) { WebControl toDisplay = null; if(ButtonType == ButtonColumnType.PushButton) { Button b = new Button(); b.Text = Text; b.CommandName = CommandName; b.CausesValidation = false; toDisplay = b; } else { LinkButton lb = new DataGridLinkButton(); lb.Text = Text; lb.CommandName = CommandName; lb.CausesValidation = false; toDisplay = lb; } if(DataTextField.Length > 0) { toDisplay.DataBinding += new EventHandler(OnDataBindButtonColumn); } cell.Controls.Add(toDisplay); } } private void OnDataBindButtonColumn(object sender, EventArgs e) { Control ctrl = (Control)sender; object item = ((DataGridItem)ctrl.NamingContainer).DataItem; if(textFieldDescriptor == null) { textFieldDescriptor = TypeDescriptor.GetProperties(item).Find(DataTextField, true); if(textFieldDescriptor == null && !DesignMode) throw new HttpException(HttpRuntime.FormatResourceString("Field_Not_Found", DataTextField)); } string text; if(textFieldDescriptor != null) { text = FormatDataTextValue(textFieldDescriptor.GetValue(item)); } else { text = "Sample_DataBound_Text"; } if(ctrl is LinkButton) { ((LinkButton)ctrl).Text = text; } else { ((Button)ctrl).Text = text; } } protected virtual string FormatDataTextValue(object dataTextValue) { string retVal = null; if(dataTextValue != null) { if(DataTextFormatString.Length > 0) { retVal = String.Format(DataTextFormatString, dataTextValue); } else { retVal = dataTextValue.ToString(); } } return retVal; } // LAMESPEC The framework uses Description values for metadata here. However they should be WebSysDescriptions // because all metadata in this namespace has WebSysDescriptions #if !NET_2_0 [Description ("The type of button used in this column.")] #endif [DefaultValue (typeof (ButtonColumnType), "LinkButton"), WebCategory ("Misc")] public virtual ButtonColumnType ButtonType { get { object o = ViewState["ButtonType"]; if(o!=null) return (ButtonColumnType)o; return ButtonColumnType.LinkButton; } set { if(!System.Enum.IsDefined(typeof(ButtonColumnType), value)) throw new ArgumentException(); ViewState["ButtonType"] = value; } } #if !NET_2_0 [Description ("The command assigned to this column.")] #endif [DefaultValue (""), WebCategory ("Misc")] public virtual string CommandName { get { string cn = (string)ViewState["CommandName"]; if(cn!=null) return cn; return String.Empty; } set { ViewState["CommandName"] = value; } } #if !NET_2_0 [Description ("The datafield that is bound to the text property.")] #endif [DefaultValue (""), WebCategory ("Misc")] public virtual string DataTextField { get { string dtf = (string)ViewState["DataTextField"]; if(dtf!=null) return dtf; return String.Empty; } set { ViewState["DataTextField"] = value; } } #if !NET_2_0 [Description ("A format that is applied to the bound text property.")] #endif [DefaultValue (""), WebCategory ("Misc")] public virtual string DataTextFormatString { get { string dtfs = (string)ViewState["DataTextFormatString"]; if(dtfs!=null) return dtfs; return String.Empty; } set { ViewState["DataTextFormatString"] = value; } } #if NET_2_0 [Localizable (true)] #else [Description ("The text used for this button.")] #endif [DefaultValue (""), WebCategory ("Misc")] public virtual string Text { get { string text = (string)ViewState["Text"]; if(text!=null) return text; return String.Empty; } set { ViewState["Text"] = value; } } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Globalization; using Microsoft.VisualStudio.Shell; namespace Microsoft.PythonTools.Django { /// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="ProvideEditorExtensionAttribute"]' /> /// <devdoc> /// This attribute associates a file extension to a given editor factory. /// The editor factory may be specified as either a GUID or a type and /// is placed on a package. /// /// This differs from the normal one in that more than one extension can be supplied and /// a linked editor GUID can be supplied. /// </devdoc> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] internal sealed class ProvideEditorExtension2Attribute : RegistrationAttribute { private Guid _factory; private string _extension; private int _priority; private Guid _project; private string _templateDir; private int _resId; private bool _editorFactoryNotify; private string _editorName; private Guid _linkedEditorGuid; private readonly string[] _extensions; /// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="ProvideEditorExtensionAttribute.ProvideEditorExtensionAttribute"]' /> /// <devdoc> /// Creates a new attribute. /// </devdoc> public ProvideEditorExtension2Attribute(object factoryType, string extension, int priority, params string[] extensions) { // figure out what type of object they passed in and get the GUID from it if (factoryType is string) this._factory = new Guid((string)factoryType); else if (factoryType is Type) this._factory = ((Type)factoryType).GUID; else if (factoryType is Guid) this._factory = (Guid)factoryType; else throw new ArgumentException(string.Format(Resources.Culture, "invalid factory type: {0}", factoryType)); _extension = extension; _priority = priority; _project = Guid.Empty; _templateDir = ""; _resId = 0; _editorFactoryNotify = false; _extensions = extensions; } /// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="ProvideEditorExtensionAttribute.Extension"]' /> /// <devdoc> /// The file extension of the file. /// </devdoc> public string Extension { get { return _extension; } } /// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="ProvideEditorExtensionAttribute.Factory"]' /> /// <devdoc> /// The editor factory guid. /// </devdoc> public Guid Factory { get { return _factory; } } /// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="ProvideEditorExtensionAttribute.Priority"]' /> /// <devdoc> /// The priority of this extension registration. /// </devdoc> public int Priority { get { return _priority; } } /// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="ProvideEditorExtensionAttribute.ProjectGuid"]/*' /> public string ProjectGuid { set { _project = new System.Guid(value); } get { return _project.ToString(); } } public string LinkedEditorGuid { get { return _linkedEditorGuid.ToString(); } set { _linkedEditorGuid = new System.Guid(value); } } /// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="ProvideEditorExtensionAttribute.EditorFactoryNotify"]/*' /> public bool EditorFactoryNotify { get { return this._editorFactoryNotify; } set { this._editorFactoryNotify = value; } } /// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="ProvideEditorExtensionAttribute.TemplateDir"]/*' /> public string TemplateDir { get { return _templateDir; } set { _templateDir = value; } } /// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="ProvideEditorExtensionAttribute.NameResourceID"]/*' /> public int NameResourceID { get { return _resId; } set { _resId = value; } } /// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="ProvideEditorExtensionAttribute.DefaultName"]/*' /> public string DefaultName { get { return _editorName; } set { _editorName = value; } } /// <summary> /// The reg key name of this extension. /// </summary> private string RegKeyName { get { return string.Format(CultureInfo.InvariantCulture, "Editors\\{0}", Factory.ToString("B")); } } /// <summary> /// The reg key name of the project. /// </summary> private string ProjectRegKeyName(RegistrationContext context) { return string.Format(CultureInfo.InvariantCulture, "Projects\\{0}\\AddItemTemplates\\TemplateDirs\\{1}", _project.ToString("B"), context.ComponentType.GUID.ToString("B")); } private string EditorFactoryNotifyKey { get { return string.Format(CultureInfo.InvariantCulture, "Projects\\{0}\\FileExtensions\\{1}", _project.ToString("B"), Extension); } } /// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="Register"]' /> /// <devdoc> /// Called to register this attribute with the given context. The context /// contains the location where the registration inforomation should be placed. /// it also contains such as the type being registered, and path information. /// /// This method is called both for registration and unregistration. The difference is /// that unregistering just uses a hive that reverses the changes applied to it. /// </devdoc> public override void Register(RegistrationContext context) { using (Key editorKey = context.CreateKey(RegKeyName)) { if (!string.IsNullOrEmpty(DefaultName)) { editorKey.SetValue(null, DefaultName); } if (0 != _resId) editorKey.SetValue("DisplayName", "#" + _resId.ToString(CultureInfo.InvariantCulture)); if (_linkedEditorGuid != Guid.Empty) { editorKey.SetValue("LinkedEditorGuid", _linkedEditorGuid.ToString("B")); } editorKey.SetValue("Package", context.ComponentType.GUID.ToString("B")); } using (Key extensionKey = context.CreateKey(RegKeyName + "\\Extensions")) { extensionKey.SetValue(Extension.Substring(1), Priority); if (_extensions != null && _extensions.Length > 0) { foreach (var extension in _extensions) { var extensionAndPri = extension.Split(':'); int pri; if (extensionAndPri.Length != 2 || !Int32.TryParse(extensionAndPri[1], out pri)) { throw new InvalidOperationException("Expected extension:priority"); } extensionKey.SetValue(extensionAndPri[0], pri); } } } // Build the path of the registry key for the "Add file to project" entry if (_project != Guid.Empty) { string prjRegKey = ProjectRegKeyName(context) + "\\/1"; using (Key projectKey = context.CreateKey(prjRegKey)) { if (0 != _resId) projectKey.SetValue("", "#" + _resId.ToString(CultureInfo.InvariantCulture)); if (_templateDir.Length != 0) { Uri url = new Uri(context.ComponentType.Assembly.CodeBase); string templates = url.LocalPath; templates = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(templates), _templateDir); templates = context.EscapePath(System.IO.Path.GetFullPath(templates)); projectKey.SetValue("TemplatesDir", templates); } projectKey.SetValue("SortPriority", Priority); } } // Register the EditorFactoryNotify if (EditorFactoryNotify) { // The IVsEditorFactoryNotify interface is called by the project system, so it doesn't make sense to // register it if there is no project associated to this editor. if (_project == Guid.Empty) throw new ArgumentException("project"); // Create the registry key using (Key edtFactoryNotifyKey = context.CreateKey(EditorFactoryNotifyKey)) { edtFactoryNotifyKey.SetValue("EditorFactoryNotify", Factory.ToString("B")); } } } /// <include file='doc\ProvideEditorExtensionAttribute.uex' path='docs/doc[@for="Unregister"]' /> /// <devdoc> /// Unregister this editor. /// </devdoc> /// <param name="context"></param> public override void Unregister(RegistrationContext context) { context.RemoveKey(RegKeyName); if (_project != Guid.Empty) { context.RemoveKey(ProjectRegKeyName(context)); if (EditorFactoryNotify) context.RemoveKey(EditorFactoryNotifyKey); } } } }
using System; using System.Diagnostics; using System.Text.RegularExpressions; using System.Threading.Tasks; using Eto.Drawing; using Eto.Forms; // Switch between using floats or doubles for input position (Match with FastNoiseLite.cs) using FNfloat = System.Single; //using FNfloat = System.Double; class Program { [STAThread] public static void Main(string[] args) { new Application().Run(new FastNoiseLiteGUI()); } } public class FastNoiseLiteGUI : Form { private Button GenerateButton; private Button UpButton; private Button DownButton; private Button ScrollButton; private NumericStepper PreviewWidth; private NumericStepper PreviewHeight; private CheckBox Invert; private CheckBox Is3D; private CheckBox VisualiseDomainWarp; private DropDown NoiseType; private DropDown RotationType3D; private NumericStepper Seed; private NumericStepper Frequency; private DropDown FractalType; private NumericStepper FractalOctaves; private NumericStepper FractalLacunarity; private NumericStepper FractalGain; private NumericStepper FractalWeightedStrength; private NumericStepper FractalPingPongStrength; private DropDown CellularDistanceFunction; private DropDown CellularReturnType; private NumericStepper CellularJitter; private DropDown DomainWarp; private DropDown DomainWarpRotationType3D; private NumericStepper DomainWarpAmplitude; private NumericStepper DomainWarpFrequency; private DropDown DomainWarpFractal; private NumericStepper DomainWarpFractalOctaves; private NumericStepper DomainWarpFractalLacunarity; private NumericStepper DomainWarpFractalGain; private Bitmap Bitmap; private ImageView Image; private int[] ImageData; private Label Time; private Label Min; private Label Max; private Label Mean; private Label ExtraInfo; private bool isScrolling = false; private float zPos = 0; private Size previewStartSize = new Size(768, 768); private Size windowSizeOffset = new Size(334, 52); public FastNoiseLiteGUI() { Title = "FastNoiseLite GUI"; Resizable = false; ImageData = new int[1]; // Create main layout, makes controls and result appear side by side var mainLayout = new StackLayout(); mainLayout.Orientation = Orientation.Horizontal; mainLayout.Spacing = 5; mainLayout.Padding = new Padding(10); mainLayout.HorizontalContentAlignment = HorizontalAlignment.Left; // Control panel var controlPanel = new StackLayout(); controlPanel.Orientation = Orientation.Vertical; controlPanel.Spacing = 5; { // Generate, Up, Down { var layout = new StackLayout() { Orientation = Orientation.Horizontal, Spacing = 2 }; GenerateButton = new Button(); GenerateButton.Text = "Generate"; GenerateButton.Click += Generate; GenerateButton.Width = 90; layout.Items.Add(GenerateButton); UpButton = new Button(); UpButton.Text = "Up"; UpButton.Enabled = false; UpButton.Click += OnUp; UpButton.Width = 70; layout.Items.Add(UpButton); DownButton = new Button(); DownButton.Text = "Down"; DownButton.Enabled = false; DownButton.Click += OnDown; DownButton.Width = 70; layout.Items.Add(DownButton); ScrollButton = new Button(); ScrollButton.Text = "Scroll"; ScrollButton.Enabled = false; ScrollButton.Click += OnScroll; ScrollButton.Width = 70; layout.Items.Add(ScrollButton); controlPanel.Items.Add(layout); } // Control table var table = new TableLayout(); table.Spacing = new Size(5, 5); // Preview controls { // Preview size dropdown { var stack = new StackLayout(); stack.Orientation = Orientation.Horizontal; stack.Spacing = 2; PreviewWidth = new NumericStepper { Value = previewStartSize.Width, Increment = 128 }; PreviewWidth.ValueChanged += Generate; stack.Items.Add(new StackLayoutItem(PreviewWidth)); PreviewHeight = new NumericStepper { Value = previewStartSize.Height, Increment = 128 }; PreviewHeight.ValueChanged += Generate; stack.Items.Add(new StackLayoutItem(PreviewHeight)); AddToTableWithLabel(table, stack, "Preview Size"); } // Invert Invert = new CheckBox(); Invert.CheckedChanged += Generate; AddToTableWithLabel(table, Invert, "Invert"); // 3D Is3D = new CheckBox(); Is3D.CheckedChanged += OnUIUpdate; AddToTableWithLabel(table, Is3D, "3D"); // Visualise Domain Warp VisualiseDomainWarp = new CheckBox(); VisualiseDomainWarp.CheckedChanged += OnUIUpdate; AddToTableWithLabel(table, VisualiseDomainWarp, "Visualise Domain Warp"); } AddHeadingToTable(table, "General"); // General properties { // Noise Type { NoiseType = new DropDown(); foreach (var name in Enum.GetNames(typeof(FastNoiseLite.NoiseType))) { NoiseType.Items.Add(FormatReadable(name)); } NoiseType.SelectedIndex = (int)FastNoiseLite.NoiseType.OpenSimplex2; NoiseType.SelectedIndexChanged += OnUIUpdate; AddToTableWithLabel(table, NoiseType, "Noise Type"); } // Rotation Type 3D { RotationType3D = new DropDown(); foreach (var name in Enum.GetNames(typeof(FastNoiseLite.RotationType3D))) { RotationType3D.Items.Add(FormatReadable(name)); } RotationType3D.SelectedIndex = (int)FastNoiseLite.RotationType3D.None; RotationType3D.SelectedIndexChanged += OnUIUpdate; AddToTableWithLabel(table, RotationType3D, "Rotation Type 3D"); } // Seed Seed = new NumericStepper { Value = 1337 }; Seed.ValueChanged += Generate; AddToTableWithLabel(table, Seed, "Seed"); // Frequency Frequency = new NumericStepper { Value = 0.02, DecimalPlaces = 3, Increment = 0.005 }; Frequency.ValueChanged += Generate; AddToTableWithLabel(table, Frequency, "Frequency"); } // Add fractal label AddHeadingToTable(table, "Fractal"); { // Fractal type { FractalType = new DropDown(); foreach (var name in Enum.GetNames(typeof(FastNoiseLite.FractalType))) { if (name.StartsWith("DomainWarp")) break; FractalType.Items.Add(FormatReadable(name)); } FractalType.SelectedIndex = (int)FastNoiseLite.FractalType.FBm; FractalType.SelectedIndexChanged += OnUIUpdate; AddToTableWithLabel(table, FractalType, "Type"); } // Octaves FractalOctaves = new NumericStepper { Value = 5 }; FractalOctaves.ValueChanged += Generate; AddToTableWithLabel(table, FractalOctaves, "Octaves"); // Lacunarity FractalLacunarity = new NumericStepper { Value = 2.0, DecimalPlaces = 2, Increment = 0.1 }; FractalLacunarity.ValueChanged += Generate; AddToTableWithLabel(table, FractalLacunarity, "Lacunarity"); // Gain FractalGain = new NumericStepper { Value = 0.5, DecimalPlaces = 2, Increment = 0.1 }; FractalGain.ValueChanged += Generate; AddToTableWithLabel(table, FractalGain, "Gain"); // Weighted Strength FractalWeightedStrength = new NumericStepper { Value = 0.0, DecimalPlaces = 2, Increment = 0.1 }; FractalWeightedStrength.ValueChanged += Generate; AddToTableWithLabel(table, FractalWeightedStrength, "Weighted Strength"); // Ping Pong Strength FractalPingPongStrength = new NumericStepper { Value = 2.0, DecimalPlaces = 2, Increment = 0.1 }; FractalPingPongStrength.ValueChanged += Generate; AddToTableWithLabel(table, FractalPingPongStrength, "Ping Pong Strength"); } // Add fractal label AddHeadingToTable(table, "Cellular"); { // Distance Function { CellularDistanceFunction = new DropDown(); foreach (var name in Enum.GetNames(typeof(FastNoiseLite.CellularDistanceFunction))) { CellularDistanceFunction.Items.Add(FormatReadable(name)); } CellularDistanceFunction.SelectedIndex = (int)FastNoiseLite.CellularDistanceFunction.EuclideanSq; CellularDistanceFunction.SelectedIndexChanged += Generate; AddToTableWithLabel(table, CellularDistanceFunction, "Distance Function"); } // Return Type { CellularReturnType = new DropDown(); foreach (var name in Enum.GetNames(typeof(FastNoiseLite.CellularReturnType))) { CellularReturnType.Items.Add(FormatReadable(name)); } CellularReturnType.SelectedIndex = (int)FastNoiseLite.CellularReturnType.Distance; CellularReturnType.SelectedIndexChanged += Generate; AddToTableWithLabel(table, CellularReturnType, "Return Type"); } // Jitter CellularJitter = new NumericStepper() { Value = 1.0, DecimalPlaces = 2, Increment = 0.1 }; CellularJitter.ValueChanged += Generate; AddToTableWithLabel(table, CellularJitter, "Jitter"); } // Add fractal label AddHeadingToTable(table, "Domain Warp"); { // Domain Warp Dropdown { DomainWarp = new DropDown(); DomainWarp.Items.Add("None"); foreach (var name in Enum.GetNames(typeof(FastNoiseLite.DomainWarpType))) { DomainWarp.Items.Add(FormatReadable(name)); } DomainWarp.SelectedIndex = 0; DomainWarp.SelectedIndexChanged += OnUIUpdate; AddToTableWithLabel(table, DomainWarp, "Type"); } // Domain Warp Rotation Type 3D { DomainWarpRotationType3D = new DropDown(); foreach (var name in Enum.GetNames(typeof(FastNoiseLite.RotationType3D))) { DomainWarpRotationType3D.Items.Add(FormatReadable(name)); } DomainWarpRotationType3D.SelectedIndex = (int)FastNoiseLite.RotationType3D.None; DomainWarpRotationType3D.SelectedIndexChanged += OnUIUpdate; AddToTableWithLabel(table, DomainWarpRotationType3D, "Rotation Type 3D"); } // Amplitude DomainWarpAmplitude = new NumericStepper { Value = 30.0, DecimalPlaces = 2, Increment = 5 }; DomainWarpAmplitude.ValueChanged += Generate; AddToTableWithLabel(table, DomainWarpAmplitude, "Amplitude"); // Frequency DomainWarpFrequency = new NumericStepper { Value = 0.005, DecimalPlaces = 3, Increment = 0.005 }; DomainWarpFrequency.ValueChanged += Generate; AddToTableWithLabel(table, DomainWarpFrequency, "Frequency"); } // Add domain warp fractal label AddHeadingToTable(table, "Domain Warp Fractal"); { // Domain Warp Fractal Dropdown { DomainWarpFractal = new DropDown(); DomainWarpFractal.Items.Add("None"); foreach (var name in Enum.GetNames(typeof(FastNoiseLite.FractalType))) { if (!name.StartsWith("DomainWarp")) continue; DomainWarpFractal.Items.Add(FormatReadable(name), name); } DomainWarpFractal.SelectedIndex = 0; DomainWarpFractal.SelectedIndexChanged += OnUIUpdate; AddToTableWithLabel(table, DomainWarpFractal, "Fractal Type"); } // Octaves DomainWarpFractalOctaves = new NumericStepper { Value = 5 }; DomainWarpFractalOctaves.ValueChanged += Generate; AddToTableWithLabel(table, DomainWarpFractalOctaves, "Octaves"); // Lacunarity DomainWarpFractalLacunarity = new NumericStepper { Value = 2.0, DecimalPlaces = 2, Increment = 0.1 }; DomainWarpFractalLacunarity.ValueChanged += Generate; AddToTableWithLabel(table, DomainWarpFractalLacunarity, "Lacunarity"); // Gain DomainWarpFractalGain = new NumericStepper { Value = 0.5, DecimalPlaces = 2, Increment = 0.1 }; DomainWarpFractalGain.ValueChanged += Generate; AddToTableWithLabel(table, DomainWarpFractalGain, "Gain"); } // Add table to the controls panel Scrollable scrollPanel = new Scrollable(); scrollPanel.Content = table; scrollPanel.Border = BorderType.None; scrollPanel.Padding = new Padding(0); controlPanel.Items.Add(scrollPanel); // Add save and github buttons { var stack = new StackLayout(); stack.Orientation = Orientation.Horizontal; stack.Spacing = 5; stack.Padding = new Padding(10); var save = new Button { Text = "Save" }; save.Click += Save; stack.Items.Add(new StackLayoutItem(save)); var github = new Button { Text = "GitHub" }; github.Click += (sender, e) => { Process.Start(new ProcessStartInfo("https://github.com/Auburn/FastNoise") { UseShellExecute = true }); }; stack.Items.Add(new StackLayoutItem(github)); controlPanel.Items.Add(stack); } } // Add control panel to layout mainLayout.Items.Add(controlPanel); // Add output panel { var layout = new StackLayout(); layout.Orientation = Orientation.Vertical; // Info { var infoPane = new StackLayout(); infoPane.Orientation = Orientation.Horizontal; infoPane.Spacing = 15; // First info column { var column = new StackLayout(); column.Orientation = Orientation.Vertical; // Time Time = new Label { Text = "Time (ms): N/A" }; column.Items.Add(new StackLayoutItem(Time)); // Mean Mean = new Label { Text = "Mean: N/A" }; column.Items.Add(new StackLayoutItem(Mean)); infoPane.Items.Add(column); } // Second info column { var column = new StackLayout(); column.Orientation = Orientation.Vertical; // Time Min = new Label { Text = "Min: N/A" }; column.Items.Add(new StackLayoutItem(Min)); // Mean Max = new Label { Text = "Max: N/A" }; column.Items.Add(new StackLayoutItem(Max)); infoPane.Items.Add(column); } // Third entry { ExtraInfo = new Label(); infoPane.Items.Add(ExtraInfo); } layout.Items.Add(new StackLayoutItem(infoPane)); } Image = new ImageView(); //var imageScroll = new Scrollable(); //imageScroll.Content = Image; layout.Items.Add(new StackLayoutItem(Image)); mainLayout.Items.Add(layout); } // Display the layout Content = mainLayout; // Ensure UI state is valid then it generates OnUIUpdate(); } async private void Generate(object sender = null, EventArgs e = null) { if (isScrolling && sender != ScrollButton) return; do { // Create noise generators var genNoise = new FastNoiseLite(); var warpNoise = new FastNoiseLite(); int w = (int)PreviewWidth.Value; int h = (int)PreviewHeight.Value; if (w <= 0 || h <= 0) { return; } genNoise.SetNoiseType((FastNoiseLite.NoiseType)NoiseType.SelectedIndex); genNoise.SetRotationType3D((FastNoiseLite.RotationType3D)RotationType3D.SelectedIndex); genNoise.SetSeed((int)Seed.Value); genNoise.SetFrequency((float)Frequency.Value); genNoise.SetFractalType((FastNoiseLite.FractalType)FractalType.SelectedIndex); genNoise.SetFractalOctaves((int)FractalOctaves.Value); genNoise.SetFractalLacunarity((float)FractalLacunarity.Value); genNoise.SetFractalGain((float)FractalGain.Value); genNoise.SetFractalWeightedStrength((float)FractalWeightedStrength.Value); genNoise.SetFractalPingPongStrength((float)FractalPingPongStrength.Value); genNoise.SetCellularDistanceFunction((FastNoiseLite.CellularDistanceFunction)CellularDistanceFunction.SelectedIndex); genNoise.SetCellularReturnType((FastNoiseLite.CellularReturnType)CellularReturnType.SelectedIndex); genNoise.SetCellularJitter((float)CellularJitter.Value); warpNoise.SetSeed((int)Seed.Value); warpNoise.SetDomainWarpType((FastNoiseLite.DomainWarpType)DomainWarp.SelectedIndex - 1); warpNoise.SetRotationType3D((FastNoiseLite.RotationType3D)DomainWarpRotationType3D.SelectedIndex); warpNoise.SetDomainWarpAmp((float)DomainWarpAmplitude.Value); warpNoise.SetFrequency((float)DomainWarpFrequency.Value); warpNoise.SetFractalType((FastNoiseLite.FractalType)Enum.Parse(typeof(FastNoiseLite.FractalType), DomainWarpFractal.SelectedKey)); warpNoise.SetFractalOctaves((int)DomainWarpFractalOctaves.Value); warpNoise.SetFractalLacunarity((float)DomainWarpFractalLacunarity.Value); warpNoise.SetFractalGain((float)DomainWarpFractalGain.Value); if (ImageData.Length != w * h) { ImageData = new int[w * h]; } float noise; float minN = float.MaxValue; float maxN = float.MinValue; float avg = 0; bool get3d = Is3D.Checked == true; // Stupid! bool invert = Invert.Checked == true; // Timer Stopwatch sw = new Stopwatch(); int index = 0; if (VisualiseDomainWarp.Checked != true) { var noiseValues = new float[w * h]; bool warp = DomainWarp.SelectedIndex > 0; sw.Start(); for (var y = h / -2; y < h / 2; y++) { for (var x = w / -2; x < w / 2; x++) { FNfloat xf = x; FNfloat yf = y; FNfloat zf = zPos; if (get3d) { if (warp) warpNoise.DomainWarp(ref xf, ref yf, ref zf); noise = genNoise.GetNoise(xf, yf, zf); } else { if (warp) warpNoise.DomainWarp(ref xf, ref yf); noise = genNoise.GetNoise(xf, yf); } avg += noise; maxN = Math.Max(maxN, noise); minN = Math.Min(minN, noise); noiseValues[index++] = noise; } } sw.Stop(); avg /= index - 1; float scale = 255 / (maxN - minN); for (var i = 0; i < noiseValues.Length; i++) { int value = (int)MathF.Round(Math.Clamp((noiseValues[i] - minN) * scale, 0, 255)); if (invert) value = 255 - value; ImageData[i] = value; ImageData[i] |= value << 8; ImageData[i] |= value << 16; } } else { var noiseValues = new float[w * h * 3]; sw.Start(); for (var y = -h / 2; y < h / 2; y++) { for (var x = -w / 2; x < w / 2; x++) { FNfloat xf = x; FNfloat yf = y; FNfloat zf = zPos; if (get3d) warpNoise.DomainWarp(ref xf, ref yf, ref zf); else warpNoise.DomainWarp(ref xf, ref yf); xf -= x; yf -= y; zf -= zPos; avg += (float)(xf + yf); maxN = Math.Max(maxN, (float)Math.Max(xf, yf)); minN = Math.Min(minN, (float)Math.Min(xf, yf)); noiseValues[index++] = (float)xf; noiseValues[index++] = (float)yf; if (get3d) { avg += (float)zf; maxN = Math.Max(maxN, (float)zf); minN = Math.Min(minN, (float)zf); noiseValues[index++] = (float)zf; } } } sw.Stop(); if (get3d) avg /= (index - 1) * 3; else avg /= (index - 1) * 2; index = 0; float scale = 1 / (maxN - minN); for (var i = 0; i < ImageData.Length; i++) { Color color = new Color(); if (get3d) { color.R = (noiseValues[index++] - minN) * scale; color.G = (noiseValues[index++] - minN) * scale; color.B = (noiseValues[index++] - minN) * scale; } else { var vx = (noiseValues[index++] - minN) / (maxN - minN) - 0.5f; var vy = (noiseValues[index++] - minN) / (maxN - minN) - 0.5f; ColorHSB hsb = new ColorHSB(); hsb.H = MathF.Atan2(vy, vx) * (180 / MathF.PI) + 180; hsb.B = Math.Min(1.0f, MathF.Sqrt(vx * vx + vy * vy) * 2); hsb.S = 0.9f; color = hsb.ToColor(); } if (Invert.Checked == true) { color.Invert(); } ImageData[i] = color.ToArgb(); } } // Set image Bitmap = new Bitmap(w, h, PixelFormat.Format32bppRgb, ImageData); Image.Image = Bitmap; // Set info labels Time.Text = "Time (ms): " + sw.ElapsedMilliseconds.ToString(); Mean.Text = "Mean: " + avg.ToString(); Min.Text = "Min: " + minN.ToString(); Max.Text = "Max: " + maxN.ToString(); // Sets the client (inner) size of the window for your content ClientSize = new Size(Math.Max((int)PreviewWidth.Value, 768), Math.Max((int)PreviewHeight.Value, 768)) + windowSizeOffset; if (isScrolling) { await Task.Delay(50); try { zPos += ((float)Frequency.Value) * 100.0f; } catch (Exception ex) { MessageBox.Show("Frequency error: " + ex.ToString()); } } } while (isScrolling); } private void OnUp(object sender, EventArgs e) { try { zPos += ((float)Frequency.Value) * 100.0f; Generate(sender, e); } catch (Exception ex) { MessageBox.Show("Frequency error: " + ex.ToString()); } } private void OnDown(object sender, EventArgs e) { try { zPos -= ((float)Frequency.Value) * 100.0f; Generate(sender, e); } catch (Exception ex) { MessageBox.Show("Frequency error: " + ex.ToString()); } } private void OnScroll(object sender, EventArgs e) { isScrolling = !isScrolling; if (isScrolling) Generate(sender, e); } private void OnUIUpdate(object sender = null, EventArgs e = null) { // 3D controls var is3d = Is3D.Checked == true; UpButton.Enabled = DownButton.Enabled = ScrollButton.Enabled = is3d; // Warp var warpVis = VisualiseDomainWarp.Checked == true; NoiseType.Enabled = !warpVis; FractalType.Enabled = !warpVis; Frequency.Enabled = !warpVis; if (warpVis) { if (is3d) ExtraInfo.Text = "Visualisation of domain warp:\r\nRed = X offset, Green = Y offset, Blue = Z offset"; else ExtraInfo.Text = "Visualisation of domain warp:\r\nHue = Angle, Brightness = Magnitude"; } else ExtraInfo.Text = ""; // Fractal options var fractalEnabled = (!warpVis && FractalType.SelectedIndex > 0); FractalOctaves.Enabled = fractalEnabled; FractalLacunarity.Enabled = fractalEnabled; FractalGain.Enabled = fractalEnabled; FractalWeightedStrength.Enabled = fractalEnabled; FractalPingPongStrength.Enabled = (fractalEnabled && FractalType.SelectedKey == "Ping Pong"); // Domain Warp Fractal options var domainWarpFractalEnabled = (DomainWarp.SelectedIndex > 0 && DomainWarpFractal.SelectedIndex > 0); DomainWarpFractalOctaves.Enabled = domainWarpFractalEnabled; DomainWarpFractalLacunarity.Enabled = domainWarpFractalEnabled; DomainWarpFractalGain.Enabled = domainWarpFractalEnabled; // Cellular var cellular = NoiseType.SelectedKey.Contains("Cellular") && !warpVis; CellularDistanceFunction.Enabled = cellular; CellularReturnType.Enabled = cellular; CellularJitter.Enabled = cellular; // Domain Warp var warp = DomainWarp.SelectedIndex > 0; DomainWarpFractal.Enabled = warp; DomainWarpAmplitude.Enabled = warp; DomainWarpFrequency.Enabled = warp; // 3D Domain Rotation RotationType3D.Enabled = !warpVis && is3d; DomainWarpRotationType3D.Enabled = warp && is3d; Generate(sender, e); } private void Save(object sender, EventArgs e) { var save = new SaveFileDialog(); save.Filters.Add(new FileFilter("PNG File", ".png")); var res = save.ShowDialog(null); if (res == DialogResult.Ok) { Bitmap.Save(save.FileName, ImageFormat.Png); } } // Helper private void AddToTableWithLabel(TableLayout parent, Control me, string label) { me.Width = 200; parent.Rows.Add(new TableRow { Cells = { TableLayout.AutoSized(new Label { Text = label, TextAlignment = TextAlignment.Right, VerticalAlignment = VerticalAlignment.Center, Width = 130 }), new TableCell(me) } }); } private void AddHeadingToTable(TableLayout parent, string label) { Font bold = new Font(new Label().Font.Family, new Label().Font.Size, FontStyle.Bold); parent.Rows.Add(new TableRow { Cells = { new Label { Text = label + "", Font = bold, Wrap = WrapMode.None, VerticalAlignment = VerticalAlignment.Center, Width = 130 } } }); } private string FormatReadable(string enumName) { return Regex.Replace(Regex.Replace(enumName, "([a-z])([A-Z0-9])", "$1 $2"), "([a-z0-9])([A-Z][a-z])", "$1 $2"); } }
using GitVersion; using NUnit.Framework; using Shouldly; using System; using System.Collections.Generic; using System.ComponentModel; [TestFixture] public class ArgumentParserTests { [Test] public void Empty_means_use_current_directory() { var arguments = ArgumentParser.ParseArguments(""); arguments.TargetPath.ShouldBe(Environment.CurrentDirectory); arguments.LogFilePath.ShouldBe(null); arguments.IsHelp.ShouldBe(false); } [Test] public void Single_means_use_as_target_directory() { var arguments = ArgumentParser.ParseArguments("path"); arguments.TargetPath.ShouldBe("path"); arguments.LogFilePath.ShouldBe(null); arguments.IsHelp.ShouldBe(false); } [Test] public void No_path_and_logfile_should_use_current_directory_TargetDirectory() { var arguments = ArgumentParser.ParseArguments("-l logFilePath"); arguments.TargetPath.ShouldBe(Environment.CurrentDirectory); arguments.LogFilePath.ShouldBe("logFilePath"); arguments.IsHelp.ShouldBe(false); } [Test] public void H_means_IsHelp() { var arguments = ArgumentParser.ParseArguments("-h"); Assert.IsNull(arguments.TargetPath); Assert.IsNull(arguments.LogFilePath); arguments.IsHelp.ShouldBe(true); } [Test] public void Exec() { var arguments = ArgumentParser.ParseArguments("-exec rake"); arguments.Exec.ShouldBe("rake"); } [Test] public void Exec_with_args() { var arguments = ArgumentParser.ParseArguments(new List<string> { "-exec", "rake", "-execargs", "clean build" }); arguments.Exec.ShouldBe("rake"); arguments.ExecArgs.ShouldBe("clean build"); } [Test] public void Msbuild() { var arguments = ArgumentParser.ParseArguments("-proj msbuild.proj"); arguments.Proj.ShouldBe("msbuild.proj"); } [Test] public void Msbuild_with_args() { var arguments = ArgumentParser.ParseArguments(new List<string> { "-proj", "msbuild.proj", "-projargs", "/p:Configuration=Debug /p:Platform=AnyCPU" }); arguments.Proj.ShouldBe("msbuild.proj"); arguments.ProjArgs.ShouldBe("/p:Configuration=Debug /p:Platform=AnyCPU"); } [Test] public void Execwith_targetdirectory() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -exec rake"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.Exec.ShouldBe("rake"); } [Test] public void TargetDirectory_and_LogFilePath_can_be_parsed() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -l logFilePath"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.LogFilePath.ShouldBe("logFilePath"); arguments.IsHelp.ShouldBe(false); } [Test] public void Username_and_Password_can_be_parsed() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -u [username] -p [password]"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.Authentication.Username.ShouldBe("[username]"); arguments.Authentication.Password.ShouldBe("[password]"); arguments.IsHelp.ShouldBe(false); } [Test] public void Unknown_output_should_throw() { var exception = Assert.Throws<WarningException>(() => ArgumentParser.ParseArguments("targetDirectoryPath -output invalid_value")); exception.Message.ShouldBe("Value 'invalid_value' cannot be parsed as output type, please use 'json' or 'buildserver'"); } [Test] public void Output_defaults_to_json() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath"); arguments.Output.ShouldBe(OutputType.Json); } [Test] public void Output_json_can_be_parsed() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -output json"); arguments.Output.ShouldBe(OutputType.Json); } [Test] public void Output_buildserver_can_be_parsed() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -output buildserver"); arguments.Output.ShouldBe(OutputType.BuildServer); } [Test] public void MultipleArgsAndFlag() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -output buildserver -updateAssemblyInfo"); arguments.Output.ShouldBe(OutputType.BuildServer); } [Test] public void Url_and_BranchName_can_be_parsed() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -url http://github.com/Particular/GitVersion.git -b somebranch"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.TargetUrl.ShouldBe("http://github.com/Particular/GitVersion.git"); arguments.TargetBranch.ShouldBe("somebranch"); arguments.IsHelp.ShouldBe(false); } [Test] public void Wrong_number_of_arguments_should_throw() { var exception = Assert.Throws<WarningException>(() => ArgumentParser.ParseArguments("targetDirectoryPath -l logFilePath extraArg")); exception.Message.ShouldBe("Could not parse command line parameter 'extraArg'."); } [TestCase("targetDirectoryPath -x logFilePath")] [TestCase("/invalid-argument")] public void Unknown_arguments_should_throw(string arguments) { var exception = Assert.Throws<WarningException>(() => ArgumentParser.ParseArguments(arguments)); exception.Message.ShouldStartWith("Could not parse command line parameter"); } [TestCase("-updateAssemblyInfo true")] [TestCase("-updateAssemblyInfo 1")] [TestCase("-updateAssemblyInfo")] [TestCase("-updateAssemblyInfo -proj foo.sln")] [TestCase("-updateAssemblyInfo assemblyInfo.cs")] [TestCase("-updateAssemblyInfo assemblyInfo.cs -ensureassemblyinfo")] [TestCase("-updateAssemblyInfo assemblyInfo.cs otherAssemblyInfo.cs")] [TestCase("-updateAssemblyInfo Assembly.cs Assembly.cs -ensureassemblyinfo")] public void Update_assembly_info_true(string command) { var arguments = ArgumentParser.ParseArguments(command); arguments.UpdateAssemblyInfo.ShouldBe(true); } [TestCase("-updateAssemblyInfo false")] [TestCase("-updateAssemblyInfo 0")] public void Update_assembly_info_false(string command) { var arguments = ArgumentParser.ParseArguments(command); arguments.UpdateAssemblyInfo.ShouldBe(false); } [TestCase("-updateAssemblyInfo Assembly.cs Assembly1.cs -ensureassemblyinfo")] public void Create_mulitple_assembly_info_protected(string command) { var exception = Assert.Throws<WarningException>(() => ArgumentParser.ParseArguments(command)); exception.Message.ShouldBe("Can't specify multiple assembly info files when using /ensureassemblyinfo switch, either use a single assembly info file or do not specify /ensureassemblyinfo and create assembly info files manually"); } [Test] public void Update_assembly_info_with_filename() { var arguments = ArgumentParser.ParseArguments("-updateAssemblyInfo CommonAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.ShouldContain("CommonAssemblyInfo.cs"); } [Test] public void Update_assembly_info_with_multiple_filenames() { var arguments = ArgumentParser.ParseArguments("-updateAssemblyInfo CommonAssemblyInfo.cs VersionAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(2); arguments.UpdateAssemblyInfoFileName.ShouldContain("CommonAssemblyInfo.cs"); arguments.UpdateAssemblyInfoFileName.ShouldContain("VersionAssemblyInfo.cs"); } [Test] public void Overrideconfig_with_no_options() { var arguments = ArgumentParser.ParseArguments("/overrideconfig"); arguments.HasOverrideConfig.ShouldBe(false); arguments.OverrideConfig.ShouldNotBeNull(); } [Test] public void Overrideconfig_with_single_tagprefix_option() { var arguments = ArgumentParser.ParseArguments("/overrideconfig tag-prefix=sample"); arguments.HasOverrideConfig.ShouldBe(true); arguments.OverrideConfig.TagPrefix.ShouldBe("sample"); } [TestCase("tag-prefix=sample;tag-prefix=other")] [TestCase("tag-prefix=sample;param2=other")] public void Overrideconfig_with_several_options(string options) { var exception = Assert.Throws<WarningException>(() => ArgumentParser.ParseArguments(string.Format("/overrideconfig {0}", options))); exception.Message.ShouldContain("Can't specify multiple /overrideconfig options"); } [TestCase("tag-prefix=sample=asdf")] public void Overrideconfig_with_invalid_option(string options) { var exception = Assert.Throws<WarningException>(() => ArgumentParser.ParseArguments(string.Format("/overrideconfig {0}", options))); exception.Message.ShouldContain("Could not parse /overrideconfig option"); } [Test] public void Update_assembly_info_with_relative_filename() { var arguments = ArgumentParser.ParseArguments("-updateAssemblyInfo ..\\..\\CommonAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.ShouldContain("..\\..\\CommonAssemblyInfo.cs"); } [Test] public void Ensure_assembly_info_true_when_found() { var arguments = ArgumentParser.ParseArguments("-ensureAssemblyInfo"); arguments.EnsureAssemblyInfo.ShouldBe(true); } [Test] public void Ensure_assembly_info_true() { var arguments = ArgumentParser.ParseArguments("-ensureAssemblyInfo true"); arguments.EnsureAssemblyInfo.ShouldBe(true); } [Test] public void Ensure_assembly_info_false() { var arguments = ArgumentParser.ParseArguments("-ensureAssemblyInfo false"); arguments.EnsureAssemblyInfo.ShouldBe(false); } [Test] public void DynamicRepoLocation() { var arguments = ArgumentParser.ParseArguments("-dynamicRepoLocation c:\\foo\\"); arguments.DynamicRepositoryLocation.ShouldBe("c:\\foo\\"); } [Test] public void Can_log_to_console() { var arguments = ArgumentParser.ParseArguments("-l console -proj foo.sln"); arguments.LogFilePath.ShouldBe("console"); } [Test] public void Nofetch_true_when_defined() { var arguments = ArgumentParser.ParseArguments("-nofetch"); arguments.NoFetch.ShouldBe(true); } [Test] public void Other_arguments_can_be_parsed_before_nofetch() { var arguments = ArgumentParser.ParseArguments("targetpath -nofetch "); arguments.TargetPath.ShouldBe("targetpath"); arguments.NoFetch.ShouldBe(true); } [Test] public void Other_arguments_can_be_parsed_after_nofetch() { var arguments = ArgumentParser.ParseArguments("-nofetch -proj foo.sln"); arguments.NoFetch.ShouldBe(true); arguments.Proj.ShouldBe("foo.sln"); } [Test] public void Log_path_can_contain_forward_slash() { var arguments = ArgumentParser.ParseArguments("-l /some/path"); arguments.LogFilePath.ShouldBe("/some/path"); } [Test] public void Boolean_argument_handling() { var arguments = ArgumentParser.ParseArguments("/nofetch /updateassemblyinfo true"); arguments.NoFetch.ShouldBe(true); arguments.UpdateAssemblyInfo.ShouldBe(true); } [Test] public void Nocache_true_when_defined() { var arguments = ArgumentParser.ParseArguments("-nocache"); arguments.NoCache.ShouldBe(true); } [TestCase("-verbosity x", true, VerbosityLevel.None)] [TestCase("-verbosity none", false, VerbosityLevel.None)] [TestCase("-verbosity info", false, VerbosityLevel.Info)] [TestCase("-verbosity debug", false, VerbosityLevel.Debug)] [TestCase("-verbosity INFO", false, VerbosityLevel.Info)] [TestCase("-verbosity warn", false, VerbosityLevel.Warn)] [TestCase("-verbosity error", false, VerbosityLevel.Error)] public void Check_verbosity_parsing(string command, bool shouldThrow, VerbosityLevel expectedVerbosity) { if (shouldThrow) { Assert.Throws<WarningException>(() => ArgumentParser.ParseArguments(command)); } else { var arguments = ArgumentParser.ParseArguments(command); arguments.Verbosity.ShouldBe(expectedVerbosity); } } }
using DevExpress.Mvvm; using DevExpress.Mvvm.UI; using DevExpress.Mvvm.UI.Interactivity; using NUnit.Framework; using System; using System.Threading; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Threading; using System.Windows.Data; using DevExpress.Mvvm.POCO; namespace DevExpress.Mvvm.UI.Tests { internal class SplashScreenTestWindow : Window, ISplashScreen { public Button WindowContent { get; private set; } public double Progress { get; private set; } public bool IsIndeterminate { get; private set; } public string TextProp { get; private set; } public void Text(string value) { TextProp = value; } public SplashScreenTestWindow() { Instance = this; Progress = double.NaN; IsIndeterminate = true; Width = 100; Height = 100; Content = WindowContent = new Button(); this.ShowInTaskbar = false; } void ISplashScreen.Progress(double value) { Progress = value; } void ISplashScreen.CloseSplashScreen() { Close(); } void ISplashScreen.SetProgressState(bool isIndeterminate) { IsIndeterminate = isIndeterminate; } public static volatile SplashScreenTestWindow Instance = null; public static void DoEvents(DispatcherPriority priority = DispatcherPriority.Background) { DispatcherFrame frame = new DispatcherFrame(); DXSplashScreen.SplashContainer.SplashScreen.Dispatcher.BeginInvoke( priority, new DispatcherOperationCallback(ExitFrame), frame); Dispatcher.PushFrame(frame); } static object ExitFrame(object f) { ((DispatcherFrame)f).Continue = false; return null; } } internal class SplashScreenTestUserControl : UserControl { public static volatile Window Window; public static volatile SplashScreenViewModel ViewModel; public static SplashScreenTestUserControl Instance { get; set; } public static void DoEvents(DispatcherPriority priority = DispatcherPriority.Background) { DispatcherFrame frame = new DispatcherFrame(); DXSplashScreen.SplashContainer.SplashScreen.Dispatcher.BeginInvoke( priority, new DispatcherOperationCallback(ExitFrame), frame); Dispatcher.PushFrame(frame); } static object ExitFrame(object f) { Window = Window.GetWindow(Instance); ViewModel = (SplashScreenViewModel)Instance.DataContext; ((DispatcherFrame)f).Continue = false; return null; } public SplashScreenTestUserControl() { Instance = this; } } public class DXSplashScreenBaseTestFixture : BaseWpfFixture { protected override void TearDownCore() { base.TearDownCore(); SplashScreenTestUserControl.Window = null; SplashScreenTestUserControl.ViewModel = null; SplashScreenTestUserControl.Instance = null; SplashScreenTestWindow.Instance = null; CloseDXSplashScreen(); } protected void CloseDXSplashScreen() { if(!DXSplashScreen.IsActive) return; DXSplashScreen.Close(); var t = DXSplashScreen.SplashContainer.InternalThread; if(t != null) t.Join(); } } [TestFixture] public class DXSplashScreenTests : DXSplashScreenBaseTestFixture { [Test, ExpectedException(typeof(InvalidOperationException))] public void InvalidUsage_Test01() { DXSplashScreen.Show<SplashScreenTestWindow>(); DXSplashScreen.Show<SplashScreenTestWindow>(); } [Test, ExpectedException(typeof(InvalidOperationException))] public void InvalidUsage_Test02() { DXSplashScreen.Close(); } [Test, ExpectedException(typeof(InvalidOperationException))] public void InvalidUsage_Test03() { DXSplashScreen.Progress(0); } [Test, Ignore] public void Simple_Test() { DXSplashScreen.Show<SplashScreenTestWindow>(); Assert.IsNotNull(DXSplashScreen.SplashContainer.InternalThread); Assert.IsNotNull(DXSplashScreen.SplashContainer.SplashScreen); SplashScreenTestWindow.DoEvents(); Assert.IsNotNull(SplashScreenTestWindow.Instance, "SplashScreenTestWindow.Instance == null"); Assert.IsNotNull(SplashScreenTestWindow.Instance.WindowContent, "SplashScreenTestWindow.Instance == null"); Assert.IsTrue(SplashScreenTestWindow.Instance.WindowContent.IsVisible); Assert.AreEqual(double.NaN, SplashScreenTestWindow.Instance.Progress); Assert.IsTrue(SplashScreenTestWindow.Instance.IsIndeterminate); CloseDXSplashScreen(); Assert.IsNull(DXSplashScreen.SplashContainer.InternalThread); Assert.IsNull(DXSplashScreen.SplashContainer.SplashScreen); } [Test] public void Complex_Test() { DXSplashScreen.Show<SplashScreenTestWindow>(); Assert.IsNotNull(DXSplashScreen.SplashContainer.InternalThread); Assert.IsNotNull(DXSplashScreen.SplashContainer.SplashScreen); Assert.IsTrue(SplashScreenTestWindow.Instance.IsIndeterminate); DXSplashScreen.Progress(0); SplashScreenTestWindow.DoEvents(); Assert.IsFalse(SplashScreenTestWindow.Instance.IsIndeterminate); for(int i = 1; i < 10; i++) { DXSplashScreen.Progress(i); SplashScreenTestWindow.DoEvents(); Assert.AreEqual(i, SplashScreenTestWindow.Instance.Progress); } CloseDXSplashScreen(); Assert.IsNull(DXSplashScreen.SplashContainer.InternalThread); Assert.IsNull(DXSplashScreen.SplashContainer.SplashScreen); } [Test] public void IsActive_Test() { Assert.IsFalse(DXSplashScreen.IsActive); DXSplashScreen.Show<SplashScreenTestWindow>(); Assert.IsTrue(DXSplashScreen.IsActive); CloseDXSplashScreen(); Assert.IsFalse(DXSplashScreen.IsActive); } [Test] public void CustomSplashScreen_Test() { Func<object, Window> windowCreator = (p) => { Assert.AreEqual(1, p); return new SplashScreenTestWindow(); }; Func<object, object> splashScreenCreator = (p) => { Assert.AreEqual(1, p); return new TextBlock(); }; DXSplashScreen.Show(windowCreator, splashScreenCreator, 1, 1); Assert.IsNotNull(DXSplashScreen.SplashContainer.InternalThread); Assert.IsNotNull(DXSplashScreen.SplashContainer.SplashScreen); CloseDXSplashScreen(); Assert.IsNull(DXSplashScreen.SplashContainer.InternalThread); Assert.IsNull(DXSplashScreen.SplashContainer.SplashScreen); } [Test] public void ShowWindowISplashScreen_Test() { DXSplashScreen.Show<SplashScreenTestWindow>(); SplashScreenTestWindow.DoEvents(); Assert.IsTrue(SplashScreenTestWindow.Instance.IsIndeterminate); Assert.AreEqual(double.NaN, SplashScreenTestWindow.Instance.Progress); DXSplashScreen.Progress(100); SplashScreenTestWindow.DoEvents(); Assert.IsFalse(SplashScreenTestWindow.Instance.IsIndeterminate); Assert.AreEqual(100, SplashScreenTestWindow.Instance.Progress); DXSplashScreen.Progress(100, 200); SplashScreenTestWindow.DoEvents(); Assert.IsFalse(SplashScreenTestWindow.Instance.IsIndeterminate); Assert.AreEqual(100, SplashScreenTestWindow.Instance.Progress); DXSplashScreen.CallSplashScreenMethod<SplashScreenTestWindow>(x => x.Text("test")); SplashScreenTestWindow.DoEvents(); Assert.IsFalse(SplashScreenTestWindow.Instance.IsIndeterminate); Assert.AreEqual(100, SplashScreenTestWindow.Instance.Progress); Assert.AreEqual("test", ((SplashScreenTestWindow)SplashScreenTestWindow.Instance).TextProp); DXSplashScreen.SetState("test"); SplashScreenTestWindow.DoEvents(); } [Test, ExpectedException(typeof(InvalidOperationException))] public void ShowWindowNotISplashScreen_Test() { DXSplashScreen.Show<Window>(); } [Test] public void ShowUserControl_Test() { DXSplashScreen.Show<SplashScreenTestUserControl>(); SplashScreenTestUserControl.DoEvents(); Assert.AreEqual(0, SplashScreenTestUserControl.ViewModel.Progress); Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.MaxProgress); Assert.AreEqual("Loading...", SplashScreenTestUserControl.ViewModel.State); Assert.AreEqual(true, SplashScreenTestUserControl.ViewModel.IsIndeterminate); DXSplashScreen.Progress(50); SplashScreenTestUserControl.DoEvents(); Assert.AreEqual(50, SplashScreenTestUserControl.ViewModel.Progress); Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.MaxProgress); Assert.AreEqual("Loading...", SplashScreenTestUserControl.ViewModel.State); Assert.AreEqual(false, SplashScreenTestUserControl.ViewModel.IsIndeterminate); DXSplashScreen.Progress(100, 200); SplashScreenTestUserControl.DoEvents(); Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.Progress); Assert.AreEqual(200, SplashScreenTestUserControl.ViewModel.MaxProgress); Assert.AreEqual("Loading...", SplashScreenTestUserControl.ViewModel.State); Assert.AreEqual(false, SplashScreenTestUserControl.ViewModel.IsIndeterminate); DXSplashScreen.SetState("Test"); SplashScreenTestUserControl.DoEvents(); Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.Progress); Assert.AreEqual(200, SplashScreenTestUserControl.ViewModel.MaxProgress); Assert.AreEqual("Test", SplashScreenTestUserControl.ViewModel.State); Assert.AreEqual(false, SplashScreenTestUserControl.ViewModel.IsIndeterminate); } [Test] public void ShowUserControlAndCheckWindowProperties_Test() { DXSplashScreen.Show<SplashScreenTestUserControl>(); SplashScreenTestUserControl.DoEvents(); Window wnd = SplashScreenTestUserControl.Window; AutoResetEvent SyncEvent = new AutoResetEvent(false); bool hasError = true; wnd.Dispatcher.BeginInvoke(new Action(() => { hasError = false; hasError = hasError | !(WindowStartupLocation.CenterScreen == wnd.WindowStartupLocation); hasError = hasError | !(true == WindowFadeAnimationBehavior.GetEnableAnimation(wnd)); hasError = hasError | !(null == wnd.Style); hasError = hasError | !(WindowStyle.None == wnd.WindowStyle); hasError = hasError | !(ResizeMode.NoResize == wnd.ResizeMode); hasError = hasError | !(true == wnd.AllowsTransparency); hasError = hasError | !(Colors.Transparent == ((SolidColorBrush)wnd.Background).Color); hasError = hasError | !(false == wnd.ShowInTaskbar); hasError = hasError | !(true == wnd.Topmost); hasError = hasError | !(SizeToContent.WidthAndHeight == wnd.SizeToContent); SyncEvent.Set(); })); SyncEvent.WaitOne(TimeSpan.FromSeconds(2)); Assert.IsFalse(hasError); CloseDXSplashScreen(); } [Test] public void TestQ338517_1() { DXSplashScreen.Show<SplashScreenTestWindow>(); Assert.IsNotNull(DXSplashScreen.SplashContainer.InternalThread); Assert.IsNotNull(DXSplashScreen.SplashContainer.SplashScreen); SplashScreenTestWindow.DoEvents(); Assert.IsTrue(SplashScreenTestWindow.Instance.WindowContent.IsVisible); Assert.AreEqual(double.NaN, SplashScreenTestWindow.Instance.Progress); Assert.IsTrue(SplashScreenTestWindow.Instance.IsIndeterminate); DXSplashScreen.CallSplashScreenMethod<SplashScreenTestWindow>(x => x.Text("Test")); SplashScreenTestWindow.DoEvents(); Assert.AreEqual("Test", ((SplashScreenTestWindow)SplashScreenTestWindow.Instance).TextProp); CloseDXSplashScreen(); Assert.IsNull(DXSplashScreen.SplashContainer.InternalThread); Assert.IsNull(DXSplashScreen.SplashContainer.SplashScreen); } [Test, ExpectedException(typeof(InvalidOperationException))] public void TestQ338517_2() { DXSplashScreen.Show<SplashScreenTestWindow>(); DXSplashScreen.CallSplashScreenMethod<UserControl>(x => x.Tag = "Test"); } } [TestFixture] public class DXSplashScreenServiceTests : DXSplashScreenBaseTestFixture { public class ContainerVM { public virtual double Progress { get; set; } public virtual double MaxProgress { get; set; } public virtual object State { get; set; } } [Test] public void TestB238799() { DXSplashScreenService s = new DXSplashScreenService(); ((ISplashScreenService)s).HideSplashScreen(); ((ISplashScreenService)s).HideSplashScreen(); } [Test] public void ShowWindowISplashScreen() { ISplashScreenService service = new DXSplashScreenService() { SplashScreenType = typeof(SplashScreenTestWindow), }; service.ShowSplashScreen(); SplashScreenTestWindow.DoEvents(); Assert.IsTrue(SplashScreenTestWindow.Instance.IsIndeterminate); Assert.AreEqual(double.NaN, SplashScreenTestWindow.Instance.Progress); service.SetSplashScreenProgress(100, 100); SplashScreenTestWindow.DoEvents(); Assert.IsFalse(SplashScreenTestWindow.Instance.IsIndeterminate); Assert.AreEqual(100, SplashScreenTestWindow.Instance.Progress); service.SetSplashScreenProgress(100, 200); SplashScreenTestWindow.DoEvents(); Assert.IsFalse(SplashScreenTestWindow.Instance.IsIndeterminate); Assert.AreEqual(100, SplashScreenTestWindow.Instance.Progress); DXSplashScreen.CallSplashScreenMethod<SplashScreenTestWindow>(x => x.Text("test")); SplashScreenTestWindow.DoEvents(); Assert.IsFalse(SplashScreenTestWindow.Instance.IsIndeterminate); Assert.AreEqual(100, SplashScreenTestWindow.Instance.Progress); Assert.AreEqual("test", ((SplashScreenTestWindow)SplashScreenTestWindow.Instance).TextProp); DXSplashScreen.SetState("test"); service.SetSplashScreenState("test"); SplashScreenTestWindow.DoEvents(); service.HideSplashScreen(); } [Test, ExpectedException(typeof(InvalidOperationException))] public void ShowWindowNotISplashScreen2() { ISplashScreenService service = new DXSplashScreenService() { SplashScreenType = typeof(Window), }; service.ShowSplashScreen(); } [Test] public void ShowUserControl() { ISplashScreenService service = new DXSplashScreenService() { ViewTemplate = new DataTemplate() { VisualTree = new FrameworkElementFactory(typeof(SplashScreenTestUserControl)) }, }; ShowUserControlCore(service); } [Test] public void BindServiceProperties() { var service = new DXSplashScreenService() { ViewTemplate = new DataTemplate() { VisualTree = new FrameworkElementFactory(typeof(SplashScreenTestUserControl)) }, }; ISplashScreenService iService = service; Border container = new Border(); ContainerVM vm = ViewModelSource.Create(() => new ContainerVM()); container.DataContext = vm; vm.State = "Loading2"; BindingOperations.SetBinding(service, DXSplashScreenService.ProgressProperty, new Binding("Progress")); BindingOperations.SetBinding(service, DXSplashScreenService.MaxProgressProperty, new Binding("MaxProgress")); BindingOperations.SetBinding(service, DXSplashScreenService.StateProperty, new Binding("State")); Interaction.GetBehaviors(container).Add(service); service.ShowSplashScreen(); SplashScreenTestUserControl.DoEvents(); Assert.AreEqual(0, SplashScreenTestUserControl.ViewModel.Progress); Assert.AreEqual(0, SplashScreenTestUserControl.ViewModel.MaxProgress); Assert.AreEqual("Loading2", SplashScreenTestUserControl.ViewModel.State); Assert.AreEqual(false, SplashScreenTestUserControl.ViewModel.IsIndeterminate); vm.Progress = 50; vm.MaxProgress = 100; SplashScreenTestUserControl.DoEvents(); Assert.AreEqual(50, SplashScreenTestUserControl.ViewModel.Progress); Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.MaxProgress); Assert.AreEqual("Loading2", SplashScreenTestUserControl.ViewModel.State); Assert.AreEqual(false, SplashScreenTestUserControl.ViewModel.IsIndeterminate); vm.Progress = 100; vm.MaxProgress = 200; SplashScreenTestUserControl.DoEvents(); Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.Progress); Assert.AreEqual(200, SplashScreenTestUserControl.ViewModel.MaxProgress); Assert.AreEqual("Loading2", SplashScreenTestUserControl.ViewModel.State); Assert.AreEqual(false, SplashScreenTestUserControl.ViewModel.IsIndeterminate); vm.State = "Test"; SplashScreenTestUserControl.DoEvents(); Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.Progress); Assert.AreEqual(200, SplashScreenTestUserControl.ViewModel.MaxProgress); Assert.AreEqual("Test", SplashScreenTestUserControl.ViewModel.State); Assert.AreEqual(false, SplashScreenTestUserControl.ViewModel.IsIndeterminate); iService.HideSplashScreen(); } [Test] public void ShowUserControlViaSplashScreenType() { ISplashScreenService service = new DXSplashScreenService() { SplashScreenType = typeof(SplashScreenTestUserControl), }; ShowUserControlCore(service); } void ShowUserControlCore(ISplashScreenService service) { service.ShowSplashScreen(); SplashScreenTestUserControl.DoEvents(); Assert.AreEqual(0, SplashScreenTestUserControl.ViewModel.Progress); Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.MaxProgress); Assert.AreEqual("Loading...", SplashScreenTestUserControl.ViewModel.State); Assert.AreEqual(true, SplashScreenTestUserControl.ViewModel.IsIndeterminate); service.SetSplashScreenProgress(50, 100); SplashScreenTestUserControl.DoEvents(); Assert.AreEqual(50, SplashScreenTestUserControl.ViewModel.Progress); Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.MaxProgress); Assert.AreEqual("Loading...", SplashScreenTestUserControl.ViewModel.State); Assert.AreEqual(false, SplashScreenTestUserControl.ViewModel.IsIndeterminate); service.SetSplashScreenProgress(100, 200); SplashScreenTestUserControl.DoEvents(); Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.Progress); Assert.AreEqual(200, SplashScreenTestUserControl.ViewModel.MaxProgress); Assert.AreEqual("Loading...", SplashScreenTestUserControl.ViewModel.State); Assert.AreEqual(false, SplashScreenTestUserControl.ViewModel.IsIndeterminate); service.SetSplashScreenState("Test"); SplashScreenTestUserControl.DoEvents(); Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.Progress); Assert.AreEqual(200, SplashScreenTestUserControl.ViewModel.MaxProgress); Assert.AreEqual("Test", SplashScreenTestUserControl.ViewModel.State); Assert.AreEqual(false, SplashScreenTestUserControl.ViewModel.IsIndeterminate); service.HideSplashScreen(); } [Test] public void ShowUserControlAndCheckWindowProperties() { ISplashScreenService service = new DXSplashScreenService() { ViewTemplate = new DataTemplate() { VisualTree = new FrameworkElementFactory(typeof(SplashScreenTestUserControl)) }, }; service.ShowSplashScreen(); SplashScreenTestUserControl.DoEvents(); Window wnd = SplashScreenTestUserControl.Window; AutoResetEvent SyncEvent = new AutoResetEvent(false); bool hasError = true; wnd.Dispatcher.BeginInvoke(new Action(() => { hasError = false; hasError = hasError | !(WindowStartupLocation.CenterScreen == wnd.WindowStartupLocation); hasError = hasError | !(true == WindowFadeAnimationBehavior.GetEnableAnimation(wnd)); hasError = hasError | !(null == wnd.Style); hasError = hasError | !(WindowStyle.None == wnd.WindowStyle); hasError = hasError | !(ResizeMode.NoResize == wnd.ResizeMode); hasError = hasError | !(true == wnd.AllowsTransparency); hasError = hasError | !(Colors.Transparent == ((SolidColorBrush)wnd.Background).Color); hasError = hasError | !(false == wnd.ShowInTaskbar); hasError = hasError | !(true == wnd.Topmost); hasError = hasError | !(SizeToContent.WidthAndHeight == wnd.SizeToContent); SyncEvent.Set(); })); SyncEvent.WaitOne(TimeSpan.FromSeconds(2)); Assert.IsFalse(hasError); service.HideSplashScreen(); } [Test] public void ShowUserControlAndCheckWindowProperties2() { Style wndStyle = new Style(); ISplashScreenService service = new DXSplashScreenService() { ViewTemplate = new DataTemplate() { VisualTree = new FrameworkElementFactory(typeof(SplashScreenTestUserControl)) }, SplashScreenWindowStyle = wndStyle, SplashScreenStartupLocation = WindowStartupLocation.Manual, }; service.ShowSplashScreen(); SplashScreenTestUserControl.DoEvents(); Window wnd = SplashScreenTestUserControl.Window; AutoResetEvent SyncEvent = new AutoResetEvent(false); bool hasError = true; wnd.Dispatcher.BeginInvoke(new Action(() => { hasError = false; hasError = hasError | !(WindowStartupLocation.Manual == wnd.WindowStartupLocation); hasError = hasError | !(false == WindowFadeAnimationBehavior.GetEnableAnimation(wnd)); hasError = hasError | !(wndStyle == wnd.Style); hasError = hasError | !(WindowStyle.SingleBorderWindow == wnd.WindowStyle); hasError = hasError | !(ResizeMode.CanResize == wnd.ResizeMode); hasError = hasError | !(false == wnd.AllowsTransparency); hasError = hasError | !(true == wnd.ShowInTaskbar); hasError = hasError | !(false == wnd.Topmost); hasError = hasError | !(SizeToContent.Manual == wnd.SizeToContent); SyncEvent.Set(); })); SyncEvent.WaitOne(TimeSpan.FromSeconds(2)); Assert.IsFalse(hasError); service.HideSplashScreen(); } [Test] public void ViewTemplateShouldBeSealed() { DataTemplate temp = new DataTemplate() { VisualTree = new FrameworkElementFactory(typeof(SplashScreenTestUserControl)) }; Assert.IsFalse(temp.IsSealed); DXSplashScreenService service = new DXSplashScreenService() { ViewTemplate = temp, }; Assert.IsTrue(temp.IsSealed); } [Test, ExpectedException(typeof(InvalidOperationException))] public void ViewTemplateSelectorIsNotSupported() { DXSplashScreenService service = new DXSplashScreenService() { ViewTemplateSelector = new DataTemplateSelector(), }; } } }
//------------------------------------------------------------------------------ // <copyright file="DataGridViewComboBoxColumn.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Windows.Forms { using System; using System.Text; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Design; using System.Globalization; /// <include file='doc\DataGridViewComboBoxColumn.uex' path='docs/doc[@for="DataGridViewComboBoxColumn"]/*' /> [ Designer("System.Windows.Forms.Design.DataGridViewComboBoxColumnDesigner, " + AssemblyRef.SystemDesign), ToolboxBitmapAttribute(typeof(DataGridViewComboBoxColumn), "DataGridViewComboBoxColumn.bmp") ] public class DataGridViewComboBoxColumn : DataGridViewColumn { private static Type columnType = typeof(DataGridViewComboBoxColumn); /// <include file='doc\DataGridViewComboBoxColumn.uex' path='docs/doc[@for="DataGridViewComboBoxColumn.DataGridViewComboBoxColumn"]/*' /> public DataGridViewComboBoxColumn() : base(new DataGridViewComboBoxCell()) { ((DataGridViewComboBoxCell)base.CellTemplate).TemplateComboBoxColumn = this; } /// <include file='doc\DataGridViewComboBoxColumn.uex' path='docs/doc[@for="DataGridViewComboBoxColumn.AutoComplete"]/*' /> [ Browsable(true), DefaultValue(true), SRCategory(SR.CatBehavior), SRDescription(SR.DataGridView_ComboBoxColumnAutoCompleteDescr) ] public bool AutoComplete { get { if (this.ComboBoxCellTemplate == null) { throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_CellTemplateRequired)); } return this.ComboBoxCellTemplate.AutoComplete; } set { if (this.AutoComplete != value) { this.ComboBoxCellTemplate.AutoComplete = value; if (this.DataGridView != null) { DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewComboBoxCell; if (dataGridViewCell != null) { dataGridViewCell.AutoComplete = value; } } } } } } /// <include file='doc\DataGridViewComboBoxColumn.uex' path='docs/doc[@for="DataGridViewComboBoxColumn.CellTemplate"]/*' /> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public override DataGridViewCell CellTemplate { get { return base.CellTemplate; } set { DataGridViewComboBoxCell dataGridViewComboBoxCell = value as DataGridViewComboBoxCell; if (value != null && dataGridViewComboBoxCell == null) { throw new InvalidCastException(SR.GetString(SR.DataGridViewTypeColumn_WrongCellTemplateType, "System.Windows.Forms.DataGridViewComboBoxCell")); } base.CellTemplate = value; if (value != null) { dataGridViewComboBoxCell.TemplateComboBoxColumn = this; } } } private DataGridViewComboBoxCell ComboBoxCellTemplate { get { return (DataGridViewComboBoxCell) this.CellTemplate; } } /// <include file='doc\DataGridViewComboBoxColumn.uex' path='docs/doc[@for="DataGridViewComboBoxColumn.DataSource"]/*' /> [ DefaultValue(null), SRCategory(SR.CatData), SRDescription(SR.DataGridView_ComboBoxColumnDataSourceDescr), RefreshProperties(RefreshProperties.Repaint), AttributeProvider(typeof(IListSource)), ] public object DataSource { get { if (this.ComboBoxCellTemplate == null) { throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_CellTemplateRequired)); } return this.ComboBoxCellTemplate.DataSource; } set { if (this.ComboBoxCellTemplate == null) { throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_CellTemplateRequired)); } this.ComboBoxCellTemplate.DataSource = value; if (this.DataGridView != null) { DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewComboBoxCell; if (dataGridViewCell != null) { dataGridViewCell.DataSource = value; } } this.DataGridView.OnColumnCommonChange(this.Index); } } } /// <include file='doc\DataGridViewComboBoxColumn.uex' path='docs/doc[@for="DataGridViewComboBoxColumn.DisplayMember"]/*' /> [ DefaultValue(""), SRCategory(SR.CatData), SRDescription(SR.DataGridView_ComboBoxColumnDisplayMemberDescr), TypeConverterAttribute("System.Windows.Forms.Design.DataMemberFieldConverter, " + AssemblyRef.SystemDesign), Editor("System.Windows.Forms.Design.DataMemberFieldEditor, " + AssemblyRef.SystemDesign, typeof(System.Drawing.Design.UITypeEditor)) ] public string DisplayMember { get { if (this.ComboBoxCellTemplate == null) { throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_CellTemplateRequired)); } return this.ComboBoxCellTemplate.DisplayMember; } set { if (this.ComboBoxCellTemplate == null) { throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_CellTemplateRequired)); } this.ComboBoxCellTemplate.DisplayMember = value; if (this.DataGridView != null) { DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewComboBoxCell; if (dataGridViewCell != null) { dataGridViewCell.DisplayMember = value; } } this.DataGridView.OnColumnCommonChange(this.Index); } } } /// <include file='doc\DataGridViewComboBoxColumn.uex' path='docs/doc[@for="DataGridViewComboBoxColumn.DisplayStyle"]/*' /> [ DefaultValue(DataGridViewComboBoxDisplayStyle.DropDownButton), SRCategory(SR.CatAppearance), SRDescription(SR.DataGridView_ComboBoxColumnDisplayStyleDescr) ] public DataGridViewComboBoxDisplayStyle DisplayStyle { get { if (this.ComboBoxCellTemplate == null) { throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_CellTemplateRequired)); } return this.ComboBoxCellTemplate.DisplayStyle; } set { if (this.ComboBoxCellTemplate == null) { throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_CellTemplateRequired)); } this.ComboBoxCellTemplate.DisplayStyle = value; if (this.DataGridView != null) { DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewComboBoxCell; if (dataGridViewCell != null) { dataGridViewCell.DisplayStyleInternal = value; } } // Calling InvalidateColumn instead of OnColumnCommonChange because DisplayStyle does not affect preferred size. this.DataGridView.InvalidateColumn(this.Index); } } } /// <include file='doc\DataGridViewComboBoxColumn.uex' path='docs/doc[@for="DataGridViewComboBoxColumn.DisplayStyleForCurrentCellOnly"]/*' /> [ DefaultValue(false), SRCategory(SR.CatAppearance), SRDescription(SR.DataGridView_ComboBoxColumnDisplayStyleForCurrentCellOnlyDescr) ] public bool DisplayStyleForCurrentCellOnly { get { if (this.ComboBoxCellTemplate == null) { throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_CellTemplateRequired)); } return this.ComboBoxCellTemplate.DisplayStyleForCurrentCellOnly; } set { if (this.ComboBoxCellTemplate == null) { throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_CellTemplateRequired)); } this.ComboBoxCellTemplate.DisplayStyleForCurrentCellOnly = value; if (this.DataGridView != null) { DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewComboBoxCell; if (dataGridViewCell != null) { dataGridViewCell.DisplayStyleForCurrentCellOnlyInternal = value; } } // Calling InvalidateColumn instead of OnColumnCommonChange because DisplayStyleForCurrentCellOnly does not affect preferred size. this.DataGridView.InvalidateColumn(this.Index); } } } /// <include file='doc\DataGridViewComboBoxColumn.uex' path='docs/doc[@for="DataGridViewComboBoxColumn.DropDownWidth"]/*' /> [ DefaultValue(1), SRCategory(SR.CatBehavior), SRDescription(SR.DataGridView_ComboBoxColumnDropDownWidthDescr), ] public int DropDownWidth { get { if (this.ComboBoxCellTemplate == null) { throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_CellTemplateRequired)); } return this.ComboBoxCellTemplate.DropDownWidth; } set { if (this.DropDownWidth != value) { this.ComboBoxCellTemplate.DropDownWidth = value; if (this.DataGridView != null) { DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewComboBoxCell; if (dataGridViewCell != null) { dataGridViewCell.DropDownWidth = value; } } } } } } /// <include file='doc\DataGridViewComboBoxColumn.uex' path='docs/doc[@for="DataGridViewComboBoxColumn.FlatStyle"]/*' /> [ DefaultValue(FlatStyle.Standard), SRCategory(SR.CatAppearance), SRDescription(SR.DataGridView_ComboBoxColumnFlatStyleDescr), ] public FlatStyle FlatStyle { get { if (this.CellTemplate == null) { throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_CellTemplateRequired)); } return ((DataGridViewComboBoxCell) this.CellTemplate).FlatStyle; } set { if (this.FlatStyle != value) { ((DataGridViewComboBoxCell)this.CellTemplate).FlatStyle = value; if (this.DataGridView != null) { DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewComboBoxCell; if (dataGridViewCell != null) { dataGridViewCell.FlatStyleInternal = value; } } this.DataGridView.OnColumnCommonChange(this.Index); } } } } /// <include file='doc\DataGridViewComboBoxColumn.uex' path='docs/doc[@for="DataGridViewComboBoxColumn.Items"]/*' /> [ Editor("System.Windows.Forms.Design.StringCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), SRCategory(SR.CatData), SRDescription(SR.DataGridView_ComboBoxColumnItemsDescr) ] public DataGridViewComboBoxCell.ObjectCollection Items { get { if (this.ComboBoxCellTemplate == null) { throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_CellTemplateRequired)); } return this.ComboBoxCellTemplate.GetItems(this.DataGridView); } } /// <include file='doc\DataGridViewComboBoxColumn.uex' path='docs/doc[@for="DataGridViewComboBoxColumn.ValueMember"]/*' /> [ DefaultValue(""), SRCategory(SR.CatData), SRDescription(SR.DataGridView_ComboBoxColumnValueMemberDescr), TypeConverterAttribute("System.Windows.Forms.Design.DataMemberFieldConverter, " + AssemblyRef.SystemDesign), Editor("System.Windows.Forms.Design.DataMemberFieldEditor, " + AssemblyRef.SystemDesign, typeof(System.Drawing.Design.UITypeEditor)) ] public string ValueMember { get { if (this.ComboBoxCellTemplate == null) { throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_CellTemplateRequired)); } return this.ComboBoxCellTemplate.ValueMember; } set { if (this.ComboBoxCellTemplate == null) { throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_CellTemplateRequired)); } this.ComboBoxCellTemplate.ValueMember = value; if (this.DataGridView != null) { DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewComboBoxCell; if (dataGridViewCell != null) { dataGridViewCell.ValueMember = value; } } this.DataGridView.OnColumnCommonChange(this.Index); } } } /// <include file='doc\DataGridViewComboBoxColumn.uex' path='docs/doc[@for="DataGridViewComboBoxColumn.MaxDropDownItems"]/*' /> [ DefaultValue(DataGridViewComboBoxCell.DATAGRIDVIEWCOMBOBOXCELL_defaultMaxDropDownItems), SRCategory(SR.CatBehavior), SRDescription(SR.DataGridView_ComboBoxColumnMaxDropDownItemsDescr) ] public int MaxDropDownItems { get { if (this.ComboBoxCellTemplate == null) { throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_CellTemplateRequired)); } return this.ComboBoxCellTemplate.MaxDropDownItems; } set { if (this.MaxDropDownItems != value) { this.ComboBoxCellTemplate.MaxDropDownItems = value; if (this.DataGridView != null) { DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewComboBoxCell; if (dataGridViewCell != null) { dataGridViewCell.MaxDropDownItems = value; } } } } } } /// <include file='doc\DataGridViewComboBoxColumn.uex' path='docs/doc[@for="DataGridViewComboBoxColumn.Sorted"]/*' /> [ DefaultValue(false), SRCategory(SR.CatBehavior), SRDescription(SR.DataGridView_ComboBoxColumnSortedDescr) ] public bool Sorted { get { if (this.ComboBoxCellTemplate == null) { throw new InvalidOperationException(SR.GetString(SR.DataGridViewColumn_CellTemplateRequired)); } return this.ComboBoxCellTemplate.Sorted; } set { if (this.Sorted != value) { this.ComboBoxCellTemplate.Sorted = value; if (this.DataGridView != null) { DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; int rowCount = dataGridViewRows.Count; for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewComboBoxCell; if (dataGridViewCell != null) { dataGridViewCell.Sorted = value; } } } } } } /// <include file='doc\DataGridViewComboBoxColumn.uex' path='docs/doc[@for="DataGridViewComboBoxColumn.Clone"]/*' /> public override object Clone() { DataGridViewComboBoxColumn dataGridViewColumn; Type thisType = this.GetType(); if (thisType == columnType) //performance improvement { dataGridViewColumn = new DataGridViewComboBoxColumn(); } else { // SECREVIEW : Late-binding does not represent a security thread, see bug#411899 for more info.. // dataGridViewColumn = (DataGridViewComboBoxColumn)System.Activator.CreateInstance(thisType); } if (dataGridViewColumn != null) { base.CloneInternal(dataGridViewColumn); ((DataGridViewComboBoxCell) dataGridViewColumn.CellTemplate).TemplateComboBoxColumn = dataGridViewColumn; } return dataGridViewColumn; } internal void OnItemsCollectionChanged() { // Items collection of the CellTemplate was changed. // Update the items collection of each existing DataGridViewComboBoxCell in the column. if (this.DataGridView != null) { DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows; int rowCount = dataGridViewRows.Count; object[] items = ((DataGridViewComboBoxCell)this.CellTemplate).Items.InnerArray.ToArray(); for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); DataGridViewComboBoxCell dataGridViewCell = dataGridViewRow.Cells[this.Index] as DataGridViewComboBoxCell; if (dataGridViewCell != null) { dataGridViewCell.Items.ClearInternal(); dataGridViewCell.Items.AddRangeInternal(items); } } this.DataGridView.OnColumnCommonChange(this.Index); } } /// <include file='doc\DataGridViewComboBoxColumn.uex' path='docs/doc[@for="DataGridViewComboBoxColumn.ToString"]/*' /> /// <devdoc> /// <para></para> /// </devdoc> public override string ToString() { StringBuilder sb = new StringBuilder(64); sb.Append("DataGridViewComboBoxColumn { Name="); sb.Append(this.Name); sb.Append(", Index="); sb.Append(this.Index.ToString(CultureInfo.CurrentCulture)); sb.Append(" }"); return sb.ToString(); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos/Networking/Responses/UseItemReviveResponse.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace POGOProtos.Networking.Responses { /// <summary>Holder for reflection information generated from POGOProtos/Networking/Responses/UseItemReviveResponse.proto</summary> public static partial class UseItemReviveResponseReflection { #region Descriptor /// <summary>File descriptor for POGOProtos/Networking/Responses/UseItemReviveResponse.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static UseItemReviveResponseReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjtQT0dPUHJvdG9zL05ldHdvcmtpbmcvUmVzcG9uc2VzL1VzZUl0ZW1SZXZp", "dmVSZXNwb25zZS5wcm90bxIfUE9HT1Byb3Rvcy5OZXR3b3JraW5nLlJlc3Bv", "bnNlcyLhAQoVVXNlSXRlbVJldml2ZVJlc3BvbnNlEk0KBnJlc3VsdBgBIAEo", "DjI9LlBPR09Qcm90b3MuTmV0d29ya2luZy5SZXNwb25zZXMuVXNlSXRlbVJl", "dml2ZVJlc3BvbnNlLlJlc3VsdBIPCgdzdGFtaW5hGAIgASgFImgKBlJlc3Vs", "dBIJCgVVTlNFVBAAEgsKB1NVQ0NFU1MQARIUChBFUlJPUl9OT19QT0tFTU9O", "EAISFAoQRVJST1JfQ0FOTk9UX1VTRRADEhoKFkVSUk9SX0RFUExPWUVEX1RP", "X0ZPUlQQBGIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Responses.UseItemReviveResponse), global::POGOProtos.Networking.Responses.UseItemReviveResponse.Parser, new[]{ "Result", "Stamina" }, null, new[]{ typeof(global::POGOProtos.Networking.Responses.UseItemReviveResponse.Types.Result) }, null) })); } #endregion } #region Messages public sealed partial class UseItemReviveResponse : pb::IMessage<UseItemReviveResponse> { private static readonly pb::MessageParser<UseItemReviveResponse> _parser = new pb::MessageParser<UseItemReviveResponse>(() => new UseItemReviveResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<UseItemReviveResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Networking.Responses.UseItemReviveResponseReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UseItemReviveResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UseItemReviveResponse(UseItemReviveResponse other) : this() { result_ = other.result_; stamina_ = other.stamina_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UseItemReviveResponse Clone() { return new UseItemReviveResponse(this); } /// <summary>Field number for the "result" field.</summary> public const int ResultFieldNumber = 1; private global::POGOProtos.Networking.Responses.UseItemReviveResponse.Types.Result result_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Networking.Responses.UseItemReviveResponse.Types.Result Result { get { return result_; } set { result_ = value; } } /// <summary>Field number for the "stamina" field.</summary> public const int StaminaFieldNumber = 2; private int stamina_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Stamina { get { return stamina_; } set { stamina_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as UseItemReviveResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(UseItemReviveResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Result != other.Result) return false; if (Stamina != other.Stamina) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Result != 0) hash ^= Result.GetHashCode(); if (Stamina != 0) hash ^= Stamina.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Result != 0) { output.WriteRawTag(8); output.WriteEnum((int) Result); } if (Stamina != 0) { output.WriteRawTag(16); output.WriteInt32(Stamina); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Result != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result); } if (Stamina != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Stamina); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(UseItemReviveResponse other) { if (other == null) { return; } if (other.Result != 0) { Result = other.Result; } if (other.Stamina != 0) { Stamina = other.Stamina; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { result_ = (global::POGOProtos.Networking.Responses.UseItemReviveResponse.Types.Result) input.ReadEnum(); break; } case 16: { Stamina = input.ReadInt32(); break; } } } } #region Nested types /// <summary>Container for nested types declared in the UseItemReviveResponse message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { public enum Result { [pbr::OriginalName("UNSET")] Unset = 0, [pbr::OriginalName("SUCCESS")] Success = 1, [pbr::OriginalName("ERROR_NO_POKEMON")] ErrorNoPokemon = 2, [pbr::OriginalName("ERROR_CANNOT_USE")] ErrorCannotUse = 3, [pbr::OriginalName("ERROR_DEPLOYED_TO_FORT")] ErrorDeployedToFort = 4, } } #endregion } #endregion } #endregion Designer generated code
/* * 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 System; using System.Collections.Generic; using System.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation { public class LocalSimulationConnectorModule : ISharedRegionModule, ISimulationService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private List<Scene> m_sceneList = new List<Scene>(); private IEntityTransferModule m_AgentTransferModule; protected IEntityTransferModule AgentTransferModule { get { if (m_AgentTransferModule == null) m_AgentTransferModule = m_sceneList[0].RequestModuleInterface<IEntityTransferModule>(); return m_AgentTransferModule; } } private bool m_ModuleEnabled = false; #region IRegionModule public void Initialise(IConfigSource config) { IConfig moduleConfig = config.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("SimulationServices", ""); if (name == Name) { //IConfig userConfig = config.Configs["SimulationService"]; //if (userConfig == null) //{ // m_log.Error("[AVATAR CONNECTOR]: SimulationService missing from OpenSim.ini"); // return; //} m_ModuleEnabled = true; m_log.Info("[SIMULATION CONNECTOR]: Local simulation enabled"); } } } public void PostInitialise() { } public void AddRegion(Scene scene) { if (!m_ModuleEnabled) return; Init(scene); scene.RegisterModuleInterface<ISimulationService>(this); } public void RemoveRegion(Scene scene) { if (!m_ModuleEnabled) return; RemoveScene(scene); scene.UnregisterModuleInterface<ISimulationService>(this); } public void RegionLoaded(Scene scene) { } public void Close() { } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "LocalSimulationConnectorModule"; } } /// <summary> /// Can be called from other modules. /// </summary> /// <param name="scene"></param> public void RemoveScene(Scene scene) { lock (m_sceneList) { if (m_sceneList.Contains(scene)) { m_sceneList.Remove(scene); } } } /// <summary> /// Can be called from other modules. /// </summary> /// <param name="scene"></param> public void Init(Scene scene) { if (!m_sceneList.Contains(scene)) { lock (m_sceneList) { m_sceneList.Add(scene); } } } #endregion /* IRegionModule */ #region ISimulation public IScene GetScene(ulong regionhandle) { foreach (Scene s in m_sceneList) { if (s.RegionInfo.RegionHandle == regionhandle) return s; } // ? weird. should not happen return m_sceneList[0]; } public ISimulationService GetInnerService() { return this; } /** * Agent-related communications */ public bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, out string reason) { if (destination == null) { reason = "Given destination was null"; m_log.DebugFormat("[LOCAL SIMULATION CONNECTOR]: CreateAgent was given a null destination"); return false; } foreach (Scene s in m_sceneList) { if (s.RegionInfo.RegionHandle == destination.RegionHandle) { m_log.DebugFormat("[LOCAL SIMULATION CONNECTOR]: Found region {0} to send SendCreateChildAgent", destination.RegionName); return s.NewUserConnection(aCircuit, teleportFlags, out reason); } } m_log.DebugFormat("[LOCAL SIMULATION CONNECTOR]: Did not find region {0} for SendCreateChildAgent", destination.RegionName); reason = "Did not find region " + destination.RegionName; return false; } public bool UpdateAgent(GridRegion destination, AgentData cAgentData) { if (destination == null) return false; foreach (Scene s in m_sceneList) { if (s.RegionInfo.RegionHandle == destination.RegionHandle) { m_log.DebugFormat( "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate", s.RegionInfo.RegionName, destination.RegionHandle); s.IncomingChildAgentDataUpdate(cAgentData); return true; } } // m_log.DebugFormat("[LOCAL COMMS]: Did not find region {0} for ChildAgentUpdate", regionHandle); return false; } public bool UpdateAgent(GridRegion destination, AgentPosition cAgentData) { if (destination == null) return false; foreach (Scene s in m_sceneList) { if (s.RegionInfo.RegionHandle == destination.RegionHandle) { //m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate"); s.IncomingChildAgentDataUpdate(cAgentData); return true; } } //m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate"); return false; } public bool RetrieveAgent(GridRegion destination, UUID id, out IAgentData agent) { agent = null; if (destination == null) return false; foreach (Scene s in m_sceneList) { if (s.RegionInfo.RegionHandle == destination.RegionHandle) { //m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate"); return s.IncomingRetrieveRootAgent(id, out agent); } } //m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate"); return false; } public bool ReleaseAgent(UUID origin, UUID id, string uri) { foreach (Scene s in m_sceneList) { if (s.RegionInfo.RegionID == origin) { m_log.Debug("[LOCAL COMMS]: Found region to SendReleaseAgent"); AgentTransferModule.AgentArrivedAtDestination(id); return true; // return s.IncomingReleaseAgent(id); } } //m_log.Debug("[LOCAL COMMS]: region not found in SendReleaseAgent " + origin); return false; } public bool CloseAgent(GridRegion destination, UUID id) { if (destination == null) return false; foreach (Scene s in m_sceneList) { if (s.RegionInfo.RegionID == destination.RegionID) { //m_log.Debug("[LOCAL COMMS]: Found region to SendCloseAgent"); return s.IncomingCloseAgent(id); } } //m_log.Debug("[LOCAL COMMS]: region not found in SendCloseAgent"); return false; } /** * Object-related communications */ public bool CreateObject(GridRegion destination, ISceneObject sog, bool isLocalCall) { if (destination == null) return false; foreach (Scene s in m_sceneList) { if (s.RegionInfo.RegionHandle == destination.RegionHandle) { //m_log.Debug("[LOCAL COMMS]: Found region to SendCreateObject"); if (isLocalCall) { // We need to make a local copy of the object ISceneObject sogClone = sog.CloneForNewScene(); sogClone.SetState(sog.GetStateSnapshot(), s); return s.IncomingCreateObject(sogClone); } else { // Use the object as it came through the wire return s.IncomingCreateObject(sog); } } } return false; } public bool CreateObject(GridRegion destination, UUID userID, UUID itemID) { if (destination == null) return false; foreach (Scene s in m_sceneList) { if (s.RegionInfo.RegionHandle == destination.RegionHandle) { return s.IncomingCreateObject(userID, itemID); } } return false; } #endregion /* IInterregionComms */ #region Misc public bool IsLocalRegion(ulong regionhandle) { foreach (Scene s in m_sceneList) if (s.RegionInfo.RegionHandle == regionhandle) return true; return false; } public bool IsLocalRegion(UUID id) { foreach (Scene s in m_sceneList) if (s.RegionInfo.RegionID == id) return true; return false; } #endregion } }
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 BullsAndCows.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) 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 System; using System.Collections; using System.Collections.Specialized; using System.Reflection; using System.IO; using System.Web; using Mono.Addins; using log4net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenMetaverse.Messages.Linden; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using Caps = OpenSim.Framework.Capabilities.Caps; using OSD = OpenMetaverse.StructuredData.OSD; using OSDMap = OpenMetaverse.StructuredData.OSDMap; using OpenSim.Framework.Capabilities; using ExtraParamType = OpenMetaverse.ExtraParamType; namespace OpenSim.Region.CoreModules.Avatar.ObjectCaps { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] public class UploadObjectAssetModule : INonSharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; #region IRegionModuleBase Members public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { } public void AddRegion(Scene pScene) { m_scene = pScene; } public void RemoveRegion(Scene scene) { m_scene.EventManager.OnRegisterCaps -= RegisterCaps; m_scene = null; } public void RegionLoaded(Scene scene) { m_scene.EventManager.OnRegisterCaps += RegisterCaps; } #endregion #region IRegionModule Members public void Close() { } public string Name { get { return "UploadObjectAssetModuleModule"; } } public void RegisterCaps(UUID agentID, Caps caps) { UUID capID = UUID.Random(); // m_log.Debug("[UPLOAD OBJECT ASSET MODULE]: /CAPS/" + capID); caps.RegisterHandler("UploadObjectAsset", new RestHTTPHandler("POST", "/CAPS/OA/" + capID + "/", delegate(Hashtable m_dhttpMethod) { return ProcessAdd(m_dhttpMethod, agentID, caps); })); /* caps.RegisterHandler("NewFileAgentInventoryVariablePrice", new LLSDStreamhandler<LLSDAssetUploadRequest, LLSDNewFileAngentInventoryVariablePriceReplyResponse>("POST", "/CAPS/" + capID.ToString(), delegate(LLSDAssetUploadRequest req) { return NewAgentInventoryRequest(req,agentID); })); */ } #endregion /// <summary> /// Parses ad request /// </summary> /// <param name="request"></param> /// <param name="AgentId"></param> /// <param name="cap"></param> /// <returns></returns> public Hashtable ProcessAdd(Hashtable request, UUID AgentId, Caps cap) { Hashtable responsedata = new Hashtable(); responsedata["int_response_code"] = 400; //501; //410; //404; responsedata["content_type"] = "text/plain"; responsedata["keepalive"] = false; responsedata["str_response_string"] = "Request wasn't what was expected"; ScenePresence avatar; if (!m_scene.TryGetScenePresence(AgentId, out avatar)) return responsedata; OSDMap r = (OSDMap)OSDParser.Deserialize((string)request["requestbody"]); UploadObjectAssetMessage message = new UploadObjectAssetMessage(); try { message.Deserialize(r); } catch (Exception ex) { m_log.Error("[UPLOAD OBJECT ASSET MODULE]: Error deserializing message " + ex.ToString()); message = null; } if (message == null) { responsedata["int_response_code"] = 400; //501; //410; //404; responsedata["content_type"] = "text/plain"; responsedata["keepalive"] = false; responsedata["str_response_string"] = "<llsd><map><key>error</key><string>Error parsing Object</string></map></llsd>"; return responsedata; } Vector3 pos = avatar.AbsolutePosition + (Vector3.UnitX * avatar.Rotation); Quaternion rot = Quaternion.Identity; Vector3 rootpos = Vector3.Zero; // Quaternion rootrot = Quaternion.Identity; SceneObjectGroup rootGroup = null; SceneObjectGroup[] allparts = new SceneObjectGroup[message.Objects.Length]; for (int i = 0; i < message.Objects.Length; i++) { UploadObjectAssetMessage.Object obj = message.Objects[i]; PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox(); if (i == 0) { rootpos = obj.Position; // rootrot = obj.Rotation; } // Combine the extraparams data into it's ugly blob again.... //int bytelength = 0; //for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++) //{ // bytelength += obj.ExtraParams[extparams].ExtraParamData.Length; //} //byte[] extraparams = new byte[bytelength]; //int position = 0; //for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++) //{ // Buffer.BlockCopy(obj.ExtraParams[extparams].ExtraParamData, 0, extraparams, position, // obj.ExtraParams[extparams].ExtraParamData.Length); // // position += obj.ExtraParams[extparams].ExtraParamData.Length; // } //pbs.ExtraParams = extraparams; for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++) { UploadObjectAssetMessage.Object.ExtraParam extraParam = obj.ExtraParams[extparams]; switch ((ushort)extraParam.Type) { case (ushort)ExtraParamType.Sculpt: Primitive.SculptData sculpt = new Primitive.SculptData(extraParam.ExtraParamData, 0); pbs.SculptEntry = true; pbs.SculptTexture = obj.SculptID; pbs.SculptType = (byte)sculpt.Type; break; case (ushort)ExtraParamType.Flexible: Primitive.FlexibleData flex = new Primitive.FlexibleData(extraParam.ExtraParamData, 0); pbs.FlexiEntry = true; pbs.FlexiDrag = flex.Drag; pbs.FlexiForceX = flex.Force.X; pbs.FlexiForceY = flex.Force.Y; pbs.FlexiForceZ = flex.Force.Z; pbs.FlexiGravity = flex.Gravity; pbs.FlexiSoftness = flex.Softness; pbs.FlexiTension = flex.Tension; pbs.FlexiWind = flex.Wind; break; case (ushort)ExtraParamType.Light: Primitive.LightData light = new Primitive.LightData(extraParam.ExtraParamData, 0); pbs.LightColorA = light.Color.A; pbs.LightColorB = light.Color.B; pbs.LightColorG = light.Color.G; pbs.LightColorR = light.Color.R; pbs.LightCutoff = light.Cutoff; pbs.LightEntry = true; pbs.LightFalloff = light.Falloff; pbs.LightIntensity = light.Intensity; pbs.LightRadius = light.Radius; break; case 0x40: pbs.ReadProjectionData(extraParam.ExtraParamData, 0); break; } } pbs.PathBegin = (ushort) obj.PathBegin; pbs.PathCurve = (byte) obj.PathCurve; pbs.PathEnd = (ushort) obj.PathEnd; pbs.PathRadiusOffset = (sbyte) obj.RadiusOffset; pbs.PathRevolutions = (byte) obj.Revolutions; pbs.PathScaleX = (byte) obj.ScaleX; pbs.PathScaleY = (byte) obj.ScaleY; pbs.PathShearX = (byte) obj.ShearX; pbs.PathShearY = (byte) obj.ShearY; pbs.PathSkew = (sbyte) obj.Skew; pbs.PathTaperX = (sbyte) obj.TaperX; pbs.PathTaperY = (sbyte) obj.TaperY; pbs.PathTwist = (sbyte) obj.Twist; pbs.PathTwistBegin = (sbyte) obj.TwistBegin; pbs.HollowShape = (HollowShape) obj.ProfileHollow; pbs.PCode = (byte) PCode.Prim; pbs.ProfileBegin = (ushort) obj.ProfileBegin; pbs.ProfileCurve = (byte) obj.ProfileCurve; pbs.ProfileEnd = (ushort) obj.ProfileEnd; pbs.Scale = obj.Scale; pbs.State = (byte) 0; SceneObjectPart prim = new SceneObjectPart(); prim.UUID = UUID.Random(); prim.CreatorID = AgentId; prim.OwnerID = AgentId; prim.GroupID = obj.GroupID; prim.LastOwnerID = prim.OwnerID; prim.CreationDate = Util.UnixTimeSinceEpoch(); prim.Name = obj.Name; prim.Description = ""; prim.PayPrice[0] = -2; prim.PayPrice[1] = -2; prim.PayPrice[2] = -2; prim.PayPrice[3] = -2; prim.PayPrice[4] = -2; Primitive.TextureEntry tmp = new Primitive.TextureEntry(UUID.Parse("89556747-24cb-43ed-920b-47caed15465f")); for (int j = 0; j < obj.Faces.Length; j++) { UploadObjectAssetMessage.Object.Face face = obj.Faces[j]; Primitive.TextureEntryFace primFace = tmp.CreateFace((uint) j); primFace.Bump = face.Bump; primFace.RGBA = face.Color; primFace.Fullbright = face.Fullbright; primFace.Glow = face.Glow; primFace.TextureID = face.ImageID; primFace.Rotation = face.ImageRot; primFace.MediaFlags = ((face.MediaFlags & 1) != 0); primFace.OffsetU = face.OffsetS; primFace.OffsetV = face.OffsetT; primFace.RepeatU = face.ScaleS; primFace.RepeatV = face.ScaleT; primFace.TexMapType = (MappingType) (face.MediaFlags & 6); } pbs.TextureEntry = tmp.GetBytes(); prim.Shape = pbs; prim.Scale = obj.Scale; SceneObjectGroup grp = new SceneObjectGroup(); grp.SetRootPart(prim); prim.ParentID = 0; if (i == 0) { rootGroup = grp; } grp.AttachToScene(m_scene); grp.AbsolutePosition = obj.Position; prim.RotationOffset = obj.Rotation; grp.RootPart.IsAttachment = false; // Required for linking grp.RootPart.UpdateFlag = 0; if (m_scene.Permissions.CanRezObject(1, avatar.UUID, pos)) { m_scene.AddSceneObject(grp); grp.AbsolutePosition = obj.Position; } allparts[i] = grp; } for (int j = 1; j < allparts.Length; j++) { rootGroup.RootPart.UpdateFlag = 0; allparts[j].RootPart.UpdateFlag = 0; rootGroup.LinkToGroup(allparts[j]); } rootGroup.ScheduleGroupForFullUpdate(); pos = m_scene.GetNewRezLocation(Vector3.Zero, rootpos, UUID.Zero, rot, (byte)1, 1, true, allparts[0].GroupScale(), false); responsedata["int_response_code"] = 200; //501; //410; //404; responsedata["content_type"] = "text/plain"; responsedata["keepalive"] = false; responsedata["str_response_string"] = String.Format("<llsd><map><key>local_id</key>{0}</map></llsd>", ConvertUintToBytes(allparts[0].LocalId)); return responsedata; } private string ConvertUintToBytes(uint val) { byte[] resultbytes = Utils.UIntToBytes(val); if (BitConverter.IsLittleEndian) Array.Reverse(resultbytes); return String.Format("<binary encoding=\"base64\">{0}</binary>", Convert.ToBase64String(resultbytes)); } } }
#region Copyright //////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2015 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 16.10Release // Tag = development-akw-16.10.00-0 //////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.IO; namespace FickleFrostbite.FIT { /// <summary> /// Implements the ObdiiData profile message. /// </summary> public class ObdiiDataMesg : Mesg { #region Fields #endregion #region Constructors public ObdiiDataMesg() : base(Profile.mesgs[Profile.ObdiiDataIndex]) { } public ObdiiDataMesg(Mesg mesg) : base(mesg) { } #endregion // Constructors #region Methods ///<summary> /// Retrieves the Timestamp field /// Units: s /// Comment: Timestamp message was output</summary> /// <returns>Returns DateTime representing the Timestamp field</returns> public DateTime GetTimestamp() { return TimestampToDateTime((uint?)GetFieldValue(253, 0, Fit.SubfieldIndexMainField)); } /// <summary> /// Set Timestamp field /// Units: s /// Comment: Timestamp message was output</summary> /// <param name="timestamp_">Nullable field value to be set</param> public void SetTimestamp(DateTime timestamp_) { SetFieldValue(253, 0, timestamp_.GetTimeStamp(), Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the TimestampMs field /// Units: ms /// Comment: Fractional part of timestamp, added to timestamp</summary> /// <returns>Returns nullable ushort representing the TimestampMs field</returns> public ushort? GetTimestampMs() { return (ushort?)GetFieldValue(0, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set TimestampMs field /// Units: ms /// Comment: Fractional part of timestamp, added to timestamp</summary> /// <param name="timestampMs_">Nullable field value to be set</param> public void SetTimestampMs(ushort? timestampMs_) { SetFieldValue(0, 0, timestampMs_, Fit.SubfieldIndexMainField); } /// <summary> /// /// </summary> /// <returns>returns number of elements in field TimeOffset</returns> public int GetNumTimeOffset() { return GetNumFieldValues(1, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the TimeOffset field /// Units: ms /// Comment: Offset of PID reading [i] from start_timestamp+start_timestamp_ms. Readings may span accross seconds.</summary> /// <param name="index">0 based index of TimeOffset element to retrieve</param> /// <returns>Returns nullable ushort representing the TimeOffset field</returns> public ushort? GetTimeOffset(int index) { return (ushort?)GetFieldValue(1, index, Fit.SubfieldIndexMainField); } /// <summary> /// Set TimeOffset field /// Units: ms /// Comment: Offset of PID reading [i] from start_timestamp+start_timestamp_ms. Readings may span accross seconds.</summary> /// <param name="index">0 based index of time_offset</param> /// <param name="timeOffset_">Nullable field value to be set</param> public void SetTimeOffset(int index, ushort? timeOffset_) { SetFieldValue(1, index, timeOffset_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Pid field /// Comment: Parameter ID</summary> /// <returns>Returns nullable byte representing the Pid field</returns> public byte? GetPid() { return (byte?)GetFieldValue(2, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Pid field /// Comment: Parameter ID</summary> /// <param name="pid_">Nullable field value to be set</param> public void SetPid(byte? pid_) { SetFieldValue(2, 0, pid_, Fit.SubfieldIndexMainField); } /// <summary> /// /// </summary> /// <returns>returns number of elements in field RawData</returns> public int GetNumRawData() { return GetNumFieldValues(3, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the RawData field /// Comment: Raw parameter data</summary> /// <param name="index">0 based index of RawData element to retrieve</param> /// <returns>Returns nullable byte representing the RawData field</returns> public byte? GetRawData(int index) { return (byte?)GetFieldValue(3, index, Fit.SubfieldIndexMainField); } /// <summary> /// Set RawData field /// Comment: Raw parameter data</summary> /// <param name="index">0 based index of raw_data</param> /// <param name="rawData_">Nullable field value to be set</param> public void SetRawData(int index, byte? rawData_) { SetFieldValue(3, index, rawData_, Fit.SubfieldIndexMainField); } /// <summary> /// /// </summary> /// <returns>returns number of elements in field PidDataSize</returns> public int GetNumPidDataSize() { return GetNumFieldValues(4, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the PidDataSize field /// Comment: Optional, data size of PID[i]. If not specified refer to SAE J1979.</summary> /// <param name="index">0 based index of PidDataSize element to retrieve</param> /// <returns>Returns nullable byte representing the PidDataSize field</returns> public byte? GetPidDataSize(int index) { return (byte?)GetFieldValue(4, index, Fit.SubfieldIndexMainField); } /// <summary> /// Set PidDataSize field /// Comment: Optional, data size of PID[i]. If not specified refer to SAE J1979.</summary> /// <param name="index">0 based index of pid_data_size</param> /// <param name="pidDataSize_">Nullable field value to be set</param> public void SetPidDataSize(int index, byte? pidDataSize_) { SetFieldValue(4, index, pidDataSize_, Fit.SubfieldIndexMainField); } /// <summary> /// /// </summary> /// <returns>returns number of elements in field SystemTime</returns> public int GetNumSystemTime() { return GetNumFieldValues(5, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the SystemTime field /// Comment: System time associated with sample expressed in ms, can be used instead of time_offset. There will be a system_time value for each raw_data element. For multibyte pids the system_time is repeated.</summary> /// <param name="index">0 based index of SystemTime element to retrieve</param> /// <returns>Returns nullable uint representing the SystemTime field</returns> public uint? GetSystemTime(int index) { return (uint?)GetFieldValue(5, index, Fit.SubfieldIndexMainField); } /// <summary> /// Set SystemTime field /// Comment: System time associated with sample expressed in ms, can be used instead of time_offset. There will be a system_time value for each raw_data element. For multibyte pids the system_time is repeated.</summary> /// <param name="index">0 based index of system_time</param> /// <param name="systemTime_">Nullable field value to be set</param> public void SetSystemTime(int index, uint? systemTime_) { SetFieldValue(5, index, systemTime_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the StartTimestamp field /// Comment: Timestamp of first sample recorded in the message. Used with time_offset to generate time of each sample</summary> /// <returns>Returns DateTime representing the StartTimestamp field</returns> public DateTime GetStartTimestamp() { return TimestampToDateTime((uint?)GetFieldValue(6, 0, Fit.SubfieldIndexMainField)); } /// <summary> /// Set StartTimestamp field /// Comment: Timestamp of first sample recorded in the message. Used with time_offset to generate time of each sample</summary> /// <param name="startTimestamp_">Nullable field value to be set</param> public void SetStartTimestamp(DateTime startTimestamp_) { SetFieldValue(6, 0, startTimestamp_.GetTimeStamp(), Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the StartTimestampMs field /// Units: ms /// Comment: Fractional part of start_timestamp</summary> /// <returns>Returns nullable ushort representing the StartTimestampMs field</returns> public ushort? GetStartTimestampMs() { return (ushort?)GetFieldValue(7, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set StartTimestampMs field /// Units: ms /// Comment: Fractional part of start_timestamp</summary> /// <param name="startTimestampMs_">Nullable field value to be set</param> public void SetStartTimestampMs(ushort? startTimestampMs_) { SetFieldValue(7, 0, startTimestampMs_, Fit.SubfieldIndexMainField); } #endregion // Methods } // Class } // namespace
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the elasticloadbalancing-2012-06-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ElasticLoadBalancing.Model { /// <summary> /// Container for the parameters to the CreateLoadBalancer operation. /// Creates a new load balancer. /// /// /// <para> /// After the call has completed successfully, a new load balancer is created with a /// unique Domain Name Service (DNS) name. The DNS name includes the name of the AWS region /// in which the load balance was created. For example, if your load balancer was created /// in the United States, the DNS name might end with either of the following: /// </para> /// <ul> <li> <i>us-east-1.elb.amazonaws.com</i> (for the Northern Virginia region) </li> /// <li> <i>us-west-1.elb.amazonaws.com</i> (for the Northern California region) </li> /// </ul> /// <para> /// For information about the AWS regions supported by Elastic Load Balancing, see <a /// href="http://docs.aws.amazon.com/general/latest/gr/rande.html#elb_region">Regions /// and Endpoints</a>. /// </para> /// /// <para> /// You can create up to 20 load balancers per region per account. /// </para> /// /// <para> /// Elastic Load Balancing supports load balancing your Amazon EC2 instances launched /// within any one of the following platforms: /// </para> /// <ul> <li> <i>EC2-Classic</i> /// <para> /// For information on creating and managing your load balancers in EC2-Classic, see <a /// href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/UserScenariosForEC2.html">Deploy /// Elastic Load Balancing in Amazon EC2-Classic</a>. /// </para> /// </li> <li> <i>EC2-VPC</i> /// <para> /// For information on creating and managing your load balancers in EC2-VPC, see <a href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/UserScenariosForVPC.html">Deploy /// Elastic Load Balancing in Amazon VPC</a>. /// </para> /// </li> </ul> /// </summary> public partial class CreateLoadBalancerRequest : AmazonElasticLoadBalancingRequest { private List<string> _availabilityZones = new List<string>(); private List<Listener> _listeners = new List<Listener>(); private string _loadBalancerName; private string _scheme; private List<string> _securityGroups = new List<string>(); private List<string> _subnets = new List<string>(); private List<Tag> _tags = new List<Tag>(); /// <summary> /// Empty constructor used to set properties independently even when a simple constructor is available /// </summary> public CreateLoadBalancerRequest() { } /// <summary> /// Instantiates CreateLoadBalancerRequest with the parameterized properties /// </summary> /// <param name="loadBalancerName"> The name associated with the load balancer. The name must be unique within your set of load balancers, must have a maximum of 32 characters, and must only contain alphanumeric characters or hyphens. </param> public CreateLoadBalancerRequest(string loadBalancerName) { _loadBalancerName = loadBalancerName; } /// <summary> /// Instantiates CreateLoadBalancerRequest with the parameterized properties /// </summary> /// <param name="loadBalancerName"> The name associated with the load balancer. The name must be unique within your set of load balancers, must have a maximum of 32 characters, and must only contain alphanumeric characters or hyphens. </param> /// <param name="listeners"> A list of the following tuples: Protocol, LoadBalancerPort, InstanceProtocol, InstancePort, and SSLCertificateId. For information about the protocols and the ports supported by Elastic Load Balancing, see <a href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/elb-listener-config.html">Listener Configurations for Elastic Load Balancing</a>.</param> /// <param name="availabilityZones"> A list of Availability Zones. At least one Availability Zone must be specified. Specified Availability Zones must be in the same EC2 Region as the load balancer. Traffic will be equally distributed across all zones. You can later add more Availability Zones after the creation of the load balancer by calling <a>EnableAvailabilityZonesForLoadBalancer</a> action. </param> public CreateLoadBalancerRequest(string loadBalancerName, List<Listener> listeners, List<string> availabilityZones) { _loadBalancerName = loadBalancerName; _listeners = listeners; _availabilityZones = availabilityZones; } /// <summary> /// Gets and sets the property AvailabilityZones. /// <para> /// A list of Availability Zones. /// </para> /// /// <para> /// At least one Availability Zone must be specified. Specified Availability Zones must /// be in the same EC2 Region as the load balancer. Traffic will be equally distributed /// across all zones. /// </para> /// /// <para> /// You can later add more Availability Zones after the creation of the load balancer /// by calling <a>EnableAvailabilityZonesForLoadBalancer</a> action. /// </para> /// </summary> public List<string> AvailabilityZones { get { return this._availabilityZones; } set { this._availabilityZones = value; } } // Check to see if AvailabilityZones property is set internal bool IsSetAvailabilityZones() { return this._availabilityZones != null && this._availabilityZones.Count > 0; } /// <summary> /// Gets and sets the property Listeners. /// <para> /// A list of the following tuples: Protocol, LoadBalancerPort, InstanceProtocol, InstancePort, /// and SSLCertificateId. /// </para> /// /// <para> /// For information about the protocols and the ports supported by Elastic Load Balancing, /// see <a href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/elb-listener-config.html">Listener /// Configurations for Elastic Load Balancing</a>. /// </para> /// </summary> public List<Listener> Listeners { get { return this._listeners; } set { this._listeners = value; } } // Check to see if Listeners property is set internal bool IsSetListeners() { return this._listeners != null && this._listeners.Count > 0; } /// <summary> /// Gets and sets the property LoadBalancerName. /// <para> /// The name associated with the load balancer. /// </para> /// /// <para> /// The name must be unique within your set of load balancers, must have a maximum of /// 32 characters, and must only contain alphanumeric characters or hyphens. /// </para> /// </summary> public string LoadBalancerName { get { return this._loadBalancerName; } set { this._loadBalancerName = value; } } // Check to see if LoadBalancerName property is set internal bool IsSetLoadBalancerName() { return this._loadBalancerName != null; } /// <summary> /// Gets and sets the property Scheme. /// <para> /// The type of a load balancer. /// </para> /// /// <para> /// By default, Elastic Load Balancing creates an Internet-facing load balancer with a /// publicly resolvable DNS name, which resolves to public IP addresses. For more information /// about Internet-facing and Internal load balancers, see <a href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/vpc-loadbalancer-types.html">Internet-facing /// and Internal Load Balancers</a>. /// </para> /// /// <para> /// Specify the value <code>internal</code> for this option to create an internal load /// balancer with a DNS name that resolves to private IP addresses. /// </para> /// <note> /// <para> /// This option is only available for load balancers created within EC2-VPC. /// </para> /// </note> /// </summary> public string Scheme { get { return this._scheme; } set { this._scheme = value; } } // Check to see if Scheme property is set internal bool IsSetScheme() { return this._scheme != null; } /// <summary> /// Gets and sets the property SecurityGroups. /// <para> /// The security groups to assign to your load balancer within your VPC. /// </para> /// </summary> public List<string> SecurityGroups { get { return this._securityGroups; } set { this._securityGroups = value; } } // Check to see if SecurityGroups property is set internal bool IsSetSecurityGroups() { return this._securityGroups != null && this._securityGroups.Count > 0; } /// <summary> /// Gets and sets the property Subnets. /// <para> /// A list of subnet IDs in your VPC to attach to your load balancer. Specify one subnet /// per Availability Zone. /// </para> /// </summary> public List<string> Subnets { get { return this._subnets; } set { this._subnets = value; } } // Check to see if Subnets property is set internal bool IsSetSubnets() { return this._subnets != null && this._subnets.Count > 0; } /// <summary> /// Gets and sets the property Tags. /// <para> /// A list of tags to assign to the load balancer. /// </para> /// /// <para> /// For more information about setting tags for your load balancer, see <a href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#tagging-elb">Tagging</a>. /// </para> /// </summary> public List<Tag> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } } }
// // Utilities.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Generated by /CodeGen/cecil-gen.rb do not edit // Tue Jul 17 00:22:33 +0200 2007 // // (C) 2005 Jb Evain // // 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 Mono.Cecil.Metadata { using System; using System.Collections; using System.IO; class Utilities { Utilities () { } public static int ReadCompressedInteger (byte [] data, int pos, out int start) { int integer = 0; start = pos; if ((data [pos] & 0x80) == 0) { integer = data [pos]; start++; } else if ((data [pos] & 0x40) == 0) { integer = (data [start] & ~0x80) << 8; integer |= data [pos + 1]; start += 2; } else { integer = (data [start] & ~0xc0) << 24; integer |= data [pos + 1] << 16; integer |= data [pos + 2] << 8; integer |= data [pos + 3]; start += 4; } return integer; } public static int WriteCompressedInteger (BinaryWriter writer, int value) { if (value < 0x80) writer.Write ((byte) value); else if (value < 0x4000) { writer.Write ((byte) (0x80 | (value >> 8))); writer.Write ((byte) (value & 0xff)); } else { writer.Write ((byte) ((value >> 24) | 0xc0)); writer.Write ((byte) ((value >> 16) & 0xff)); writer.Write ((byte) ((value >> 8) & 0xff)); writer.Write ((byte) (value & 0xff)); } return (int) writer.BaseStream.Position; } public static MetadataToken GetMetadataToken (CodedIndex cidx, uint data) { uint rid = 0; switch (cidx) { case CodedIndex.TypeDefOrRef : rid = data >> 2; switch (data & 3) { case 0 : return new MetadataToken (TokenType.TypeDef, rid); case 1 : return new MetadataToken (TokenType.TypeRef, rid); case 2 : return new MetadataToken (TokenType.TypeSpec, rid); default : return MetadataToken.Zero; } case CodedIndex.HasConstant : rid = data >> 2; switch (data & 3) { case 0 : return new MetadataToken (TokenType.Field, rid); case 1 : return new MetadataToken (TokenType.Param, rid); case 2 : return new MetadataToken (TokenType.Property, rid); default : return MetadataToken.Zero; } case CodedIndex.HasCustomAttribute : rid = data >> 5; switch (data & 31) { case 0 : return new MetadataToken (TokenType.Method, rid); case 1 : return new MetadataToken (TokenType.Field, rid); case 2 : return new MetadataToken (TokenType.TypeRef, rid); case 3 : return new MetadataToken (TokenType.TypeDef, rid); case 4 : return new MetadataToken (TokenType.Param, rid); case 5 : return new MetadataToken (TokenType.InterfaceImpl, rid); case 6 : return new MetadataToken (TokenType.MemberRef, rid); case 7 : return new MetadataToken (TokenType.Module, rid); case 8 : return new MetadataToken (TokenType.Permission, rid); case 9 : return new MetadataToken (TokenType.Property, rid); case 10 : return new MetadataToken (TokenType.Event, rid); case 11 : return new MetadataToken (TokenType.Signature, rid); case 12 : return new MetadataToken (TokenType.ModuleRef, rid); case 13 : return new MetadataToken (TokenType.TypeSpec, rid); case 14 : return new MetadataToken (TokenType.Assembly, rid); case 15 : return new MetadataToken (TokenType.AssemblyRef, rid); case 16 : return new MetadataToken (TokenType.File, rid); case 17 : return new MetadataToken (TokenType.ExportedType, rid); case 18 : return new MetadataToken (TokenType.ManifestResource, rid); case 19 : return new MetadataToken (TokenType.GenericParam, rid); default : return MetadataToken.Zero; } case CodedIndex.HasFieldMarshal : rid = data >> 1; switch (data & 1) { case 0 : return new MetadataToken (TokenType.Field, rid); case 1 : return new MetadataToken (TokenType.Param, rid); default : return MetadataToken.Zero; } case CodedIndex.HasDeclSecurity : rid = data >> 2; switch (data & 3) { case 0 : return new MetadataToken (TokenType.TypeDef, rid); case 1 : return new MetadataToken (TokenType.Method, rid); case 2 : return new MetadataToken (TokenType.Assembly, rid); default : return MetadataToken.Zero; } case CodedIndex.MemberRefParent : rid = data >> 3; switch (data & 7) { case 0 : return new MetadataToken (TokenType.TypeDef, rid); case 1 : return new MetadataToken (TokenType.TypeRef, rid); case 2 : return new MetadataToken (TokenType.ModuleRef, rid); case 3 : return new MetadataToken (TokenType.Method, rid); case 4 : return new MetadataToken (TokenType.TypeSpec, rid); default : return MetadataToken.Zero; } case CodedIndex.HasSemantics : rid = data >> 1; switch (data & 1) { case 0 : return new MetadataToken (TokenType.Event, rid); case 1 : return new MetadataToken (TokenType.Property, rid); default : return MetadataToken.Zero; } case CodedIndex.MethodDefOrRef : rid = data >> 1; switch (data & 1) { case 0 : return new MetadataToken (TokenType.Method, rid); case 1 : return new MetadataToken (TokenType.MemberRef, rid); default : return MetadataToken.Zero; } case CodedIndex.MemberForwarded : rid = data >> 1; switch (data & 1) { case 0 : return new MetadataToken (TokenType.Field, rid); case 1 : return new MetadataToken (TokenType.Method, rid); default : return MetadataToken.Zero; } case CodedIndex.Implementation : rid = data >> 2; switch (data & 3) { case 0 : return new MetadataToken (TokenType.File, rid); case 1 : return new MetadataToken (TokenType.AssemblyRef, rid); case 2 : return new MetadataToken (TokenType.ExportedType, rid); default : return MetadataToken.Zero; } case CodedIndex.CustomAttributeType : rid = data >> 3; switch (data & 7) { case 2 : return new MetadataToken (TokenType.Method, rid); case 3 : return new MetadataToken (TokenType.MemberRef, rid); default : return MetadataToken.Zero; } case CodedIndex.ResolutionScope : rid = data >> 2; switch (data & 3) { case 0 : return new MetadataToken (TokenType.Module, rid); case 1 : return new MetadataToken (TokenType.ModuleRef, rid); case 2 : return new MetadataToken (TokenType.AssemblyRef, rid); case 3 : return new MetadataToken (TokenType.TypeRef, rid); default : return MetadataToken.Zero; } case CodedIndex.TypeOrMethodDef : rid = data >> 1; switch (data & 1) { case 0 : return new MetadataToken (TokenType.TypeDef, rid); case 1 : return new MetadataToken (TokenType.Method, rid); default : return MetadataToken.Zero; } default : return MetadataToken.Zero; } } public static uint CompressMetadataToken (CodedIndex cidx, MetadataToken token) { uint ret = 0; if (token.RID == 0) return ret; switch (cidx) { case CodedIndex.TypeDefOrRef : ret = token.RID << 2; switch (token.TokenType) { case TokenType.TypeDef : return ret | 0; case TokenType.TypeRef : return ret | 1; case TokenType.TypeSpec : return ret | 2; default : throw new MetadataFormatException("Non valid Token for TypeDefOrRef"); } case CodedIndex.HasConstant : ret = token.RID << 2; switch (token.TokenType) { case TokenType.Field : return ret | 0; case TokenType.Param : return ret | 1; case TokenType.Property : return ret | 2; default : throw new MetadataFormatException("Non valid Token for HasConstant"); } case CodedIndex.HasCustomAttribute : ret = token.RID << 5; switch (token.TokenType) { case TokenType.Method : return ret | 0; case TokenType.Field : return ret | 1; case TokenType.TypeRef : return ret | 2; case TokenType.TypeDef : return ret | 3; case TokenType.Param : return ret | 4; case TokenType.InterfaceImpl : return ret | 5; case TokenType.MemberRef : return ret | 6; case TokenType.Module : return ret | 7; case TokenType.Permission : return ret | 8; case TokenType.Property : return ret | 9; case TokenType.Event : return ret | 10; case TokenType.Signature : return ret | 11; case TokenType.ModuleRef : return ret | 12; case TokenType.TypeSpec : return ret | 13; case TokenType.Assembly : return ret | 14; case TokenType.AssemblyRef : return ret | 15; case TokenType.File : return ret | 16; case TokenType.ExportedType : return ret | 17; case TokenType.ManifestResource : return ret | 18; case TokenType.GenericParam : return ret | 19; default : throw new MetadataFormatException("Non valid Token for HasCustomAttribute"); } case CodedIndex.HasFieldMarshal : ret = token.RID << 1; switch (token.TokenType) { case TokenType.Field : return ret | 0; case TokenType.Param : return ret | 1; default : throw new MetadataFormatException("Non valid Token for HasFieldMarshal"); } case CodedIndex.HasDeclSecurity : ret = token.RID << 2; switch (token.TokenType) { case TokenType.TypeDef : return ret | 0; case TokenType.Method : return ret | 1; case TokenType.Assembly : return ret | 2; default : throw new MetadataFormatException("Non valid Token for HasDeclSecurity"); } case CodedIndex.MemberRefParent : ret = token.RID << 3; switch (token.TokenType) { case TokenType.TypeDef : return ret | 0; case TokenType.TypeRef : return ret | 1; case TokenType.ModuleRef : return ret | 2; case TokenType.Method : return ret | 3; case TokenType.TypeSpec : return ret | 4; default : throw new MetadataFormatException("Non valid Token for MemberRefParent"); } case CodedIndex.HasSemantics : ret = token.RID << 1; switch (token.TokenType) { case TokenType.Event : return ret | 0; case TokenType.Property : return ret | 1; default : throw new MetadataFormatException("Non valid Token for HasSemantics"); } case CodedIndex.MethodDefOrRef : ret = token.RID << 1; switch (token.TokenType) { case TokenType.Method : return ret | 0; case TokenType.MemberRef : return ret | 1; default : throw new MetadataFormatException("Non valid Token for MethodDefOrRef"); } case CodedIndex.MemberForwarded : ret = token.RID << 1; switch (token.TokenType) { case TokenType.Field : return ret | 0; case TokenType.Method : return ret | 1; default : throw new MetadataFormatException("Non valid Token for MemberForwarded"); } case CodedIndex.Implementation : ret = token.RID << 2; switch (token.TokenType) { case TokenType.File : return ret | 0; case TokenType.AssemblyRef : return ret | 1; case TokenType.ExportedType : return ret | 2; default : throw new MetadataFormatException("Non valid Token for Implementation"); } case CodedIndex.CustomAttributeType : ret = token.RID << 3; switch (token.TokenType) { case TokenType.Method : return ret | 2; case TokenType.MemberRef : return ret | 3; default : throw new MetadataFormatException("Non valid Token for CustomAttributeType"); } case CodedIndex.ResolutionScope : ret = token.RID << 2; switch (token.TokenType) { case TokenType.Module : return ret | 0; case TokenType.ModuleRef : return ret | 1; case TokenType.AssemblyRef : return ret | 2; case TokenType.TypeRef : return ret | 3; default : throw new MetadataFormatException("Non valid Token for ResolutionScope"); } case CodedIndex.TypeOrMethodDef : ret = token.RID << 1; switch (token.TokenType) { case TokenType.TypeDef : return ret | 0; case TokenType.Method : return ret | 1; default : throw new MetadataFormatException("Non valid Token for TypeOrMethodDef"); } default : throw new MetadataFormatException ("Non valid CodedIndex"); } } /* internal static Type GetCorrespondingTable (TokenType t) { switch (t) { case TokenType.Assembly : return typeof (AssemblyTable); case TokenType.AssemblyRef : return typeof (AssemblyRefTable); case TokenType.CustomAttribute : return typeof (CustomAttributeTable); case TokenType.Event : return typeof (EventTable); case TokenType.ExportedType : return typeof (ExportedTypeTable); case TokenType.Field : return typeof (FieldTable); case TokenType.File : return typeof (FileTable); case TokenType.InterfaceImpl : return typeof (InterfaceImplTable); case TokenType.MemberRef : return typeof (MemberRefTable); case TokenType.Method : return typeof (MethodTable); case TokenType.Module : return typeof (ModuleTable); case TokenType.ModuleRef : return typeof (ModuleRefTable); case TokenType.Param : return typeof (ParamTable); case TokenType.Permission : return typeof (DeclSecurityTable); case TokenType.Property : return typeof (PropertyTable); case TokenType.Signature : return typeof (StandAloneSigTable); case TokenType.TypeDef : return typeof (TypeDefTable); case TokenType.TypeRef : return typeof (TypeRefTable); case TokenType.TypeSpec : return typeof (TypeSpecTable); default : return null; } } internal delegate int TableRowCounter (int rid); internal static int GetCodedIndexSize (CodedIndex ci, TableRowCounter rowCounter, IDictionary codedIndexCache) { int bits = 0, max = 0; if (codedIndexCache [ci] != null) return (int) codedIndexCache [ci]; int res = 0; int [] rids; switch (ci) { case CodedIndex.TypeDefOrRef : bits = 2; rids = new int [3]; rids [0] = TypeDefTable.RId; rids [1] = TypeRefTable.RId; rids [2] = TypeSpecTable.RId; break; case CodedIndex.HasConstant : bits = 2; rids = new int [3]; rids [0] = FieldTable.RId; rids [1] = ParamTable.RId; rids [2] = PropertyTable.RId; break; case CodedIndex.HasCustomAttribute : bits = 5; rids = new int [20]; rids [0] = MethodTable.RId; rids [1] = FieldTable.RId; rids [2] = TypeRefTable.RId; rids [3] = TypeDefTable.RId; rids [4] = ParamTable.RId; rids [5] = InterfaceImplTable.RId; rids [6] = MemberRefTable.RId; rids [7] = ModuleTable.RId; rids [8] = DeclSecurityTable.RId; rids [9] = PropertyTable.RId; rids [10] = EventTable.RId; rids [11] = StandAloneSigTable.RId; rids [12] = ModuleRefTable.RId; rids [13] = TypeSpecTable.RId; rids [14] = AssemblyTable.RId; rids [15] = AssemblyRefTable.RId; rids [16] = FileTable.RId; rids [17] = ExportedTypeTable.RId; rids [18] = ManifestResourceTable.RId; rids [19] = GenericParamTable.RId; break; case CodedIndex.HasFieldMarshal : bits = 1; rids = new int [2]; rids [0] = FieldTable.RId; rids [1] = ParamTable.RId; break; case CodedIndex.HasDeclSecurity : bits = 2; rids = new int [3]; rids [0] = TypeDefTable.RId; rids [1] = MethodTable.RId; rids [2] = AssemblyTable.RId; break; case CodedIndex.MemberRefParent : bits = 3; rids = new int [5]; rids [0] = TypeDefTable.RId; rids [1] = TypeRefTable.RId; rids [2] = ModuleRefTable.RId; rids [3] = MethodTable.RId; rids [4] = TypeSpecTable.RId; break; case CodedIndex.HasSemantics : bits = 1; rids = new int [2]; rids [0] = EventTable.RId; rids [1] = PropertyTable.RId; break; case CodedIndex.MethodDefOrRef : bits = 1; rids = new int [2]; rids [0] = MethodTable.RId; rids [1] = MemberRefTable.RId; break; case CodedIndex.MemberForwarded : bits = 1; rids = new int [2]; rids [0] = FieldTable.RId; rids [1] = MethodTable.RId; break; case CodedIndex.Implementation : bits = 2; rids = new int [3]; rids [0] = FileTable.RId; rids [1] = AssemblyRefTable.RId; rids [2] = ExportedTypeTable.RId; break; case CodedIndex.CustomAttributeType : bits = 3; rids = new int [2]; rids [0] = MethodTable.RId; rids [1] = MemberRefTable.RId; break; case CodedIndex.ResolutionScope : bits = 2; rids = new int [4]; rids [0] = ModuleTable.RId; rids [1] = ModuleRefTable.RId; rids [2] = AssemblyRefTable.RId; rids [3] = TypeRefTable.RId; break; case CodedIndex.TypeOrMethodDef : bits = 1; rids = new int [2]; rids [0] = TypeDefTable.RId; rids [1] = MethodTable.RId; break; default : throw new MetadataFormatException ("Non valid CodedIndex"); } for (int i = 0; i < rids.Length; i++) { int rows = rowCounter (rids [i]); if (rows > max) max = rows; } res = max < (1 << (16 - bits)) ? 2 : 4; codedIndexCache [ci] = res; return res; } */ } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the PnPlanilla class. /// </summary> [Serializable] public partial class PnPlanillaCollection : ActiveList<PnPlanilla, PnPlanillaCollection> { public PnPlanillaCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnPlanillaCollection</returns> public PnPlanillaCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnPlanilla o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_planillas table. /// </summary> [Serializable] public partial class PnPlanilla : ActiveRecord<PnPlanilla>, IActiveRecord { #region .ctors and Default Settings public PnPlanilla() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnPlanilla(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnPlanilla(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnPlanilla(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_planillas", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdPlanillas = new TableSchema.TableColumn(schema); colvarIdPlanillas.ColumnName = "id_planillas"; colvarIdPlanillas.DataType = DbType.Int32; colvarIdPlanillas.MaxLength = 0; colvarIdPlanillas.AutoIncrement = true; colvarIdPlanillas.IsNullable = false; colvarIdPlanillas.IsPrimaryKey = true; colvarIdPlanillas.IsForeignKey = false; colvarIdPlanillas.IsReadOnly = false; colvarIdPlanillas.DefaultSetting = @""; colvarIdPlanillas.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdPlanillas); TableSchema.TableColumn colvarIdAgenteInscriptor = new TableSchema.TableColumn(schema); colvarIdAgenteInscriptor.ColumnName = "id_agente_inscriptor"; colvarIdAgenteInscriptor.DataType = DbType.Int32; colvarIdAgenteInscriptor.MaxLength = 0; colvarIdAgenteInscriptor.AutoIncrement = false; colvarIdAgenteInscriptor.IsNullable = false; colvarIdAgenteInscriptor.IsPrimaryKey = false; colvarIdAgenteInscriptor.IsForeignKey = false; colvarIdAgenteInscriptor.IsReadOnly = false; colvarIdAgenteInscriptor.DefaultSetting = @""; colvarIdAgenteInscriptor.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdAgenteInscriptor); TableSchema.TableColumn colvarIdEntrega = new TableSchema.TableColumn(schema); colvarIdEntrega.ColumnName = "id_entrega"; colvarIdEntrega.DataType = DbType.Int32; colvarIdEntrega.MaxLength = 0; colvarIdEntrega.AutoIncrement = false; colvarIdEntrega.IsNullable = false; colvarIdEntrega.IsPrimaryKey = false; colvarIdEntrega.IsForeignKey = false; colvarIdEntrega.IsReadOnly = false; colvarIdEntrega.DefaultSetting = @""; colvarIdEntrega.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEntrega); TableSchema.TableColumn colvarIdRecibe = new TableSchema.TableColumn(schema); colvarIdRecibe.ColumnName = "id_recibe"; colvarIdRecibe.DataType = DbType.Int32; colvarIdRecibe.MaxLength = 0; colvarIdRecibe.AutoIncrement = false; colvarIdRecibe.IsNullable = false; colvarIdRecibe.IsPrimaryKey = false; colvarIdRecibe.IsForeignKey = false; colvarIdRecibe.IsReadOnly = false; colvarIdRecibe.DefaultSetting = @""; colvarIdRecibe.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdRecibe); TableSchema.TableColumn colvarPeriodo = new TableSchema.TableColumn(schema); colvarPeriodo.ColumnName = "periodo"; colvarPeriodo.DataType = DbType.AnsiString; colvarPeriodo.MaxLength = -1; colvarPeriodo.AutoIncrement = false; colvarPeriodo.IsNullable = true; colvarPeriodo.IsPrimaryKey = false; colvarPeriodo.IsForeignKey = false; colvarPeriodo.IsReadOnly = false; colvarPeriodo.DefaultSetting = @""; colvarPeriodo.ForeignKeyTableName = ""; schema.Columns.Add(colvarPeriodo); TableSchema.TableColumn colvarCantNino = new TableSchema.TableColumn(schema); colvarCantNino.ColumnName = "cant_nino"; colvarCantNino.DataType = DbType.Int32; colvarCantNino.MaxLength = 0; colvarCantNino.AutoIncrement = false; colvarCantNino.IsNullable = true; colvarCantNino.IsPrimaryKey = false; colvarCantNino.IsForeignKey = false; colvarCantNino.IsReadOnly = false; colvarCantNino.DefaultSetting = @""; colvarCantNino.ForeignKeyTableName = ""; schema.Columns.Add(colvarCantNino); TableSchema.TableColumn colvarCantEmbarazada = new TableSchema.TableColumn(schema); colvarCantEmbarazada.ColumnName = "cant_embarazada"; colvarCantEmbarazada.DataType = DbType.Int32; colvarCantEmbarazada.MaxLength = 0; colvarCantEmbarazada.AutoIncrement = false; colvarCantEmbarazada.IsNullable = true; colvarCantEmbarazada.IsPrimaryKey = false; colvarCantEmbarazada.IsForeignKey = false; colvarCantEmbarazada.IsReadOnly = false; colvarCantEmbarazada.DefaultSetting = @""; colvarCantEmbarazada.ForeignKeyTableName = ""; schema.Columns.Add(colvarCantEmbarazada); TableSchema.TableColumn colvarMotivo = new TableSchema.TableColumn(schema); colvarMotivo.ColumnName = "motivo"; colvarMotivo.DataType = DbType.AnsiString; colvarMotivo.MaxLength = -1; colvarMotivo.AutoIncrement = false; colvarMotivo.IsNullable = true; colvarMotivo.IsPrimaryKey = false; colvarMotivo.IsForeignKey = false; colvarMotivo.IsReadOnly = false; colvarMotivo.DefaultSetting = @""; colvarMotivo.ForeignKeyTableName = ""; schema.Columns.Add(colvarMotivo); TableSchema.TableColumn colvarUsuario = new TableSchema.TableColumn(schema); colvarUsuario.ColumnName = "usuario"; colvarUsuario.DataType = DbType.AnsiString; colvarUsuario.MaxLength = -1; colvarUsuario.AutoIncrement = false; colvarUsuario.IsNullable = true; colvarUsuario.IsPrimaryKey = false; colvarUsuario.IsForeignKey = false; colvarUsuario.IsReadOnly = false; colvarUsuario.DefaultSetting = @""; colvarUsuario.ForeignKeyTableName = ""; schema.Columns.Add(colvarUsuario); TableSchema.TableColumn colvarTipo = new TableSchema.TableColumn(schema); colvarTipo.ColumnName = "tipo"; colvarTipo.DataType = DbType.AnsiString; colvarTipo.MaxLength = -1; colvarTipo.AutoIncrement = false; colvarTipo.IsNullable = true; colvarTipo.IsPrimaryKey = false; colvarTipo.IsForeignKey = false; colvarTipo.IsReadOnly = false; colvarTipo.DefaultSetting = @""; colvarTipo.ForeignKeyTableName = ""; schema.Columns.Add(colvarTipo); TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema); colvarIdEfector.ColumnName = "id_efector"; colvarIdEfector.DataType = DbType.AnsiString; colvarIdEfector.MaxLength = -1; colvarIdEfector.AutoIncrement = false; colvarIdEfector.IsNullable = true; colvarIdEfector.IsPrimaryKey = false; colvarIdEfector.IsForeignKey = false; colvarIdEfector.IsReadOnly = false; colvarIdEfector.DefaultSetting = @""; colvarIdEfector.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEfector); TableSchema.TableColumn colvarFechaHora = new TableSchema.TableColumn(schema); colvarFechaHora.ColumnName = "fecha_hora"; colvarFechaHora.DataType = DbType.DateTime; colvarFechaHora.MaxLength = 0; colvarFechaHora.AutoIncrement = false; colvarFechaHora.IsNullable = true; colvarFechaHora.IsPrimaryKey = false; colvarFechaHora.IsForeignKey = false; colvarFechaHora.IsReadOnly = false; colvarFechaHora.DefaultSetting = @""; colvarFechaHora.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaHora); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_planillas",schema); } } #endregion #region Props [XmlAttribute("IdPlanillas")] [Bindable(true)] public int IdPlanillas { get { return GetColumnValue<int>(Columns.IdPlanillas); } set { SetColumnValue(Columns.IdPlanillas, value); } } [XmlAttribute("IdAgenteInscriptor")] [Bindable(true)] public int IdAgenteInscriptor { get { return GetColumnValue<int>(Columns.IdAgenteInscriptor); } set { SetColumnValue(Columns.IdAgenteInscriptor, value); } } [XmlAttribute("IdEntrega")] [Bindable(true)] public int IdEntrega { get { return GetColumnValue<int>(Columns.IdEntrega); } set { SetColumnValue(Columns.IdEntrega, value); } } [XmlAttribute("IdRecibe")] [Bindable(true)] public int IdRecibe { get { return GetColumnValue<int>(Columns.IdRecibe); } set { SetColumnValue(Columns.IdRecibe, value); } } [XmlAttribute("Periodo")] [Bindable(true)] public string Periodo { get { return GetColumnValue<string>(Columns.Periodo); } set { SetColumnValue(Columns.Periodo, value); } } [XmlAttribute("CantNino")] [Bindable(true)] public int? CantNino { get { return GetColumnValue<int?>(Columns.CantNino); } set { SetColumnValue(Columns.CantNino, value); } } [XmlAttribute("CantEmbarazada")] [Bindable(true)] public int? CantEmbarazada { get { return GetColumnValue<int?>(Columns.CantEmbarazada); } set { SetColumnValue(Columns.CantEmbarazada, value); } } [XmlAttribute("Motivo")] [Bindable(true)] public string Motivo { get { return GetColumnValue<string>(Columns.Motivo); } set { SetColumnValue(Columns.Motivo, value); } } [XmlAttribute("Usuario")] [Bindable(true)] public string Usuario { get { return GetColumnValue<string>(Columns.Usuario); } set { SetColumnValue(Columns.Usuario, value); } } [XmlAttribute("Tipo")] [Bindable(true)] public string Tipo { get { return GetColumnValue<string>(Columns.Tipo); } set { SetColumnValue(Columns.Tipo, value); } } [XmlAttribute("IdEfector")] [Bindable(true)] public string IdEfector { get { return GetColumnValue<string>(Columns.IdEfector); } set { SetColumnValue(Columns.IdEfector, value); } } [XmlAttribute("FechaHora")] [Bindable(true)] public DateTime? FechaHora { get { return GetColumnValue<DateTime?>(Columns.FechaHora); } set { SetColumnValue(Columns.FechaHora, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdAgenteInscriptor,int varIdEntrega,int varIdRecibe,string varPeriodo,int? varCantNino,int? varCantEmbarazada,string varMotivo,string varUsuario,string varTipo,string varIdEfector,DateTime? varFechaHora) { PnPlanilla item = new PnPlanilla(); item.IdAgenteInscriptor = varIdAgenteInscriptor; item.IdEntrega = varIdEntrega; item.IdRecibe = varIdRecibe; item.Periodo = varPeriodo; item.CantNino = varCantNino; item.CantEmbarazada = varCantEmbarazada; item.Motivo = varMotivo; item.Usuario = varUsuario; item.Tipo = varTipo; item.IdEfector = varIdEfector; item.FechaHora = varFechaHora; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdPlanillas,int varIdAgenteInscriptor,int varIdEntrega,int varIdRecibe,string varPeriodo,int? varCantNino,int? varCantEmbarazada,string varMotivo,string varUsuario,string varTipo,string varIdEfector,DateTime? varFechaHora) { PnPlanilla item = new PnPlanilla(); item.IdPlanillas = varIdPlanillas; item.IdAgenteInscriptor = varIdAgenteInscriptor; item.IdEntrega = varIdEntrega; item.IdRecibe = varIdRecibe; item.Periodo = varPeriodo; item.CantNino = varCantNino; item.CantEmbarazada = varCantEmbarazada; item.Motivo = varMotivo; item.Usuario = varUsuario; item.Tipo = varTipo; item.IdEfector = varIdEfector; item.FechaHora = varFechaHora; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdPlanillasColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdAgenteInscriptorColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdEntregaColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn IdRecibeColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn PeriodoColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn CantNinoColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn CantEmbarazadaColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn MotivoColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn UsuarioColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn TipoColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn IdEfectorColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn FechaHoraColumn { get { return Schema.Columns[11]; } } #endregion #region Columns Struct public struct Columns { public static string IdPlanillas = @"id_planillas"; public static string IdAgenteInscriptor = @"id_agente_inscriptor"; public static string IdEntrega = @"id_entrega"; public static string IdRecibe = @"id_recibe"; public static string Periodo = @"periodo"; public static string CantNino = @"cant_nino"; public static string CantEmbarazada = @"cant_embarazada"; public static string Motivo = @"motivo"; public static string Usuario = @"usuario"; public static string Tipo = @"tipo"; public static string IdEfector = @"id_efector"; public static string FechaHora = @"fecha_hora"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gagr = Google.Api.Gax.ResourceNames; using gcnv = Google.Cloud.NetworkSecurity.V1Beta1; using sys = System; namespace Google.Cloud.NetworkSecurity.V1Beta1 { /// <summary>Resource name for the <c>ClientTlsPolicy</c> resource.</summary> public sealed partial class ClientTlsPolicyName : gax::IResourceName, sys::IEquatable<ClientTlsPolicyName> { /// <summary>The possible contents of <see cref="ClientTlsPolicyName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}</c>. /// </summary> ProjectLocationClientTlsPolicy = 1, } private static gax::PathTemplate s_projectLocationClientTlsPolicy = new gax::PathTemplate("projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}"); /// <summary>Creates a <see cref="ClientTlsPolicyName"/> 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="ClientTlsPolicyName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static ClientTlsPolicyName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ClientTlsPolicyName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ClientTlsPolicyName"/> with the pattern /// <c>projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}</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="clientTlsPolicyId">The <c>ClientTlsPolicy</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ClientTlsPolicyName"/> constructed from the provided ids.</returns> public static ClientTlsPolicyName FromProjectLocationClientTlsPolicy(string projectId, string locationId, string clientTlsPolicyId) => new ClientTlsPolicyName(ResourceNameType.ProjectLocationClientTlsPolicy, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), clientTlsPolicyId: gax::GaxPreconditions.CheckNotNullOrEmpty(clientTlsPolicyId, nameof(clientTlsPolicyId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ClientTlsPolicyName"/> with pattern /// <c>projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}</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="clientTlsPolicyId">The <c>ClientTlsPolicy</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ClientTlsPolicyName"/> with pattern /// <c>projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}</c>. /// </returns> public static string Format(string projectId, string locationId, string clientTlsPolicyId) => FormatProjectLocationClientTlsPolicy(projectId, locationId, clientTlsPolicyId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ClientTlsPolicyName"/> with pattern /// <c>projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}</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="clientTlsPolicyId">The <c>ClientTlsPolicy</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ClientTlsPolicyName"/> with pattern /// <c>projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}</c>. /// </returns> public static string FormatProjectLocationClientTlsPolicy(string projectId, string locationId, string clientTlsPolicyId) => s_projectLocationClientTlsPolicy.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(clientTlsPolicyId, nameof(clientTlsPolicyId))); /// <summary> /// Parses the given resource name string into a new <see cref="ClientTlsPolicyName"/> 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}/clientTlsPolicies/{client_tls_policy}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="clientTlsPolicyName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ClientTlsPolicyName"/> if successful.</returns> public static ClientTlsPolicyName Parse(string clientTlsPolicyName) => Parse(clientTlsPolicyName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ClientTlsPolicyName"/> 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}/clientTlsPolicies/{client_tls_policy}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="clientTlsPolicyName">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="ClientTlsPolicyName"/> if successful.</returns> public static ClientTlsPolicyName Parse(string clientTlsPolicyName, bool allowUnparsed) => TryParse(clientTlsPolicyName, allowUnparsed, out ClientTlsPolicyName 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="ClientTlsPolicyName"/> 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}/clientTlsPolicies/{client_tls_policy}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="clientTlsPolicyName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ClientTlsPolicyName"/>, 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 clientTlsPolicyName, out ClientTlsPolicyName result) => TryParse(clientTlsPolicyName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ClientTlsPolicyName"/> 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}/clientTlsPolicies/{client_tls_policy}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="clientTlsPolicyName">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="ClientTlsPolicyName"/>, 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 clientTlsPolicyName, bool allowUnparsed, out ClientTlsPolicyName result) { gax::GaxPreconditions.CheckNotNull(clientTlsPolicyName, nameof(clientTlsPolicyName)); gax::TemplatedResourceName resourceName; if (s_projectLocationClientTlsPolicy.TryParseName(clientTlsPolicyName, out resourceName)) { result = FromProjectLocationClientTlsPolicy(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(clientTlsPolicyName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ClientTlsPolicyName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string clientTlsPolicyId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; ClientTlsPolicyId = clientTlsPolicyId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="ClientTlsPolicyName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}</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="clientTlsPolicyId">The <c>ClientTlsPolicy</c> ID. Must not be <c>null</c> or empty.</param> public ClientTlsPolicyName(string projectId, string locationId, string clientTlsPolicyId) : this(ResourceNameType.ProjectLocationClientTlsPolicy, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), clientTlsPolicyId: gax::GaxPreconditions.CheckNotNullOrEmpty(clientTlsPolicyId, nameof(clientTlsPolicyId))) { } /// <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>ClientTlsPolicy</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string ClientTlsPolicyId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationClientTlsPolicy: return s_projectLocationClientTlsPolicy.Expand(ProjectId, LocationId, ClientTlsPolicyId); 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 ClientTlsPolicyName); /// <inheritdoc/> public bool Equals(ClientTlsPolicyName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ClientTlsPolicyName a, ClientTlsPolicyName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ClientTlsPolicyName a, ClientTlsPolicyName b) => !(a == b); } public partial class ClientTlsPolicy { /// <summary> /// <see cref="gcnv::ClientTlsPolicyName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcnv::ClientTlsPolicyName ClientTlsPolicyName { get => string.IsNullOrEmpty(Name) ? null : gcnv::ClientTlsPolicyName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListClientTlsPoliciesRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetClientTlsPolicyRequest { /// <summary> /// <see cref="gcnv::ClientTlsPolicyName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcnv::ClientTlsPolicyName ClientTlsPolicyName { get => string.IsNullOrEmpty(Name) ? null : gcnv::ClientTlsPolicyName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreateClientTlsPolicyRequest { /// <summary> /// <see cref="ClientTlsPolicyName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public ClientTlsPolicyName ParentAsClientTlsPolicyName { get => string.IsNullOrEmpty(Parent) ? null : ClientTlsPolicyName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class DeleteClientTlsPolicyRequest { /// <summary> /// <see cref="gcnv::ClientTlsPolicyName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcnv::ClientTlsPolicyName ClientTlsPolicyName { get => string.IsNullOrEmpty(Name) ? null : gcnv::ClientTlsPolicyName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
#region Copyright // // Nini Configuration Project. // // Copyright (C) 2014 Nicholas Omann. All rights reserved. // Copyright (C) 2006 Brent R. Matzelle. All rights reserved. // // This software is published under the terms of the MIT X11 license, a copy of // which has been included with this distribution in the LICENSE.txt file. // #endregion using System; using System.IO; using Nini.Config; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Xml; namespace Nini.Test.Config { [TestClass] public class DotNetConfigSourceTests { #region Tests [TestMethod] public void GetConfig () { XmlDocument doc = NiniDoc (); AddSection (doc, "Pets"); AddKey (doc, "Pets", "cat", "muffy"); AddKey (doc, "Pets", "dog", "rover"); AddKey (doc, "Pets", "bird", "tweety"); DotNetConfigSource source = new DotNetConfigSource (DocumentToReader (doc)); IConfig config = source.Configs["Pets"]; Assert.AreEqual ("Pets", config.Name); Assert.AreEqual (3, config.GetKeys ().Length); Assert.AreEqual (source, config.ConfigSource); } [TestMethod] public void GetString () { XmlDocument doc = NiniDoc (); AddSection (doc, "Pets"); AddKey (doc, "Pets", "cat", "muffy"); AddKey (doc, "Pets", "dog", "rover"); AddKey (doc, "Pets", "bird", "tweety"); DotNetConfigSource source = new DotNetConfigSource (DocumentToReader (doc)); IConfig config = source.Configs["Pets"]; Assert.AreEqual ("muffy", config.Get ("cat")); Assert.AreEqual ("rover", config.Get ("dog")); Assert.AreEqual ("muffy", config.GetString ("cat")); Assert.AreEqual ("rover", config.GetString ("dog")); Assert.AreEqual ("my default", config.Get ("Not Here", "my default")); Assert.IsNull (config.Get ("Not Here 2")); } [TestMethod] public void GetInt () { XmlDocument doc = NiniDoc (); AddSection (doc, "Pets"); AddKey (doc, "Pets", "value 1", "49588"); DotNetConfigSource source = new DotNetConfigSource (DocumentToReader (doc)); IConfig config = source.Configs["Pets"]; Assert.AreEqual (49588, config.GetInt ("value 1")); Assert.AreEqual (12345, config.GetInt ("Not Here", 12345)); try { config.GetInt ("Not Here Also"); Assert.Fail (); } catch { } } [TestMethod] public void SetAndSave () { string filePath = "Test.xml"; XmlDocument doc = NiniDoc (); AddSection (doc, "NewSection"); AddKey (doc, "NewSection", "dog", "Rover"); AddKey (doc, "NewSection", "cat", "Muffy"); doc.Save (filePath); DotNetConfigSource source = new DotNetConfigSource (filePath); IConfig config = source.Configs["NewSection"]; Assert.AreEqual ("Rover", config.Get ("dog")); Assert.AreEqual ("Muffy", config.Get ("cat")); config.Set ("dog", "Spots"); config.Set ("cat", "Misha"); config.Set ("DoesNotExist", "SomeValue"); Assert.AreEqual ("Spots", config.Get ("dog")); Assert.AreEqual ("Misha", config.Get ("cat")); Assert.AreEqual ("SomeValue", config.Get ("DoesNotExist")); source.Save (); source = new DotNetConfigSource (filePath); config = source.Configs["NewSection"]; Assert.AreEqual ("Spots", config.Get ("dog")); Assert.AreEqual ("Misha", config.Get ("cat")); Assert.AreEqual ("SomeValue", config.Get ("DoesNotExist")); File.Delete (filePath); } [TestMethod] public void MergeAndSave () { string xmlFileName = "NiniConfig.xml"; XmlDocument doc = NiniDoc (); AddSection (doc, "Pets"); AddKey (doc, "Pets", "cat", "Muffy"); AddKey (doc, "Pets", "dog", "Rover"); AddKey (doc, "Pets", "bird", "Tweety"); doc.Save (xmlFileName); StringWriter writer = new StringWriter (); writer.WriteLine ("[Pets]"); writer.WriteLine ("cat = Becky"); // overwrite writer.WriteLine ("lizard = Saurus"); // new writer.WriteLine ("[People]"); writer.WriteLine (" woman = Jane"); writer.WriteLine (" man = John"); IniConfigSource iniSource = new IniConfigSource (new StringReader (writer.ToString ())); DotNetConfigSource xmlSource = new DotNetConfigSource (xmlFileName); xmlSource.Merge (iniSource); IConfig config = xmlSource.Configs["Pets"]; Assert.AreEqual (4, config.GetKeys ().Length); Assert.AreEqual ("Becky", config.Get ("cat")); Assert.AreEqual ("Rover", config.Get ("dog")); Assert.AreEqual ("Saurus", config.Get ("lizard")); config = xmlSource.Configs["People"]; Assert.AreEqual (2, config.GetKeys ().Length); Assert.AreEqual ("Jane", config.Get ("woman")); Assert.AreEqual ("John", config.Get ("man")); config.Set ("woman", "Tara"); config.Set ("man", "Quentin"); xmlSource.Save (); xmlSource = new DotNetConfigSource (xmlFileName); config = xmlSource.Configs["Pets"]; Assert.AreEqual (4, config.GetKeys ().Length); Assert.AreEqual ("Becky", config.Get ("cat")); Assert.AreEqual ("Rover", config.Get ("dog")); Assert.AreEqual ("Saurus", config.Get ("lizard")); config = xmlSource.Configs["People"]; Assert.AreEqual (2, config.GetKeys ().Length); Assert.AreEqual ("Tara", config.Get ("woman")); Assert.AreEqual ("Quentin", config.Get ("man")); File.Delete (xmlFileName); } [TestMethod] public void SaveToNewPath () { string filePath = "Test.xml"; string newPath = "TestNew.xml"; XmlDocument doc = NiniDoc (); AddSection (doc, "Pets"); AddKey (doc, "Pets", "cat", "Muffy"); AddKey (doc, "Pets", "dog", "Rover"); doc.Save (filePath); DotNetConfigSource source = new DotNetConfigSource (filePath); IConfig config = source.Configs["Pets"]; Assert.AreEqual ("Rover", config.Get ("dog")); Assert.AreEqual ("Muffy", config.Get ("cat")); source.Save (newPath); source = new DotNetConfigSource (newPath); config = source.Configs["Pets"]; Assert.AreEqual ("Rover", config.Get ("dog")); Assert.AreEqual ("Muffy", config.Get ("cat")); File.Delete (filePath); File.Delete (newPath); } [TestMethod] public void SaveToWriter () { string newPath = "TestNew.xml"; XmlDocument doc = NiniDoc (); AddSection (doc, "Pets"); AddKey (doc, "Pets", "cat", "Muffy"); AddKey (doc, "Pets","dog", "Rover"); DotNetConfigSource source = new DotNetConfigSource (DocumentToReader (doc)); IConfig config = source.Configs["Pets"]; Assert.AreEqual ("Rover", config.Get ("dog")); Assert.AreEqual ("Muffy", config.Get ("cat")); StreamWriter textWriter = new StreamWriter (newPath); source.Save (textWriter); textWriter.Close (); // save to disk source = new DotNetConfigSource (newPath); config = source.Configs["Pets"]; Assert.AreEqual ("Rover", config.Get ("dog")); Assert.AreEqual ("Muffy", config.Get ("cat")); File.Delete (newPath); } [TestMethod] public void ReplaceText () { XmlDocument doc = NiniDoc (); AddSection (doc, "Test"); AddKey (doc, "Test", "author", "Brent"); AddKey (doc, "Test", "domain", "${protocol}://nini.sf.net/"); AddKey (doc, "Test", "apache", "Apache implements ${protocol}"); AddKey (doc, "Test", "developer", "author of Nini: ${author} !"); AddKey (doc, "Test", "love", "We love the ${protocol} protocol"); AddKey (doc, "Test", "combination", "${author} likes ${protocol}"); AddKey (doc, "Test", "fact", "fact: ${apache}"); AddKey (doc, "Test", "protocol", "http"); DotNetConfigSource source = new DotNetConfigSource (DocumentToReader (doc)); source.ReplaceKeyValues (); IConfig config = source.Configs["Test"]; Assert.AreEqual ("http", config.Get ("protocol")); Assert.AreEqual ("fact: Apache implements http", config.Get ("fact")); Assert.AreEqual ("http://nini.sf.net/", config.Get ("domain")); Assert.AreEqual ("Apache implements http", config.Get ("apache")); Assert.AreEqual ("We love the http protocol", config.Get ("love")); Assert.AreEqual ("author of Nini: Brent !", config.Get ("developer")); Assert.AreEqual ("Brent likes http", config.Get ("combination")); } [TestMethod] public void SaveNewSection () { string filePath = "Test.xml"; XmlDocument doc = NiniDoc (); AddSection (doc, "NewSection"); AddKey (doc, "NewSection", "dog", "Rover"); AddKey (doc, "NewSection", "cat", "Muffy"); doc.Save (filePath); DotNetConfigSource source = new DotNetConfigSource (filePath); IConfig config = source.AddConfig ("test"); Assert.IsNotNull (source.Configs["test"]); source.Save (); source = new DotNetConfigSource (filePath); config = source.Configs["NewSection"]; Assert.AreEqual ("Rover", config.Get ("dog")); Assert.AreEqual ("Muffy", config.Get ("cat")); Assert.IsNotNull (source.Configs["test"]); File.Delete (filePath); } [TestMethod] public void ToStringTest () { XmlDocument doc = NiniDoc (); AddSection (doc, "Pets"); AddKey (doc, "Pets", "cat", "Muffy"); AddKey (doc, "Pets", "dog", "Rover"); DotNetConfigSource source = new DotNetConfigSource (DocumentToReader (doc)); string eol = Environment.NewLine; string compare = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" + eol + "<configuration>" + eol + " <configSections>" + eol + " <section name=\"Pets\" " + "type=\"System.Configuration.NameValueSectionHandler\" />" + eol + " </configSections>" + eol + " <Pets>" + eol + " <add key=\"cat\" value=\"Muffy\" />" + eol + " <add key=\"dog\" value=\"Rover\" />" + eol + " </Pets>" + eol + "</configuration>"; Assert.AreEqual (compare, source.ToString ()); } [TestMethod] public void EmptyConstructor () { string filePath = "EmptyConstructor.xml"; DotNetConfigSource source = new DotNetConfigSource (); IConfig config = source.AddConfig ("Pets"); config.Set ("cat", "Muffy"); config.Set ("dog", "Rover"); config.Set ("bird", "Tweety"); source.Save (filePath); Assert.AreEqual (3, config.GetKeys ().Length); Assert.AreEqual ("Muffy", config.Get ("cat")); Assert.AreEqual ("Rover", config.Get ("dog")); Assert.AreEqual ("Tweety", config.Get ("bird")); source = new DotNetConfigSource (filePath); config = source.Configs["Pets"]; Assert.AreEqual (3, config.GetKeys ().Length); Assert.AreEqual ("Muffy", config.Get ("cat")); Assert.AreEqual ("Rover", config.Get ("dog")); Assert.AreEqual ("Tweety", config.Get ("bird")); File.Delete (filePath); } [TestMethod] public void Reload () { string filePath = "ReloadDot.xml"; DotNetConfigSource source = new DotNetConfigSource (); IConfig petConfig = source.AddConfig ("Pets"); petConfig.Set ("cat", "Muffy"); petConfig.Set ("dog", "Rover"); IConfig weatherConfig = source.AddConfig ("Weather"); weatherConfig.Set ("skies", "cloudy"); weatherConfig.Set ("precipitation", "rain"); source.Save (filePath); Assert.AreEqual (2, petConfig.GetKeys ().Length); Assert.AreEqual ("Muffy", petConfig.Get ("cat")); Assert.AreEqual (2, source.Configs.Count); DotNetConfigSource newSource = new DotNetConfigSource (filePath); IConfig compareConfig = newSource.Configs["Pets"]; Assert.AreEqual (2, compareConfig.GetKeys ().Length); Assert.AreEqual ("Muffy", compareConfig.Get ("cat")); Assert.IsTrue (compareConfig == newSource.Configs["Pets"], "References before are not equal"); // Set the new values to source source.Configs["Pets"].Set ("cat", "Misha"); source.Configs["Pets"].Set ("lizard", "Lizzy"); source.Configs["Pets"].Set ("hampster", "Surly"); source.Configs["Pets"].Remove ("dog"); source.Configs.Remove (weatherConfig); source.Save (); // saves new value // Reload the new source and check for changes newSource.Reload (); Assert.IsTrue (compareConfig == newSource.Configs["Pets"], "References after are not equal"); Assert.AreEqual (1, newSource.Configs.Count); Assert.AreEqual (3, newSource.Configs["Pets"].GetKeys ().Length); Assert.AreEqual ("Lizzy", newSource.Configs["Pets"].Get ("lizard")); Assert.AreEqual ("Misha", newSource.Configs["Pets"].Get ("cat")); Assert.IsNull (newSource.Configs["Pets"].Get ("dog")); File.Delete (filePath); } [TestMethod] public void SaveToStream () { string filePath = "SaveToStream.ini"; FileStream stream = new FileStream (filePath, FileMode.Create); // Create a new document and save to stream DotNetConfigSource source = new DotNetConfigSource (); IConfig config = source.AddConfig ("Pets"); config.Set ("dog", "rover"); config.Set ("cat", "muffy"); source.Save (stream); stream.Close (); DotNetConfigSource newSource = new DotNetConfigSource (filePath); config = newSource.Configs["Pets"]; Assert.IsNotNull (config); Assert.AreEqual (2, config.GetKeys ().Length); Assert.AreEqual ("rover", config.GetString ("dog")); Assert.AreEqual ("muffy", config.GetString ("cat")); stream.Close (); File.Delete (filePath); } [TestMethod] public void NoConfigSectionsNode () { string filePath = "AppSettings.xml"; // Create an XML document with no configSections node XmlDocument doc = new XmlDocument (); doc.LoadXml ("<configuration></configuration>"); XmlNode node = doc.CreateElement ("appSettings"); doc.DocumentElement.AppendChild (node); AddKey (doc, "appSettings", "Test", "Hello"); doc.Save (filePath); DotNetConfigSource source = new DotNetConfigSource (filePath); IConfig config = source.Configs["appSettings"]; Assert.AreEqual ("Hello", config.GetString ("Test")); File.Delete (filePath); } [TestMethod] public void LoadReader () { XmlDocument doc = NiniDoc (); AddSection (doc, "Pets"); AddKey (doc, "Pets", "cat", "muffy"); AddKey (doc, "Pets", "dog", "rover"); AddKey (doc, "Pets", "bird", "tweety"); DotNetConfigSource source = new DotNetConfigSource (DocumentToReader (doc)); IConfig config = source.Configs["Pets"]; Assert.AreEqual (3, config.GetKeys ().Length); Assert.AreEqual ("rover", config.Get ("dog")); config.Set ("dog", "new name"); config.Remove ("bird"); source.Load (DocumentToReader (doc)); config = source.Configs["Pets"]; Assert.AreEqual (3, config.GetKeys ().Length); Assert.AreEqual ("rover", config.Get ("dog")); } #endregion #region Private methods private XmlDocument NiniDoc () { XmlDocument doc = new XmlDocument (); doc.LoadXml ("<configuration><configSections/></configuration>"); return doc; } private void AddSection (XmlDocument doc, string sectionName) { XmlNode node = doc.SelectSingleNode ("/configuration/configSections"); XmlNode sectionNode = doc.CreateElement ("section"); node.AppendChild (sectionNode); XmlNode attrNode = doc.CreateAttribute ("name"); attrNode.Value = sectionName; sectionNode.Attributes.SetNamedItem (attrNode); attrNode = doc.CreateAttribute ("type"); attrNode.Value = "System.Configuration.NameValueSectionHandler"; sectionNode.Attributes.SetNamedItem (attrNode); if (sectionName.IndexOf (' ') != -1) { Console.WriteLine (sectionName); } sectionNode = doc.CreateElement (sectionName); doc.DocumentElement.AppendChild (sectionNode); } private void AddKey (XmlDocument doc, string section, string key, string value) { XmlNode sectionNode = doc.SelectSingleNode ("/configuration/" + section); XmlNode keyNode = doc.CreateElement ("add"); XmlNode attrNode = doc.CreateAttribute ("key"); attrNode.Value = key; keyNode.Attributes.SetNamedItem (attrNode); attrNode = doc.CreateAttribute ("value"); attrNode.Value = value; keyNode.Attributes.SetNamedItem (attrNode); sectionNode.AppendChild (keyNode); } private XmlTextReader DocumentToReader (XmlDocument doc) { StringReader reader = new StringReader (doc.OuterXml); return new XmlTextReader (reader); } #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.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.DotNet.CodeFormatting.Rules { /// <summary> /// Mark any fields that can provably be marked as readonly. /// </summary> [GlobalSemanticRule(MarkReadonlyFieldsRule.Name, MarkReadonlyFieldsRule.Description, GlobalSemanticRuleOrder.MarkReadonlyFieldsRule, DefaultRule = false)] internal sealed class MarkReadonlyFieldsRule : IGlobalSemanticFormattingRule { internal const string Name = "ReadonlyFields"; internal const string Description = "Mark fields which can be readonly as readonly"; private readonly SemaphoreSlim _processUsagesLock = new SemaphoreSlim(1, 1); private ConcurrentDictionary<IFieldSymbol, bool> _unwrittenWritableFields; public bool SupportsLanguage(string languageName) { return languageName == LanguageNames.CSharp; } public async Task<Solution> ProcessAsync( Document document, SyntaxNode syntaxRoot, CancellationToken cancellationToken) { if (_unwrittenWritableFields == null) { using (await SemaphoreLock.GetAsync(_processUsagesLock)) { // A global analysis must be run before we can do any actual processing, because a field might // be written in a different file than it is declared (even private ones may be split between // partial classes). // It's also quite expensive, which is why it's being done inside the lock, so // that the entire solution is not processed for each input file individually if (_unwrittenWritableFields == null) { List<Document> allDocuments = document.Project.Solution.Projects.SelectMany(p => p.Documents).ToList(); HashSet<IFieldSymbol>[] fields = await Task.WhenAll( allDocuments .AsParallel() .Select( doc => WritableFieldScanner.Scan(doc, cancellationToken))); var writableFields = new ConcurrentDictionary<IFieldSymbol, bool>( fields.SelectMany(s => s).Select(f => new KeyValuePair<IFieldSymbol, bool>(f, true))); await Task.WhenAll( allDocuments.AsParallel() .Select( doc => WriteUsagesScanner.RemoveWrittenFields( doc, writableFields, cancellationToken))); _unwrittenWritableFields = writableFields; } } } if (_unwrittenWritableFields.Count == 0) { // If there are no unwritten writable fields, skip all the rewriting return document.Project.Solution; } SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken); var application = new ReadonlyRewriter( _unwrittenWritableFields, await document.GetSemanticModelAsync(cancellationToken)); return document.Project.Solution.WithDocumentSyntaxRoot(document.Id, application.Visit(root)); } /// <summary> /// This is the first walker, which looks for fields that are valid to transform to readonly. /// It returns any private or internal fields that are not already marked readonly, and returns a hash set /// of them. Internal fields are only considered if the "InternalsVisibleTo" is a reference to something /// in the same solution, since it's possible to analyse the global usages of it. Otherwise there is an /// assembly we don't have access to that can see that field, so we have to treat is as public. /// </summary> private sealed class WritableFieldScanner : CSharpSyntaxWalker { private static readonly HashSet<string> s_serializingFieldAttributes = new HashSet<string> { "System.ComponentModel.Composition.ImportAttribute", "System.ComponentModel.Composition.ImportManyAttribute", }; private readonly HashSet<IFieldSymbol> _fields = new HashSet<IFieldSymbol>(); private readonly ISymbol _internalsVisibleToAttribute; private readonly SemanticModel _model; private WritableFieldScanner(SemanticModel model) { _model = model; _internalsVisibleToAttribute = model.Compilation.GetTypeByMetadataName( "System.Runtime.CompilerServices.InternalsVisibleToAttribute"); } public static async Task<HashSet<IFieldSymbol>> Scan( Document document, CancellationToken cancellationToken) { var scanner = new WritableFieldScanner( await document.GetSemanticModelAsync(cancellationToken)); scanner.Visit(await document.GetSyntaxRootAsync(cancellationToken)); return scanner._fields; } public override void VisitFieldDeclaration(FieldDeclarationSyntax node) { var fieldSymbol = (IFieldSymbol)_model.GetDeclaredSymbol(node.Declaration.Variables[0]); if (fieldSymbol.IsReadOnly || fieldSymbol.IsConst || fieldSymbol.IsExtern) { return; } if (IsSymbolVisibleOutsideSolution(fieldSymbol, _internalsVisibleToAttribute)) { return; } if (IsFieldSerializableByAttributes(fieldSymbol)) { return; } _fields.Add(fieldSymbol); } private static bool IsSymbolVisibleOutsideSolution(ISymbol symbol, ISymbol internalsVisibleToAttribute) { Accessibility accessibility = symbol.DeclaredAccessibility; if (accessibility == Accessibility.NotApplicable) { if (symbol.Kind == SymbolKind.Field) { accessibility = Accessibility.Private; } else { accessibility = Accessibility.Internal; } } if (accessibility == Accessibility.Public || accessibility == Accessibility.Protected) { if (symbol.ContainingType != null) { // a public symbol in a non-visible class isn't visible return IsSymbolVisibleOutsideSolution(symbol.ContainingType, internalsVisibleToAttribute); } // They are public, we are going to skip them. return true; } if (accessibility > Accessibility.Private) { bool visibleOutsideSolution = IsVisibleOutsideSolution( symbol, internalsVisibleToAttribute); if (visibleOutsideSolution) { if (symbol.ContainingType != null) { // a visible symbol in a non-visible class isn't visible return IsSymbolVisibleOutsideSolution( symbol.ContainingType, internalsVisibleToAttribute); } return true; } } return false; } private static bool IsVisibleOutsideSolution( ISymbol field, ISymbol internalsVisibleToAttribute) { IAssemblySymbol assembly = field.ContainingAssembly; return assembly.GetAttributes().Any(a => Equals(a.AttributeClass, internalsVisibleToAttribute)); } private bool IsFieldSerializableByAttributes(IFieldSymbol field) { if (field.GetAttributes() .Any(attr => s_serializingFieldAttributes.Contains(NameHelper.GetFullName(attr.AttributeClass)))) { return true; } return false; } } /// <summary> /// This is the second walker. It checks all code for instances where one of the writable fields (as /// calculated by <see cref="WritableFieldScanner" />) is written to, and removes it from the set. /// Once the scan is complete, the set will not contain any fields written in the specified document. /// </summary> private sealed class WriteUsagesScanner : CSharpSyntaxWalker { private readonly SemanticModel _semanticModel; private readonly ConcurrentDictionary<IFieldSymbol, bool> _writableFields; private WriteUsagesScanner( SemanticModel semanticModel, ConcurrentDictionary<IFieldSymbol, bool> writableFields) { _semanticModel = semanticModel; _writableFields = writableFields; } public override void VisitArgument(ArgumentSyntax node) { base.VisitArgument(node); if (!node.RefOrOutKeyword.IsKind(SyntaxKind.None)) { CheckForFieldWrite(node.Expression); } } public override void VisitAssignmentExpression(AssignmentExpressionSyntax node) { base.VisitAssignmentExpression(node); CheckForFieldWrite(node.Left); } public override void VisitBinaryExpression(BinaryExpressionSyntax node) { base.VisitBinaryExpression(node); switch (node.OperatorToken.Kind()) { case SyntaxKind.AddAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: { CheckForFieldWrite(node.Left); break; } } } public override void VisitIndexerDeclaration(IndexerDeclarationSyntax node) { base.VisitIndexerDeclaration(node); if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.ExternKeyword))) { // This method body is unable to be analysed, so may contain writer instances CheckForRefParametersForExternMethod(node.ParameterList.Parameters); } } public override void VisitInvocationExpression(InvocationExpressionSyntax node) { base.VisitInvocationExpression(node); // A call to myStruct.myField.myMethod() will change if "myField" is marked // readonly, since myMethod might modify it. So those need to be counted as writes if (node.Expression.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { var memberAccess = (MemberAccessExpressionSyntax)node.Expression; ISymbol symbol = _semanticModel.GetSymbolInfo(memberAccess.Expression).Symbol; if (symbol != null && symbol.Kind == SymbolKind.Field) { var fieldSymbol = (IFieldSymbol)symbol; if (fieldSymbol.Type.TypeKind == TypeKind.Struct) { if (!IsImmutablePrimitiveType(fieldSymbol.Type)) { MarkWriteInstance(fieldSymbol); } } } } } public override void VisitMethodDeclaration(MethodDeclarationSyntax node) { base.VisitMethodDeclaration(node); if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.ExternKeyword))) { // This method body is unable to be analysed, so may contain writer instances CheckForRefParametersForExternMethod(node.ParameterList.Parameters); } } private void CheckForRefParametersForExternMethod(IEnumerable<ParameterSyntax> parameters) { foreach (ParameterSyntax parameter in parameters) { ITypeSymbol parameterType = _semanticModel.GetTypeInfo(parameter.Type).Type; if (parameterType == null) { continue; } bool canModify = true; if (parameterType.TypeKind == TypeKind.Struct) { canModify = parameter.Modifiers.Any(m => m.IsKind(SyntaxKind.RefKeyword)); } if (canModify) { // This parameter might be used to modify one of the fields, since the // implmentation is hidden from this analysys. Assume all fields // of the type are written to foreach (IFieldSymbol field in parameterType.GetMembers().OfType<IFieldSymbol>()) { MarkWriteInstance(field); } } } } private void CheckForFieldWrite(ExpressionSyntax node) { var fieldSymbol = _semanticModel.GetSymbolInfo(node).Symbol as IFieldSymbol; if (fieldSymbol != null) { if (IsInsideOwnConstructor(node, fieldSymbol.ContainingType, fieldSymbol.IsStatic)) { return; } MarkWriteInstance(fieldSymbol); } } private bool IsImmutablePrimitiveType(ITypeSymbol type) { // All of the "special type" structs exposed are all immutable, // so it's safe to assume all methods on them are non-mutating, and // therefore safe to call on a readonly field return type.SpecialType != SpecialType.None && type.TypeKind == TypeKind.Struct; } private bool IsInsideOwnConstructor(SyntaxNode node, ITypeSymbol type, bool isStatic) { while (node != null) { switch (node.Kind()) { case SyntaxKind.ConstructorDeclaration: { return _semanticModel.GetDeclaredSymbol(node).IsStatic == isStatic && IsInType(node.Parent, type); } case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: return false; } node = node.Parent; } return false; } private bool IsInType(SyntaxNode node, ITypeSymbol containingType) { while (node != null) { if (node.IsKind(SyntaxKind.ClassDeclaration) || node.IsKind(SyntaxKind.StructDeclaration)) { return Equals(containingType, _semanticModel.GetDeclaredSymbol(node)); } node = node.Parent; } return false; } private void MarkWriteInstance(IFieldSymbol fieldSymbol) { bool ignored; _writableFields.TryRemove(fieldSymbol, out ignored); } public static async Task RemoveWrittenFields( Document document, ConcurrentDictionary<IFieldSymbol, bool> writableFields, CancellationToken cancellationToken) { var scanner = new WriteUsagesScanner( await document.GetSemanticModelAsync(cancellationToken), writableFields); scanner.Visit(await document.GetSyntaxRootAsync(cancellationToken)); } } /// <summary> /// This is the actually rewriter, and should be run third, using the data gathered from the other two /// (<see cref="WritableFieldScanner" /> and <see cref="WriteUsagesScanner" />). /// Any field in the set is both writeable, but not actually written to, which means the "readonly" /// modifier should be applied to it. /// </summary> private sealed class ReadonlyRewriter : CSharpSyntaxRewriter { private readonly SemanticModel _model; private readonly ConcurrentDictionary<IFieldSymbol, bool> _unwrittenFields; public ReadonlyRewriter(ConcurrentDictionary<IFieldSymbol, bool> unwrittenFields, SemanticModel model) { _model = model; _unwrittenFields = unwrittenFields; } public override SyntaxNode VisitFieldDeclaration(FieldDeclarationSyntax node) { var fieldSymbol = (IFieldSymbol)_model.GetDeclaredSymbol(node.Declaration.Variables[0]); bool ignored; if (_unwrittenFields.TryRemove(fieldSymbol, out ignored)) { return node.WithModifiers( node.Modifiers.Add( SyntaxFactory.Token( SyntaxFactory.TriviaList(), SyntaxKind.ReadOnlyKeyword, SyntaxFactory.TriviaList( SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " "))))); } return node; } } } }
// Copyright 2018 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 gaxres = Google.Api.Gax.ResourceNames; using pb = Google.Protobuf; using pbwkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using sys = System; using sc = System.Collections; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.ErrorReporting.V1Beta1 { /// <summary> /// Settings for a <see cref="ReportErrorsServiceClient"/>. /// </summary> public sealed partial class ReportErrorsServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary> /// Get a new instance of the default <see cref="ReportErrorsServiceSettings"/>. /// </summary> /// <returns> /// A new instance of the default <see cref="ReportErrorsServiceSettings"/>. /// </returns> public static ReportErrorsServiceSettings GetDefault() => new ReportErrorsServiceSettings(); /// <summary> /// Constructs a new <see cref="ReportErrorsServiceSettings"/> object with default settings. /// </summary> public ReportErrorsServiceSettings() { } private ReportErrorsServiceSettings(ReportErrorsServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); ReportErrorEventSettings = existing.ReportErrorEventSettings; OnCopy(existing); } partial void OnCopy(ReportErrorsServiceSettings existing); /// <summary> /// The filter specifying which RPC <see cref="grpccore::StatusCode"/>s are eligible for retry /// for "Idempotent" <see cref="ReportErrorsServiceClient"/> RPC methods. /// </summary> /// <remarks> /// The eligible RPC <see cref="grpccore::StatusCode"/>s for retry for "Idempotent" RPC methods are: /// <list type="bullet"> /// <item><description><see cref="grpccore::StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="grpccore::StatusCode.Unavailable"/></description></item> /// </list> /// </remarks> public static sys::Predicate<grpccore::RpcException> IdempotentRetryFilter { get; } = gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.DeadlineExceeded, grpccore::StatusCode.Unavailable); /// <summary> /// The filter specifying which RPC <see cref="grpccore::StatusCode"/>s are eligible for retry /// for "NonIdempotent" <see cref="ReportErrorsServiceClient"/> RPC methods. /// </summary> /// <remarks> /// There are no RPC <see cref="grpccore::StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods. /// </remarks> public static sys::Predicate<grpccore::RpcException> NonIdempotentRetryFilter { get; } = gaxgrpc::RetrySettings.FilterForStatusCodes(); /// <summary> /// "Default" retry backoff for <see cref="ReportErrorsServiceClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" retry backoff for <see cref="ReportErrorsServiceClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" retry backoff for <see cref="ReportErrorsServiceClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial delay: 100 milliseconds</description></item> /// <item><description>Maximum delay: 60000 milliseconds</description></item> /// <item><description>Delay multiplier: 1.3</description></item> /// </list> /// </remarks> public static gaxgrpc::BackoffSettings GetDefaultRetryBackoff() => new gaxgrpc::BackoffSettings( delay: sys::TimeSpan.FromMilliseconds(100), maxDelay: sys::TimeSpan.FromMilliseconds(60000), delayMultiplier: 1.3 ); /// <summary> /// "Default" timeout backoff for <see cref="ReportErrorsServiceClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" timeout backoff for <see cref="ReportErrorsServiceClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" timeout backoff for <see cref="ReportErrorsServiceClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Maximum timeout: 20000 milliseconds</description></item> /// </list> /// </remarks> public static gaxgrpc::BackoffSettings GetDefaultTimeoutBackoff() => new gaxgrpc::BackoffSettings( delay: sys::TimeSpan.FromMilliseconds(20000), maxDelay: sys::TimeSpan.FromMilliseconds(20000), delayMultiplier: 1.0 ); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ReportErrorsServiceClient.ReportErrorEvent</c> and <c>ReportErrorsServiceClient.ReportErrorEventAsync</c>. /// </summary> /// <remarks> /// The default <c>ReportErrorsServiceClient.ReportErrorEvent</c> and /// <c>ReportErrorsServiceClient.ReportErrorEventAsync</c> <see cref="gaxgrpc::RetrySettings"/> are: /// <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: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 20000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description>No status codes</description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public gaxgrpc::CallSettings ReportErrorEventSettings { get; set; } = gaxgrpc::CallSettings.FromCallTiming( gaxgrpc::CallTiming.FromRetry(new gaxgrpc::RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)), retryFilter: NonIdempotentRetryFilter ))); /// <summary> /// Creates a deep clone of this object, with all the same property values. /// </summary> /// <returns>A deep clone of this <see cref="ReportErrorsServiceSettings"/> object.</returns> public ReportErrorsServiceSettings Clone() => new ReportErrorsServiceSettings(this); } /// <summary> /// ReportErrorsService client wrapper, for convenient use. /// </summary> public abstract partial class ReportErrorsServiceClient { /// <summary> /// The default endpoint for the ReportErrorsService service, which is a host of "clouderrorreporting.googleapis.com" and a port of 443. /// </summary> public static gaxgrpc::ServiceEndpoint DefaultEndpoint { get; } = new gaxgrpc::ServiceEndpoint("clouderrorreporting.googleapis.com", 443); /// <summary> /// The default ReportErrorsService scopes. /// </summary> /// <remarks> /// The default ReportErrorsService 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", }); private static readonly gaxgrpc::ChannelPool s_channelPool = new gaxgrpc::ChannelPool(DefaultScopes); /// <summary> /// Asynchronously creates a <see cref="ReportErrorsServiceClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. See the example for how to use custom credentials. /// </summary> /// <example> /// This sample shows how to create a client using default credentials: /// <code> /// using Google.Cloud.ErrorReporting.V1Beta1; /// ... /// // When running on Google Cloud Platform this will use the project Compute Credential. /// // Or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of a JSON /// // credential file to use that credential. /// ReportErrorsServiceClient client = await ReportErrorsServiceClient.CreateAsync(); /// </code> /// This sample shows how to create a client using credentials loaded from a JSON file: /// <code> /// using Google.Cloud.ErrorReporting.V1Beta1; /// using Google.Apis.Auth.OAuth2; /// using Grpc.Auth; /// using Grpc.Core; /// ... /// GoogleCredential cred = GoogleCredential.FromFile("/path/to/credentials.json"); /// Channel channel = new Channel( /// ReportErrorsServiceClient.DefaultEndpoint.Host, ReportErrorsServiceClient.DefaultEndpoint.Port, cred.ToChannelCredentials()); /// ReportErrorsServiceClient client = ReportErrorsServiceClient.Create(channel); /// ... /// // Shutdown the channel when it is no longer required. /// await channel.ShutdownAsync(); /// </code> /// </example> /// <param name="endpoint">Optional <see cref="gaxgrpc::ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="ReportErrorsServiceSettings"/>.</param> /// <returns>The task representing the created <see cref="ReportErrorsServiceClient"/>.</returns> public static async stt::Task<ReportErrorsServiceClient> CreateAsync(gaxgrpc::ServiceEndpoint endpoint = null, ReportErrorsServiceSettings settings = null) { grpccore::Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false); return Create(channel, settings); } /// <summary> /// Synchronously creates a <see cref="ReportErrorsServiceClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. See the example for how to use custom credentials. /// </summary> /// <example> /// This sample shows how to create a client using default credentials: /// <code> /// using Google.Cloud.ErrorReporting.V1Beta1; /// ... /// // When running on Google Cloud Platform this will use the project Compute Credential. /// // Or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of a JSON /// // credential file to use that credential. /// ReportErrorsServiceClient client = ReportErrorsServiceClient.Create(); /// </code> /// This sample shows how to create a client using credentials loaded from a JSON file: /// <code> /// using Google.Cloud.ErrorReporting.V1Beta1; /// using Google.Apis.Auth.OAuth2; /// using Grpc.Auth; /// using Grpc.Core; /// ... /// GoogleCredential cred = GoogleCredential.FromFile("/path/to/credentials.json"); /// Channel channel = new Channel( /// ReportErrorsServiceClient.DefaultEndpoint.Host, ReportErrorsServiceClient.DefaultEndpoint.Port, cred.ToChannelCredentials()); /// ReportErrorsServiceClient client = ReportErrorsServiceClient.Create(channel); /// ... /// // Shutdown the channel when it is no longer required. /// channel.ShutdownAsync().Wait(); /// </code> /// </example> /// <param name="endpoint">Optional <see cref="gaxgrpc::ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="ReportErrorsServiceSettings"/>.</param> /// <returns>The created <see cref="ReportErrorsServiceClient"/>.</returns> public static ReportErrorsServiceClient Create(gaxgrpc::ServiceEndpoint endpoint = null, ReportErrorsServiceSettings settings = null) { grpccore::Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint); return Create(channel, settings); } /// <summary> /// Creates a <see cref="ReportErrorsServiceClient"/> which uses the specified channel for remote operations. /// </summary> /// <param name="channel">The <see cref="grpccore::Channel"/> for remote operations. Must not be null.</param> /// <param name="settings">Optional <see cref="ReportErrorsServiceSettings"/>.</param> /// <returns>The created <see cref="ReportErrorsServiceClient"/>.</returns> public static ReportErrorsServiceClient Create(grpccore::Channel channel, ReportErrorsServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(channel, nameof(channel)); return Create(new grpccore::DefaultCallInvoker(channel), settings); } /// <summary> /// Creates a <see cref="ReportErrorsServiceClient"/> 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="ReportErrorsServiceSettings"/>.</param> /// <returns>The created <see cref="ReportErrorsServiceClient"/>.</returns> public static ReportErrorsServiceClient Create(grpccore::CallInvoker callInvoker, ReportErrorsServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpccore::Interceptors.Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpccore::Interceptors.CallInvokerExtensions.Intercept(callInvoker, interceptor); } ReportErrorsService.ReportErrorsServiceClient grpcClient = new ReportErrorsService.ReportErrorsServiceClient(callInvoker); return new ReportErrorsServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create(gaxgrpc::ServiceEndpoint, ReportErrorsServiceSettings)"/> /// and <see cref="CreateAsync(gaxgrpc::ServiceEndpoint, ReportErrorsServiceSettings)"/>. Channels which weren't automatically /// created are not affected. /// </summary> /// <remarks>After calling this method, further calls to <see cref="Create(gaxgrpc::ServiceEndpoint, ReportErrorsServiceSettings)"/> /// and <see cref="CreateAsync(gaxgrpc::ServiceEndpoint, ReportErrorsServiceSettings)"/> 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() => s_channelPool.ShutdownChannelsAsync(); /// <summary> /// The underlying gRPC ReportErrorsService client. /// </summary> public virtual ReportErrorsService.ReportErrorsServiceClient GrpcClient { get { throw new sys::NotImplementedException(); } } /// <summary> /// Report an individual error event. /// /// This endpoint accepts &lt;strong&gt;either&lt;/strong&gt; an OAuth token, /// &lt;strong&gt;or&lt;/strong&gt; an /// &lt;a href="https://support.google.com/cloud/answer/6158862"&gt;API key&lt;/a&gt; /// for authentication. To use an API key, append it to the URL as the value of /// a `key` parameter. For example: /// &lt;pre&gt;POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456&lt;/pre&gt; /// </summary> /// <param name="projectName"> /// [Required] The resource name of the Google Cloud Platform project. Written /// as `projects/` plus the /// [Google Cloud Platform project ID](https://support.google.com/cloud/answer/6158840). /// Example: `projects/my-project-123`. /// </param> /// <param name="event"> /// [Required] The error event to be reported. /// </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<ReportErrorEventResponse> ReportErrorEventAsync( gaxres::ProjectName projectName, ReportedErrorEvent @event, gaxgrpc::CallSettings callSettings = null) => ReportErrorEventAsync( new ReportErrorEventRequest { ProjectNameAsProjectName = gax::GaxPreconditions.CheckNotNull(projectName, nameof(projectName)), Event = gax::GaxPreconditions.CheckNotNull(@event, nameof(@event)), }, callSettings); /// <summary> /// Report an individual error event. /// /// This endpoint accepts &lt;strong&gt;either&lt;/strong&gt; an OAuth token, /// &lt;strong&gt;or&lt;/strong&gt; an /// &lt;a href="https://support.google.com/cloud/answer/6158862"&gt;API key&lt;/a&gt; /// for authentication. To use an API key, append it to the URL as the value of /// a `key` parameter. For example: /// &lt;pre&gt;POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456&lt;/pre&gt; /// </summary> /// <param name="projectName"> /// [Required] The resource name of the Google Cloud Platform project. Written /// as `projects/` plus the /// [Google Cloud Platform project ID](https://support.google.com/cloud/answer/6158840). /// Example: `projects/my-project-123`. /// </param> /// <param name="event"> /// [Required] The error event to be reported. /// </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<ReportErrorEventResponse> ReportErrorEventAsync( gaxres::ProjectName projectName, ReportedErrorEvent @event, st::CancellationToken cancellationToken) => ReportErrorEventAsync( projectName, @event, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Report an individual error event. /// /// This endpoint accepts &lt;strong&gt;either&lt;/strong&gt; an OAuth token, /// &lt;strong&gt;or&lt;/strong&gt; an /// &lt;a href="https://support.google.com/cloud/answer/6158862"&gt;API key&lt;/a&gt; /// for authentication. To use an API key, append it to the URL as the value of /// a `key` parameter. For example: /// &lt;pre&gt;POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456&lt;/pre&gt; /// </summary> /// <param name="projectName"> /// [Required] The resource name of the Google Cloud Platform project. Written /// as `projects/` plus the /// [Google Cloud Platform project ID](https://support.google.com/cloud/answer/6158840). /// Example: `projects/my-project-123`. /// </param> /// <param name="event"> /// [Required] The error event to be reported. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual ReportErrorEventResponse ReportErrorEvent( gaxres::ProjectName projectName, ReportedErrorEvent @event, gaxgrpc::CallSettings callSettings = null) => ReportErrorEvent( new ReportErrorEventRequest { ProjectNameAsProjectName = gax::GaxPreconditions.CheckNotNull(projectName, nameof(projectName)), Event = gax::GaxPreconditions.CheckNotNull(@event, nameof(@event)), }, callSettings); /// <summary> /// Report an individual error event. /// /// This endpoint accepts &lt;strong&gt;either&lt;/strong&gt; an OAuth token, /// &lt;strong&gt;or&lt;/strong&gt; an /// &lt;a href="https://support.google.com/cloud/answer/6158862"&gt;API key&lt;/a&gt; /// for authentication. To use an API key, append it to the URL as the value of /// a `key` parameter. For example: /// &lt;pre&gt;POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456&lt;/pre&gt; /// </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<ReportErrorEventResponse> ReportErrorEventAsync( ReportErrorEventRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Report an individual error event. /// /// This endpoint accepts &lt;strong&gt;either&lt;/strong&gt; an OAuth token, /// &lt;strong&gt;or&lt;/strong&gt; an /// &lt;a href="https://support.google.com/cloud/answer/6158862"&gt;API key&lt;/a&gt; /// for authentication. To use an API key, append it to the URL as the value of /// a `key` parameter. For example: /// &lt;pre&gt;POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456&lt;/pre&gt; /// </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<ReportErrorEventResponse> ReportErrorEventAsync( ReportErrorEventRequest request, st::CancellationToken cancellationToken) => ReportErrorEventAsync( request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Report an individual error event. /// /// This endpoint accepts &lt;strong&gt;either&lt;/strong&gt; an OAuth token, /// &lt;strong&gt;or&lt;/strong&gt; an /// &lt;a href="https://support.google.com/cloud/answer/6158862"&gt;API key&lt;/a&gt; /// for authentication. To use an API key, append it to the URL as the value of /// a `key` parameter. For example: /// &lt;pre&gt;POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456&lt;/pre&gt; /// </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 ReportErrorEventResponse ReportErrorEvent( ReportErrorEventRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } } /// <summary> /// ReportErrorsService client wrapper implementation, for convenient use. /// </summary> public sealed partial class ReportErrorsServiceClientImpl : ReportErrorsServiceClient { private readonly gaxgrpc::ApiCall<ReportErrorEventRequest, ReportErrorEventResponse> _callReportErrorEvent; /// <summary> /// Constructs a client wrapper for the ReportErrorsService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="ReportErrorsServiceSettings"/> used within this client </param> public ReportErrorsServiceClientImpl(ReportErrorsService.ReportErrorsServiceClient grpcClient, ReportErrorsServiceSettings settings) { GrpcClient = grpcClient; ReportErrorsServiceSettings effectiveSettings = settings ?? ReportErrorsServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callReportErrorEvent = clientHelper.BuildApiCall<ReportErrorEventRequest, ReportErrorEventResponse>( GrpcClient.ReportErrorEventAsync, GrpcClient.ReportErrorEvent, effectiveSettings.ReportErrorEventSettings); Modify_ApiCall(ref _callReportErrorEvent); Modify_ReportErrorEventApiCall(ref _callReportErrorEvent); OnConstruction(grpcClient, effectiveSettings, clientHelper); } // Partial methods are named to (mostly) ensure there cannot be conflicts with RPC method names. // Partial methods called for every ApiCall on construction. // Allows modification of all the underlying ApiCall objects. partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, pb::IMessage<TRequest> where TResponse : class, pb::IMessage<TResponse>; // Partial methods called for each ApiCall on construction. // Allows per-RPC-method modification of the underlying ApiCall object. partial void Modify_ReportErrorEventApiCall(ref gaxgrpc::ApiCall<ReportErrorEventRequest, ReportErrorEventResponse> call); partial void OnConstruction(ReportErrorsService.ReportErrorsServiceClient grpcClient, ReportErrorsServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary> /// The underlying gRPC ReportErrorsService client. /// </summary> public override ReportErrorsService.ReportErrorsServiceClient GrpcClient { get; } // Partial methods called on each request. // Allows per-RPC-call modification to the request and CallSettings objects, // before the underlying RPC is performed. partial void Modify_ReportErrorEventRequest(ref ReportErrorEventRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Report an individual error event. /// /// This endpoint accepts &lt;strong&gt;either&lt;/strong&gt; an OAuth token, /// &lt;strong&gt;or&lt;/strong&gt; an /// &lt;a href="https://support.google.com/cloud/answer/6158862"&gt;API key&lt;/a&gt; /// for authentication. To use an API key, append it to the URL as the value of /// a `key` parameter. For example: /// &lt;pre&gt;POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456&lt;/pre&gt; /// </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<ReportErrorEventResponse> ReportErrorEventAsync( ReportErrorEventRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ReportErrorEventRequest(ref request, ref callSettings); return _callReportErrorEvent.Async(request, callSettings); } /// <summary> /// Report an individual error event. /// /// This endpoint accepts &lt;strong&gt;either&lt;/strong&gt; an OAuth token, /// &lt;strong&gt;or&lt;/strong&gt; an /// &lt;a href="https://support.google.com/cloud/answer/6158862"&gt;API key&lt;/a&gt; /// for authentication. To use an API key, append it to the URL as the value of /// a `key` parameter. For example: /// &lt;pre&gt;POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456&lt;/pre&gt; /// </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 ReportErrorEventResponse ReportErrorEvent( ReportErrorEventRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ReportErrorEventRequest(ref request, ref callSettings); return _callReportErrorEvent.Sync(request, callSettings); } } // Partial classes to enable page-streaming }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace TestCases.SS.UserModel { using System; using NUnit.Framework; using NPOI.SS.UserModel; using NPOI.SS.Util; using System.Collections.Generic; using NPOI.Util; /** * Tests of implementations of {@link NPOI.ss.usermodel.Name}. * * @author Yegor Kozlov */ public abstract class BaseTestNamedRange { private ITestDataProvider _testDataProvider; //public BaseTestNamedRange() // : this(TestCases.HSSF.HSSFITestDataProvider.Instance) //{ } protected BaseTestNamedRange(ITestDataProvider TestDataProvider) { _testDataProvider = TestDataProvider; } [Test] public void TestCreate() { // Create a new workbook IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet1 = wb.CreateSheet("Test1"); ISheet sheet2 = wb.CreateSheet("Testing Named Ranges"); IName name1 = wb.CreateName(); name1.NameName = ("testOne"); //setting a duplicate name should throw ArgumentException IName name2 = wb.CreateName(); try { name2.NameName = ("testOne"); Assert.Fail("expected exception"); } catch (ArgumentException e) { Assert.AreEqual("The workbook already contains this name: testOne", e.Message); } //the check for duplicates is case-insensitive try { name2.NameName = ("TESTone"); Assert.Fail("expected exception"); } catch (ArgumentException e) { Assert.AreEqual("The workbook already contains this name: TESTone", e.Message); } name2.NameName = ("testTwo"); String ref1 = "Test1!$A$1:$B$1"; name1.RefersToFormula = (ref1); Assert.AreEqual(ref1, name1.RefersToFormula); Assert.AreEqual("Test1", name1.SheetName); String ref2 = "'Testing Named Ranges'!$A$1:$B$1"; name1.RefersToFormula = (ref2); Assert.AreEqual("'Testing Named Ranges'!$A$1:$B$1", name1.RefersToFormula); Assert.AreEqual("Testing Named Ranges", name1.SheetName); Assert.AreEqual(-1, name1.SheetIndex); name1.SheetIndex = (-1); Assert.AreEqual(-1, name1.SheetIndex); try { name1.SheetIndex = (2); Assert.Fail("should throw ArgumentException"); } catch (ArgumentException e) { Assert.AreEqual("Sheet index (2) is out of range (0..1)", e.Message); } name1.SheetIndex = (1); Assert.AreEqual(1, name1.SheetIndex); //-1 means the name applies to the entire workbook name1.SheetIndex = (-1); Assert.AreEqual(-1, name1.SheetIndex); //names cannot be blank and must begin with a letter or underscore and not contain spaces String[] invalidNames = { "", "123", "1Name", "Named Range" }; foreach (String name in invalidNames) { try { name1.NameName = (name); Assert.Fail("should have thrown exceptiuon due to invalid name: " + name); } catch (ArgumentException) { // expected during successful Test } } } [Test] public void TestUnicodeNamedRange() { IWorkbook workBook = _testDataProvider.CreateWorkbook(); workBook.CreateSheet("Test"); IName name = workBook.CreateName(); name.NameName = ("\u03B1"); name.RefersToFormula = ("Test!$D$3:$E$8"); IWorkbook workBook2 = _testDataProvider.WriteOutAndReadBack(workBook); IName name2 = workBook2.GetNameAt(0); Assert.AreEqual("\u03B1", name2.NameName); Assert.AreEqual("Test!$D$3:$E$8", name2.RefersToFormula); } [Test] public void TestAddRemove() { IWorkbook wb = _testDataProvider.CreateWorkbook(); Assert.AreEqual(0, wb.NumberOfNames); IName name1 = wb.CreateName(); name1.NameName = ("name1"); Assert.AreEqual(1, wb.NumberOfNames); IName name2 = wb.CreateName(); name2.NameName = ("name2"); Assert.AreEqual(2, wb.NumberOfNames); IName name3 = wb.CreateName(); name3.NameName = ("name3"); Assert.AreEqual(3, wb.NumberOfNames); wb.RemoveName("name2"); Assert.AreEqual(2, wb.NumberOfNames); wb.RemoveName(0); Assert.AreEqual(1, wb.NumberOfNames); } [Test] public void TestScope() { IWorkbook wb = _testDataProvider.CreateWorkbook(); wb.CreateSheet(); wb.CreateSheet(); IName name; name = wb.CreateName(); name.NameName = ("aaa"); name = wb.CreateName(); try { name.NameName = ("aaa"); Assert.Fail("Expected exception"); } catch (Exception e) { Assert.AreEqual("The workbook already contains this name: aaa", e.Message); } name = wb.CreateName(); name.SheetIndex = (0); name.NameName = ("aaa"); name = wb.CreateName(); name.SheetIndex = (0); try { name.NameName = ("aaa"); Assert.Fail("Expected exception"); } catch (Exception e) { Assert.AreEqual("The sheet already contains this name: aaa", e.Message); } name = wb.CreateName(); name.SheetIndex = (1); name.NameName = ("aaa"); name = wb.CreateName(); name.SheetIndex = (1); try { name.NameName = ("aaa"); Assert.Fail("Expected exception"); } catch (Exception e) { Assert.AreEqual("The sheet already contains this name: aaa", e.Message); } Assert.AreEqual(3, wb.GetNames("aaa").Count); } /** * Test case provided by czhang@cambian.com (Chun Zhang) * <p> * Addresses Bug <a href="http://issues.apache.org/bugzilla/Show_bug.cgi?id=13775" target="_bug">#13775</a> */ [Test] public void TestMultiNamedRange() { // Create a new workbook IWorkbook wb = _testDataProvider.CreateWorkbook(); // Create a worksheet 'sheet1' in the new workbook wb.CreateSheet(); wb.SetSheetName(0, "sheet1"); // Create another worksheet 'sheet2' in the new workbook wb.CreateSheet(); wb.SetSheetName(1, "sheet2"); // Create a new named range for worksheet 'sheet1' IName namedRange1 = wb.CreateName(); // Set the name for the named range for worksheet 'sheet1' namedRange1.NameName = ("RangeTest1"); // Set the reference for the named range for worksheet 'sheet1' namedRange1.RefersToFormula = ("sheet1" + "!$A$1:$L$41"); // Create a new named range for worksheet 'sheet2' IName namedRange2 = wb.CreateName(); // Set the name for the named range for worksheet 'sheet2' namedRange2.NameName = ("RangeTest2"); // Set the reference for the named range for worksheet 'sheet2' namedRange2.RefersToFormula = ("sheet2" + "!$A$1:$O$21"); // Write the workbook to a file // Read the Excel file and verify its content wb = _testDataProvider.WriteOutAndReadBack(wb); IName nm1 = wb.GetName("RangeTest1"); Assert.IsTrue("RangeTest1".Equals(nm1.NameName), "Name is " + nm1.NameName); Assert.IsTrue((wb.GetSheetName(0) + "!$A$1:$L$41").Equals(nm1.RefersToFormula), "Reference is " + nm1.RefersToFormula); IName nm2 = wb.GetName("RangeTest2"); Assert.IsTrue("RangeTest2".Equals(nm2.NameName), "Name is " + nm2.NameName); Assert.IsTrue((wb.GetSheetName(1) + "!$A$1:$O$21").Equals(nm2.RefersToFormula), "Reference is " + nm2.RefersToFormula); } /** * Test to see if the print areas can be retrieved/Created in memory */ [Test] public void TestSinglePrintArea() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); workbook.CreateSheet("Test Print Area"); String sheetName = workbook.GetSheetName(0); String reference = "$A$1:$B$1"; workbook.SetPrintArea(0, reference); String retrievedPrintArea = workbook.GetPrintArea(0); Assert.IsNotNull(retrievedPrintArea, "Print Area not defined for first sheet"); Assert.AreEqual("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea); } /** * For Convenience, don't force sheet names to be used */ [Test] public void TestSinglePrintAreaWOSheet() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); workbook.CreateSheet("Test Print Area"); String sheetName = workbook.GetSheetName(0); String reference = "$A$1:$B$1"; workbook.SetPrintArea(0, reference); String retrievedPrintArea = workbook.GetPrintArea(0); Assert.IsNotNull(retrievedPrintArea, "Print Area not defined for first sheet"); Assert.AreEqual("'" + sheetName + "'!" + reference, retrievedPrintArea); } /** * Test to see if the print area made it to the file */ [Test] public void TestPrintAreaFile() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); workbook.CreateSheet("Test Print Area"); String sheetName = workbook.GetSheetName(0); String reference = "$A$1:$B$1"; workbook.SetPrintArea(0, reference); workbook = _testDataProvider.WriteOutAndReadBack(workbook); String retrievedPrintArea = workbook.GetPrintArea(0); Assert.IsNotNull(retrievedPrintArea, "Print Area not defined for first sheet"); Assert.AreEqual("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea, "References Match"); } /** * Test to see if multiple print areas made it to the file */ [Test] public void TestMultiplePrintAreaFile() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); workbook.CreateSheet("Sheet1"); workbook.CreateSheet("Sheet2"); workbook.CreateSheet("Sheet3"); String reference1 = "$A$1:$B$1"; String reference2 = "$B$2:$D$5"; String reference3 = "$D$2:$F$5"; workbook.SetPrintArea(0, reference1); workbook.SetPrintArea(1, reference2); workbook.SetPrintArea(2, reference3); //Check Created print areas String retrievedPrintArea; retrievedPrintArea = workbook.GetPrintArea(0); Assert.IsNotNull(retrievedPrintArea, "Print Area Not Found (Sheet 1)"); Assert.AreEqual("Sheet1!" + reference1, retrievedPrintArea); retrievedPrintArea = workbook.GetPrintArea(1); Assert.IsNotNull(retrievedPrintArea, "Print Area Not Found (Sheet 2)"); Assert.AreEqual("Sheet2!" + reference2, retrievedPrintArea); retrievedPrintArea = workbook.GetPrintArea(2); Assert.IsNotNull(retrievedPrintArea, "Print Area Not Found (Sheet 3)"); Assert.AreEqual("Sheet3!" + reference3, retrievedPrintArea); // Check print areas After re-reading workbook workbook = _testDataProvider.WriteOutAndReadBack(workbook); retrievedPrintArea = workbook.GetPrintArea(0); Assert.IsNotNull(retrievedPrintArea, "Print Area Not Found (Sheet 1)"); Assert.AreEqual("Sheet1!" + reference1, retrievedPrintArea); retrievedPrintArea = workbook.GetPrintArea(1); Assert.IsNotNull(retrievedPrintArea, "Print Area Not Found (Sheet 2)"); Assert.AreEqual("Sheet2!" + reference2, retrievedPrintArea); retrievedPrintArea = workbook.GetPrintArea(2); Assert.IsNotNull(retrievedPrintArea, "Print Area Not Found (Sheet 3)"); Assert.AreEqual("Sheet3!" + reference3, retrievedPrintArea); } /** * Tests the Setting of print areas with coordinates (Row/Column designations) * */ [Test] public void TestPrintAreaCoords() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); workbook.CreateSheet("Test Print Area"); String sheetName = workbook.GetSheetName(0); workbook.SetPrintArea(0, 0, 1, 0, 0); String retrievedPrintArea = workbook.GetPrintArea(0); Assert.IsNotNull(retrievedPrintArea, "Print Area not defined for first sheet"); Assert.AreEqual("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea); } /** * Tests the parsing of union area expressions, and re-display in the presence of sheet names * with special characters. */ [Test] public void TestPrintAreaUnion() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); workbook.CreateSheet("Test Print Area"); String reference = "$A$1:$B$1,$D$1:$F$2"; workbook.SetPrintArea(0, reference); String retrievedPrintArea = workbook.GetPrintArea(0); Assert.IsNotNull(retrievedPrintArea, "Print Area not defined for first sheet"); Assert.AreEqual("'Test Print Area'!$A$1:$B$1,'Test Print Area'!$D$1:$F$2", retrievedPrintArea); } /** * Verifies an existing print area is deleted * */ [Test] public void TestPrintAreaRemove() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); workbook.CreateSheet("Test Print Area"); workbook.GetSheetName(0); workbook.SetPrintArea(0, 0, 1, 0, 0); String retrievedPrintArea = workbook.GetPrintArea(0); Assert.IsNotNull(retrievedPrintArea, "Print Area not defined for first sheet"); workbook.RemovePrintArea(0); Assert.IsNull(workbook.GetPrintArea(0), "PrintArea was not Removed"); } /** * Test that multiple named ranges can be Added written and read */ [Test] public void TestMultipleNamedWrite() { IWorkbook wb = _testDataProvider.CreateWorkbook(); wb.CreateSheet("testSheet1"); String sheetName = wb.GetSheetName(0); Assert.AreEqual("testSheet1", sheetName); //Creating new Named Range IName newNamedRange = wb.CreateName(); newNamedRange.NameName = ("RangeTest"); newNamedRange.RefersToFormula = (sheetName + "!$D$4:$E$8"); //Creating another new Named Range IName newNamedRange2 = wb.CreateName(); newNamedRange2.NameName = ("AnotherTest"); newNamedRange2.RefersToFormula = (sheetName + "!$F$1:$G$6"); wb.GetNameAt(0); wb = _testDataProvider.WriteOutAndReadBack(wb); IName nm = wb.GetName("RangeTest"); Assert.IsTrue("RangeTest".Equals(nm.NameName), "Name is " + nm.NameName); Assert.IsTrue((wb.GetSheetName(0) + "!$D$4:$E$8").Equals(nm.RefersToFormula), "Reference is " + nm.RefersToFormula); nm = wb.GetName("AnotherTest"); Assert.IsTrue("AnotherTest".Equals(nm.NameName), "Name is " + nm.NameName); Assert.IsTrue(newNamedRange2.RefersToFormula.Equals(nm.RefersToFormula), "Reference is " + nm.RefersToFormula); } /** * Verifies correct functioning for "single cell named range" (aka "named cell") */ [Test] public void TestNamedCell_1() { // Setup for this Testcase String sheetName = "Test Named Cell"; String cellName = "named_cell"; String cellValue = "TEST Value"; IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(sheetName); ICreationHelper factory = wb.GetCreationHelper(); sheet.CreateRow(0).CreateCell(0).SetCellValue(factory.CreateRichTextString(cellValue)); // create named range for a single cell using areareference IName namedCell = wb.CreateName(); namedCell.NameName = (cellName); String reference = "'" + sheetName + "'" + "!A1:A1"; namedCell.RefersToFormula = (reference); // retrieve the newly Created named range IName aNamedCell = wb.GetName(cellName); Assert.IsNotNull(aNamedCell); // retrieve the cell at the named range and Test its contents AreaReference aref = new AreaReference(aNamedCell.RefersToFormula); Assert.IsTrue(aref.IsSingleCell, "Should be exactly 1 cell in the named cell :'" + cellName + "'"); CellReference cref = aref.FirstCell; Assert.IsNotNull(cref); ISheet s = wb.GetSheet(cref.SheetName); Assert.IsNotNull(s); IRow r = sheet.GetRow(cref.Row); ICell c = r.GetCell(cref.Col); String contents = c.RichStringCellValue.String; Assert.AreEqual(contents, cellValue, "Contents of cell retrieved by its named reference"); } /** * Verifies correct functioning for "single cell named range" (aka "named cell") */ [Test] public void TestNamedCell_2() { // Setup for this Testcase String sname = "TestSheet", cname = "TestName", cvalue = "TestVal"; IWorkbook wb = _testDataProvider.CreateWorkbook(); ICreationHelper factory = wb.GetCreationHelper(); ISheet sheet = wb.CreateSheet(sname); sheet.CreateRow(0).CreateCell(0).SetCellValue(factory.CreateRichTextString(cvalue)); // create named range for a single cell using cellreference IName namedCell = wb.CreateName(); namedCell.NameName = (cname); String reference = sname + "!A1"; namedCell.RefersToFormula = (reference); // retrieve the newly Created named range IName aNamedCell = wb.GetName(cname); Assert.IsNotNull(aNamedCell); // retrieve the cell at the named range and Test its contents CellReference cref = new CellReference(aNamedCell.RefersToFormula); Assert.IsNotNull(cref); ISheet s = wb.GetSheet(cref.SheetName); IRow r = sheet.GetRow(cref.Row); ICell c = r.GetCell(cref.Col); String contents = c.RichStringCellValue.String; Assert.AreEqual(contents, cvalue, "Contents of cell retrieved by its named reference"); } /** * Bugzilla attachment 23444 (from bug 46973) has a NAME record with the following encoding: * <pre> * 00000000 | 18 00 17 00 00 00 00 08 00 00 00 00 00 00 00 00 | ................ * 00000010 | 00 00 00 55 50 53 53 74 61 74 65 | ...UPSState * </pre> * * This caused trouble for anything that requires {@link Name#getRefersToFormula()} * It is easy enough to re-create the the same data (by not Setting the formula). Excel * seems to gracefully remove this unInitialized name record. It would be nice if POI * could do the same, but that would involve adjusting subsequent name indexes across * all formulas. <p/> * * For the moment, POI has been made to behave more sensibly with unInitialised name * records. */ [Test] public void TestUnInitialisedNameGetRefersToFormula_bug46973() { IWorkbook wb = _testDataProvider.CreateWorkbook(); IName n = wb.CreateName(); n.NameName = ("UPSState"); String formula; try { formula = n.RefersToFormula; } catch (ArgumentException e) { if (e.Message.Equals("ptgs must not be null")) { throw new AssertionException("Identified bug 46973"); } throw e; } Assert.IsNull(formula); Assert.IsFalse(n.IsDeleted); // according to exact defInition of isDeleted() } [Test] public void TestDeletedCell() { IWorkbook wb = _testDataProvider.CreateWorkbook(); IName n = wb.CreateName(); n.NameName = ("MyName"); // contrived example to expose bug: n.RefersToFormula = ("if(A1,\"#REF!\", \"\")"); if (n.IsDeleted) { throw new AssertionException("Identified bug in recoginising formulas referring to deleted cells"); } } [Test] public void TestFunctionNames() { IWorkbook wb = _testDataProvider.CreateWorkbook(); IName n = wb.CreateName(); Assert.IsFalse(n.IsFunctionName); n.SetFunction(false); Assert.IsFalse(n.IsFunctionName); n.SetFunction(true); Assert.IsTrue(n.IsFunctionName); n.SetFunction(false); Assert.IsFalse(n.IsFunctionName); } [Test] public void TestDefferedSetting() { IWorkbook wb = _testDataProvider.CreateWorkbook(); IName n1 = wb.CreateName(); Assert.IsNull(n1.RefersToFormula); Assert.AreEqual("", n1.NameName); IName n2 = wb.CreateName(); Assert.IsNull(n2.RefersToFormula); Assert.AreEqual("", n2.NameName); n1.NameName = ("sale_1"); n1.RefersToFormula = ("10"); n2.NameName = ("sale_2"); n2.RefersToFormula = ("20"); try { n2.NameName = ("sale_1"); Assert.Fail("Expected exception"); } catch (Exception e) { Assert.AreEqual("The workbook already contains this name: sale_1", e.Message); } } [Test] public void TestBug56930() { IWorkbook wb = _testDataProvider.CreateWorkbook(); // x1 on sheet1 defines "x=1" wb.CreateSheet("sheet1"); IName x1 = wb.CreateName(); x1.NameName = "x"; x1.RefersToFormula = "1"; x1.SheetIndex = wb.GetSheetIndex("sheet1"); // x2 on sheet2 defines "x=2" wb.CreateSheet("sheet2"); IName x2 = wb.CreateName(); x2.NameName = "x"; x2.RefersToFormula = "2"; x2.SheetIndex = wb.GetSheetIndex("sheet2"); IList<IName> names = wb.GetNames("x"); Assert.AreEqual(2, names.Count, "Had: " + names); Assert.AreEqual("1", names[0].RefersToFormula); Assert.AreEqual("2", names[1].RefersToFormula); Assert.AreEqual("1", wb.GetName("x").RefersToFormula); wb.RemoveName("x"); Assert.AreEqual("2", wb.GetName("x").RefersToFormula); wb.Close(); } [Test] public void Test56781() { IWorkbook wb = _testDataProvider.CreateWorkbook(); IName name = wb.CreateName(); foreach (String valid in Arrays.AsList( "Hello", "number1", "_underscore" //"p.e.r.o.i.d.s", //"\\Backslash", //"Backslash\\" )) { name.NameName = valid; } try { name.NameName = ""; Assert.Fail("expected exception: (blank)"); } catch (ArgumentException e) { Assert.AreEqual("Name cannot be blank", e.Message); } foreach (String invalid in Arrays.AsList( "1number", "Sheet1!A1", "Exclamation!", "Has Space", "Colon:", "A-Minus", "A+Plus", "Dollar$")) { try { name.NameName = invalid; Assert.Fail("expected exception: " + invalid); } catch (ArgumentException e) { Assert.IsTrue(e.Message.StartsWith("Invalid name: '" + invalid + "'"), invalid); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime; using Internal.Runtime.Augments; namespace Internal.Runtime.CompilerServices { // This structure is used to resolve a instance method given an object instance. To use this type // 1) New up an instance using one of the constructors below. // 2) Use the ToIntPtr() method to get the interned instance of this type. This will permanently allocate // a block of memory that can be used to represent a virtual method resolution. This memory is interned // so that repeated allocation of the same resolver will not leak. // 3) Use the ResolveMethod function to do the virtual lookup. This function takes advantage of // a lockless cache so the resolution is very fast for repeated lookups. public struct OpenMethodResolver : IEquatable<OpenMethodResolver> { public const short DispatchResolve = 0; public const short GVMResolve = 1; public const short OpenNonVirtualResolve = 2; public const short OpenNonVirtualResolveLookthruUnboxing = 3; private readonly short _resolveType; private readonly GCHandle _readerGCHandle; private readonly int _handle; private readonly IntPtr _methodHandleOrSlotOrCodePointer; private readonly IntPtr _nonVirtualOpenInvokeCodePointer; private readonly EETypePtr _declaringType; public OpenMethodResolver(RuntimeTypeHandle declaringTypeOfSlot, int slot, GCHandle readerGCHandle, int handle) { _resolveType = DispatchResolve; _declaringType = declaringTypeOfSlot.ToEETypePtr(); _methodHandleOrSlotOrCodePointer = new IntPtr(slot); _handle = handle; _readerGCHandle = readerGCHandle; _nonVirtualOpenInvokeCodePointer = IntPtr.Zero; } public unsafe OpenMethodResolver(RuntimeTypeHandle declaringTypeOfSlot, RuntimeMethodHandle gvmSlot, GCHandle readerGCHandle, int handle) { _resolveType = GVMResolve; _methodHandleOrSlotOrCodePointer = *(IntPtr*)&gvmSlot; _declaringType = declaringTypeOfSlot.ToEETypePtr(); _handle = handle; _readerGCHandle = readerGCHandle; _nonVirtualOpenInvokeCodePointer = IntPtr.Zero; } public OpenMethodResolver(RuntimeTypeHandle declaringType, IntPtr codePointer, GCHandle readerGCHandle, int handle) { _resolveType = OpenNonVirtualResolve; _nonVirtualOpenInvokeCodePointer = _methodHandleOrSlotOrCodePointer = codePointer; _declaringType = declaringType.ToEETypePtr(); _handle = handle; _readerGCHandle = readerGCHandle; } public OpenMethodResolver(RuntimeTypeHandle declaringType, IntPtr codePointer, GCHandle readerGCHandle, int handle, short resolveType) { _resolveType = resolveType; _methodHandleOrSlotOrCodePointer = codePointer; _declaringType = declaringType.ToEETypePtr(); _handle = handle; _readerGCHandle = readerGCHandle; if (resolveType == OpenNonVirtualResolve) _nonVirtualOpenInvokeCodePointer = codePointer; else if (resolveType == OpenNonVirtualResolveLookthruUnboxing) _nonVirtualOpenInvokeCodePointer = RuntimeAugments.TypeLoaderCallbacks.ConvertUnboxingFunctionPointerToUnderlyingNonUnboxingPointer(codePointer, declaringType); else throw new NotSupportedException(); } public short ResolverType { get { return _resolveType; } } public RuntimeTypeHandle DeclaringType { get { return new RuntimeTypeHandle(_declaringType); } } public unsafe RuntimeMethodHandle GVMMethodHandle { get { IntPtr localIntPtr = _methodHandleOrSlotOrCodePointer; IntPtr* pMethodHandle = &localIntPtr; return *(RuntimeMethodHandle*)pMethodHandle; } } public bool IsOpenNonVirtualResolve { get { switch(_resolveType) { case OpenNonVirtualResolve: case OpenNonVirtualResolveLookthruUnboxing: return true; default: return false; } } } public IntPtr CodePointer { get { return _methodHandleOrSlotOrCodePointer; } } public object Reader { get { return _readerGCHandle.Target; } } public int Handle { get { return _handle; } } unsafe private IntPtr ResolveMethod(object thisObject) { if (_resolveType == DispatchResolve) { return RuntimeImports.RhResolveDispatch(thisObject, _declaringType, (ushort)_methodHandleOrSlotOrCodePointer.ToInt32()); } else if (_resolveType == GVMResolve) { return TypeLoaderExports.GVMLookupForSlot(thisObject, GVMMethodHandle); } else { throw new NotSupportedException(); // Should never happen, in this case, the dispatch should be resolved in the other ResolveMethod function } } unsafe internal static IntPtr ResolveMethodWorker(IntPtr resolver, object thisObject) { return ((OpenMethodResolver*)resolver)->ResolveMethod(thisObject); } unsafe public static IntPtr ResolveMethod(IntPtr resolver, object thisObject) { IntPtr nonVirtualOpenInvokeCodePointer = ((OpenMethodResolver*)resolver)->_nonVirtualOpenInvokeCodePointer; if (nonVirtualOpenInvokeCodePointer != IntPtr.Zero) return nonVirtualOpenInvokeCodePointer; return TypeLoaderExports.OpenInstanceMethodLookup(resolver, thisObject); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int _rotl(int value, int shift) { return (int)(((uint)value << shift) | ((uint)value >> (32 - shift))); } private static int CalcHashCode(int hashCode1, int hashCode2, int hashCode3, int hashCode4) { int length = 4; int hash1 = 0x449b3ad6; int hash2 = (length << 3) + 0x55399219; hash1 = (hash1 + _rotl(hash1, 5)) ^ hashCode1; hash2 = (hash2 + _rotl(hash2, 5)) ^ hashCode2; hash1 = (hash1 + _rotl(hash1, 5)) ^ hashCode3; hash2 = (hash2 + _rotl(hash2, 5)) ^ hashCode4; hash1 += _rotl(hash1, 8); hash2 += _rotl(hash2, 8); return hash1 ^ hash2; } public override int GetHashCode() { return CalcHashCode(_resolveType, _handle, _methodHandleOrSlotOrCodePointer.GetHashCode(), _declaringType.GetHashCode()); } public bool Equals(OpenMethodResolver other) { if (other._resolveType != _resolveType) return false; if (other._handle != _handle) return false; if (other._methodHandleOrSlotOrCodePointer != _methodHandleOrSlotOrCodePointer) return false; return other._declaringType.Equals(_declaringType); } public override bool Equals(object obj) { if (!(obj is OpenMethodResolver)) { return false; } return ((OpenMethodResolver)obj).Equals(this); } private static LowLevelDictionary<OpenMethodResolver, IntPtr> s_internedResolverHash = new LowLevelDictionary<OpenMethodResolver, IntPtr>(); unsafe public IntPtr ToIntPtr() { lock (s_internedResolverHash) { IntPtr returnValue; if (s_internedResolverHash.TryGetValue(this, out returnValue)) return returnValue; returnValue = Interop.MemAlloc(new UIntPtr((uint)sizeof(OpenMethodResolver))); *((OpenMethodResolver*)returnValue) = this; s_internedResolverHash.Add(this, returnValue); return returnValue; } } } }
/* * Exchange Web Services Managed API * * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ namespace Microsoft.Exchange.WebServices.Data { using System; /// <summary> /// Represents the Id of an Exchange object. /// </summary> public abstract class ServiceId : ComplexProperty { private string changeKey; private string uniqueId; /// <summary> /// Initializes a new instance of the <see cref="ServiceId"/> class. /// </summary> internal ServiceId() : base() { } /// <summary> /// Initializes a new instance of the <see cref="ServiceId"/> class. /// </summary> /// <param name="uniqueId">The unique id.</param> internal ServiceId(string uniqueId) : this() { EwsUtilities.ValidateParam(uniqueId, "uniqueId"); this.uniqueId = uniqueId; } /// <summary> /// Reads attributes from XML. /// </summary> /// <param name="reader">The reader.</param> internal override void ReadAttributesFromXml(EwsServiceXmlReader reader) { this.uniqueId = reader.ReadAttributeValue(XmlAttributeNames.Id); this.changeKey = reader.ReadAttributeValue(XmlAttributeNames.ChangeKey); } /// <summary> /// Writes attributes to XML. /// </summary> /// <param name="writer">The writer.</param> internal override void WriteAttributesToXml(EwsServiceXmlWriter writer) { writer.WriteAttributeValue(XmlAttributeNames.Id, this.UniqueId); writer.WriteAttributeValue(XmlAttributeNames.ChangeKey, this.ChangeKey); } /// <summary> /// Gets the name of the XML element. /// </summary> /// <returns>XML element name.</returns> internal abstract string GetXmlElementName(); /// <summary> /// Writes to XML. /// </summary> /// <param name="writer">The writer.</param> internal void WriteToXml(EwsServiceXmlWriter writer) { this.WriteToXml(writer, this.GetXmlElementName()); } /// <summary> /// Assigns from existing id. /// </summary> /// <param name="source">The source.</param> internal void Assign(ServiceId source) { this.uniqueId = source.UniqueId; this.changeKey = source.ChangeKey; } /// <summary> /// True if this instance is valid, false otherthise. /// </summary> /// <value><c>true</c> if this instance is valid; otherwise, <c>false</c>.</value> internal virtual bool IsValid { get { return !string.IsNullOrEmpty(this.uniqueId); } } /// <summary> /// Gets the unique Id of the Exchange object. /// </summary> public string UniqueId { get { return this.uniqueId; } internal set { this.uniqueId = value; } } /// <summary> /// Gets the change key associated with the Exchange object. The change key represents the /// the version of the associated item or folder. /// </summary> public string ChangeKey { get { return this.changeKey; } internal set { this.changeKey = value; } } /// <summary> /// Determines whether two ServiceId instances are equal (including ChangeKeys) /// </summary> /// <param name="other">The ServiceId to compare with the current ServiceId.</param> public bool SameIdAndChangeKey(ServiceId other) { if (this.Equals(other)) { return ((this.ChangeKey == null) && (other.ChangeKey == null)) || this.ChangeKey.Equals(other.ChangeKey); } else { return false; } } #region Object method overrides /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param> /// <remarks> /// We do not consider the ChangeKey for ServiceId.Equals.</remarks> /// <returns> /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false. /// </returns> /// <exception cref="T:System.NullReferenceException">The <paramref name="obj"/> parameter is null.</exception> public override bool Equals(object obj) { if (object.ReferenceEquals(this, obj)) { return true; } else { ServiceId other = obj as ServiceId; if (other == null) { return false; } else if (!(this.IsValid && other.IsValid)) { return false; } else { return this.UniqueId.Equals(other.UniqueId); } } } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <remarks> /// We do not consider the change key in the hash code computation. /// </remarks> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { return this.IsValid ? this.UniqueId.GetHashCode() : base.GetHashCode(); } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override string ToString() { return (this.uniqueId == null) ? string.Empty : this.uniqueId; } #endregion } }
namespace Azure.Communication.CallingServer { public partial class AddParticipantResult { internal AddParticipantResult() { } public string ParticipantId { get { throw null; } } } public partial class AddParticipantResultEvent : Azure.Communication.CallingServer.CallingServerEventBase { internal AddParticipantResultEvent() { } public string OperationContext { get { throw null; } } public Azure.Communication.CallingServer.ResultInfo ResultInfo { get { throw null; } } public Azure.Communication.CallingServer.OperationStatus Status { get { throw null; } } public static Azure.Communication.CallingServer.AddParticipantResultEvent Deserialize(string content) { throw null; } } public partial class CallConnection { protected CallConnection() { } public virtual string CallConnectionId { get { throw null; } } public virtual Azure.Response<Azure.Communication.CallingServer.AddParticipantResult> AddParticipant(Azure.Communication.CommunicationIdentifier participant, string alternateCallerId = null, string operationContext = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Communication.CallingServer.AddParticipantResult>> AddParticipantAsync(Azure.Communication.CommunicationIdentifier participant, string alternateCallerId = null, string operationContext = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Communication.CallingServer.CancelAllMediaOperationsResult> CancelAllMediaOperations(string operationContext = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Communication.CallingServer.CancelAllMediaOperationsResult>> CancelAllMediaOperationsAsync(string operationContext = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response Hangup(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> HangupAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Communication.CallingServer.PlayAudioResult> PlayAudio(Azure.Communication.CallingServer.PlayAudioOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Communication.CallingServer.PlayAudioResult> PlayAudio(System.Uri audioFileUri, bool? loop, string audioFileId, System.Uri callbackUri, string operationContext = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Communication.CallingServer.PlayAudioResult>> PlayAudioAsync(Azure.Communication.CallingServer.PlayAudioOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Communication.CallingServer.PlayAudioResult>> PlayAudioAsync(System.Uri audioFileUri, bool? loop, string audioFileId, System.Uri callbackUri, string operationContext = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response RemoveParticipant(string participantId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> RemoveParticipantAsync(string participantId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct CallConnectionState : System.IEquatable<Azure.Communication.CallingServer.CallConnectionState> { private readonly object _dummy; private readonly int _dummyPrimitive; public CallConnectionState(string value) { throw null; } public static Azure.Communication.CallingServer.CallConnectionState Connected { get { throw null; } } public static Azure.Communication.CallingServer.CallConnectionState Connecting { get { throw null; } } public static Azure.Communication.CallingServer.CallConnectionState Disconnected { get { throw null; } } public static Azure.Communication.CallingServer.CallConnectionState Disconnecting { get { throw null; } } public static Azure.Communication.CallingServer.CallConnectionState Incoming { get { throw null; } } public bool Equals(Azure.Communication.CallingServer.CallConnectionState other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Communication.CallingServer.CallConnectionState left, Azure.Communication.CallingServer.CallConnectionState right) { throw null; } public static implicit operator Azure.Communication.CallingServer.CallConnectionState (string value) { throw null; } public static bool operator !=(Azure.Communication.CallingServer.CallConnectionState left, Azure.Communication.CallingServer.CallConnectionState right) { throw null; } public override string ToString() { throw null; } } public partial class CallConnectionStateChangedEvent : Azure.Communication.CallingServer.CallingServerEventBase { internal CallConnectionStateChangedEvent() { } public string CallConnectionId { get { throw null; } } public Azure.Communication.CallingServer.CallConnectionState CallConnectionState { get { throw null; } } public string ServerCallId { get { throw null; } } public static Azure.Communication.CallingServer.CallConnectionStateChangedEvent Deserialize(string content) { throw null; } } public partial class CallingServerClient { protected CallingServerClient() { } public CallingServerClient(string connectionString) { } public CallingServerClient(string connectionString, Azure.Communication.CallingServer.CallingServerClientOptions options) { } public CallingServerClient(System.Uri endpoint, Azure.Core.TokenCredential credential) { } public CallingServerClient(System.Uri endpoint, Azure.Core.TokenCredential credential, Azure.Communication.CallingServer.CallingServerClientOptions options) { } public virtual Azure.Response<Azure.Communication.CallingServer.CallConnection> CreateCallConnection(Azure.Communication.CommunicationIdentifier source, System.Collections.Generic.IEnumerable<Azure.Communication.CommunicationIdentifier> targets, Azure.Communication.CallingServer.CreateCallOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Communication.CallingServer.CallConnection>> CreateCallConnectionAsync(Azure.Communication.CommunicationIdentifier source, System.Collections.Generic.IEnumerable<Azure.Communication.CommunicationIdentifier> targets, Azure.Communication.CallingServer.CreateCallOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<System.IO.Stream> DownloadStreaming(System.Uri sourceEndpoint, Azure.HttpRange range = default(Azure.HttpRange), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<System.IO.Stream>> DownloadStreamingAsync(System.Uri sourceEndpoint, Azure.HttpRange range = default(Azure.HttpRange), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response DownloadTo(System.Uri sourceEndpoint, System.IO.Stream destinationStream, Azure.Communication.CallingServer.ContentTransferOptions transferOptions = default(Azure.Communication.CallingServer.ContentTransferOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response DownloadTo(System.Uri sourceEndpoint, string destinationPath, Azure.Communication.CallingServer.ContentTransferOptions transferOptions = default(Azure.Communication.CallingServer.ContentTransferOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> DownloadToAsync(System.Uri sourceEndpoint, System.IO.Stream destinationStream, Azure.Communication.CallingServer.ContentTransferOptions transferOptions = default(Azure.Communication.CallingServer.ContentTransferOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> DownloadToAsync(System.Uri sourceEndpoint, string destinationPath, Azure.Communication.CallingServer.ContentTransferOptions transferOptions = default(Azure.Communication.CallingServer.ContentTransferOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Communication.CallingServer.CallConnection GetCallConnection(string callConnectionId) { throw null; } public virtual Azure.Communication.CallingServer.ServerCall InitializeServerCall(string serverCallId) { throw null; } public virtual Azure.Response<Azure.Communication.CallingServer.CallConnection> JoinCall(string serverCallId, Azure.Communication.CommunicationIdentifier source, Azure.Communication.CallingServer.JoinCallOptions callOptions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Communication.CallingServer.CallConnection>> JoinCallAsync(string serverCallId, Azure.Communication.CommunicationIdentifier source, Azure.Communication.CallingServer.JoinCallOptions callOptions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class CallingServerClientOptions : Azure.Core.ClientOptions { public CallingServerClientOptions(Azure.Communication.CallingServer.CallingServerClientOptions.ServiceVersion version = Azure.Communication.CallingServer.CallingServerClientOptions.ServiceVersion.V2021_08_30_Preview) { } public enum ServiceVersion { V2021_06_15_Preview = 1, V2021_08_30_Preview = 2, } } public abstract partial class CallingServerEventBase { protected CallingServerEventBase() { } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct CallingServerEventType : System.IEquatable<Azure.Communication.CallingServer.CallingServerEventType> { private readonly object _dummy; private readonly int _dummyPrimitive; public CallingServerEventType(string value) { throw null; } public static Azure.Communication.CallingServer.CallingServerEventType AddParticipantResultEvent { get { throw null; } } public static Azure.Communication.CallingServer.CallingServerEventType CallConnectionStateChangedEvent { get { throw null; } } public static Azure.Communication.CallingServer.CallingServerEventType CallRecordingStateChangeEvent { get { throw null; } } public static Azure.Communication.CallingServer.CallingServerEventType ParticipantsUpdatedEvent { get { throw null; } } public static Azure.Communication.CallingServer.CallingServerEventType PlayAudioResultEvent { get { throw null; } } public static Azure.Communication.CallingServer.CallingServerEventType ToneReceivedEvent { get { throw null; } } public bool Equals(Azure.Communication.CallingServer.CallingServerEventType other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Communication.CallingServer.CallingServerEventType left, Azure.Communication.CallingServer.CallingServerEventType right) { throw null; } public static bool operator !=(Azure.Communication.CallingServer.CallingServerEventType left, Azure.Communication.CallingServer.CallingServerEventType right) { throw null; } public override string ToString() { throw null; } } public static partial class CallingServerModelFactory { public static Azure.Communication.CallingServer.AddParticipantResult AddParticipantResult(string participantId = null) { throw null; } public static Azure.Communication.CallingServer.AddParticipantResultEvent AddParticipantResultEvent(Azure.Communication.CallingServer.ResultInfo resultInfo = null, string operationContext = null, Azure.Communication.CallingServer.OperationStatus status = default(Azure.Communication.CallingServer.OperationStatus)) { throw null; } public static Azure.Communication.CallingServer.CallConnectionStateChangedEvent CallConnectionStateChangedEvent(string serverCallId = null, string callConnectionId = null, Azure.Communication.CallingServer.CallConnectionState callConnectionState = default(Azure.Communication.CallingServer.CallConnectionState)) { throw null; } public static Azure.Communication.CallingServer.CallRecordingProperties CallRecordingProperties(Azure.Communication.CallingServer.CallRecordingState recordingState = default(Azure.Communication.CallingServer.CallRecordingState)) { throw null; } public static Azure.Communication.CallingServer.CallRecordingStateChangeEvent CallRecordingStateChangeEvent(string recordingId = null, Azure.Communication.CallingServer.CallRecordingState state = default(Azure.Communication.CallingServer.CallRecordingState), System.DateTimeOffset startDateTime = default(System.DateTimeOffset), string serverCallId = null) { throw null; } public static Azure.Communication.CallingServer.CancelAllMediaOperationsResult CancelAllMediaOperationsResult(string operationId = null, Azure.Communication.CallingServer.OperationStatus status = default(Azure.Communication.CallingServer.OperationStatus), string operationContext = null, Azure.Communication.CallingServer.ResultInfo resultInfo = null) { throw null; } public static Azure.Communication.CallingServer.PlayAudioResult PlayAudioResult(string operationId = null, Azure.Communication.CallingServer.OperationStatus status = default(Azure.Communication.CallingServer.OperationStatus), string operationContext = null, Azure.Communication.CallingServer.ResultInfo resultInfo = null) { throw null; } public static Azure.Communication.CallingServer.PlayAudioResultEvent PlayAudioResultEvent(Azure.Communication.CallingServer.ResultInfo resultInfo = null, string operationContext = null, Azure.Communication.CallingServer.OperationStatus status = default(Azure.Communication.CallingServer.OperationStatus)) { throw null; } public static Azure.Communication.CallingServer.ResultInfo ResultInfo(int code = 0, int subcode = 0, string message = null) { throw null; } public static Azure.Communication.CallingServer.StartRecordingResult StartRecordingResult(string recordingId = null) { throw null; } public static Azure.Communication.CallingServer.ToneInfo ToneInfo(int sequenceId = 0, Azure.Communication.CallingServer.ToneValue tone = default(Azure.Communication.CallingServer.ToneValue)) { throw null; } public static Azure.Communication.CallingServer.ToneReceivedEvent ToneReceivedEvent(Azure.Communication.CallingServer.ToneInfo toneInfo = null, string callConnectionId = null) { throw null; } } public partial class CallParticipant { internal CallParticipant() { } public Azure.Communication.CommunicationIdentifier Identifier { get { throw null; } } public bool IsMuted { get { throw null; } } public string ParticipantId { get { throw null; } } } public partial class CallRecordingProperties { internal CallRecordingProperties() { } public Azure.Communication.CallingServer.CallRecordingState RecordingState { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct CallRecordingState : System.IEquatable<Azure.Communication.CallingServer.CallRecordingState> { private readonly object _dummy; private readonly int _dummyPrimitive; public CallRecordingState(string value) { throw null; } public static Azure.Communication.CallingServer.CallRecordingState Active { get { throw null; } } public static Azure.Communication.CallingServer.CallRecordingState Inactive { get { throw null; } } public bool Equals(Azure.Communication.CallingServer.CallRecordingState other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Communication.CallingServer.CallRecordingState left, Azure.Communication.CallingServer.CallRecordingState right) { throw null; } public static implicit operator Azure.Communication.CallingServer.CallRecordingState (string value) { throw null; } public static bool operator !=(Azure.Communication.CallingServer.CallRecordingState left, Azure.Communication.CallingServer.CallRecordingState right) { throw null; } public override string ToString() { throw null; } } public partial class CallRecordingStateChangeEvent : Azure.Communication.CallingServer.CallingServerEventBase { internal CallRecordingStateChangeEvent() { } public string RecordingId { get { throw null; } } public string ServerCallId { get { throw null; } } public System.DateTimeOffset StartDateTime { get { throw null; } } public Azure.Communication.CallingServer.CallRecordingState State { get { throw null; } } public static Azure.Communication.CallingServer.CallRecordingStateChangeEvent Deserialize(string content) { throw null; } } public partial class CancelAllMediaOperationsResult { internal CancelAllMediaOperationsResult() { } public string OperationContext { get { throw null; } } public string OperationId { get { throw null; } } public Azure.Communication.CallingServer.ResultInfo ResultInfo { get { throw null; } } public Azure.Communication.CallingServer.OperationStatus Status { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct ContentTransferOptions : System.IEquatable<Azure.Communication.CallingServer.ContentTransferOptions> { public long InitialTransferSize { get { throw null; } set { } } public int MaximumConcurrency { get { throw null; } set { } } public long MaximumTransferSize { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public bool Equals(Azure.Communication.CallingServer.ContentTransferOptions obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static bool operator ==(Azure.Communication.CallingServer.ContentTransferOptions left, Azure.Communication.CallingServer.ContentTransferOptions right) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static bool operator !=(Azure.Communication.CallingServer.ContentTransferOptions left, Azure.Communication.CallingServer.ContentTransferOptions right) { throw null; } } public partial class CreateCallOptions { public CreateCallOptions(System.Uri callbackUri, System.Collections.Generic.IEnumerable<Azure.Communication.CallingServer.MediaType> requestedMediaTypes, System.Collections.Generic.IEnumerable<Azure.Communication.CallingServer.EventSubscriptionType> requestedCallEvents) { } public Azure.Communication.PhoneNumberIdentifier AlternateCallerId { get { throw null; } set { } } public System.Uri CallbackUri { get { throw null; } } public System.Collections.Generic.IList<Azure.Communication.CallingServer.EventSubscriptionType> RequestedCallEvents { get { throw null; } } public System.Collections.Generic.IList<Azure.Communication.CallingServer.MediaType> RequestedMediaTypes { get { throw null; } } public string Subject { get { throw null; } set { } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct EventSubscriptionType : System.IEquatable<Azure.Communication.CallingServer.EventSubscriptionType> { private readonly object _dummy; private readonly int _dummyPrimitive; public EventSubscriptionType(string value) { throw null; } public static Azure.Communication.CallingServer.EventSubscriptionType DtmfReceived { get { throw null; } } public static Azure.Communication.CallingServer.EventSubscriptionType ParticipantsUpdated { get { throw null; } } public bool Equals(Azure.Communication.CallingServer.EventSubscriptionType other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Communication.CallingServer.EventSubscriptionType left, Azure.Communication.CallingServer.EventSubscriptionType right) { throw null; } public static implicit operator Azure.Communication.CallingServer.EventSubscriptionType (string value) { throw null; } public static bool operator !=(Azure.Communication.CallingServer.EventSubscriptionType left, Azure.Communication.CallingServer.EventSubscriptionType right) { throw null; } public override string ToString() { throw null; } } public partial class JoinCallOptions { public JoinCallOptions(System.Uri callbackUri, System.Collections.Generic.IEnumerable<Azure.Communication.CallingServer.MediaType> requestedMediaTypes, System.Collections.Generic.IEnumerable<Azure.Communication.CallingServer.EventSubscriptionType> requestedCallEvents) { } public System.Uri CallbackUri { get { throw null; } } public System.Collections.Generic.IList<Azure.Communication.CallingServer.EventSubscriptionType> RequestedCallEvents { get { throw null; } } public System.Collections.Generic.IList<Azure.Communication.CallingServer.MediaType> RequestedMediaTypes { get { throw null; } } public string Subject { get { throw null; } set { } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct MediaType : System.IEquatable<Azure.Communication.CallingServer.MediaType> { private readonly object _dummy; private readonly int _dummyPrimitive; public MediaType(string value) { throw null; } public static Azure.Communication.CallingServer.MediaType Audio { get { throw null; } } public static Azure.Communication.CallingServer.MediaType Video { get { throw null; } } public bool Equals(Azure.Communication.CallingServer.MediaType other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Communication.CallingServer.MediaType left, Azure.Communication.CallingServer.MediaType right) { throw null; } public static implicit operator Azure.Communication.CallingServer.MediaType (string value) { throw null; } public static bool operator !=(Azure.Communication.CallingServer.MediaType left, Azure.Communication.CallingServer.MediaType right) { throw null; } public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct OperationStatus : System.IEquatable<Azure.Communication.CallingServer.OperationStatus> { private readonly object _dummy; private readonly int _dummyPrimitive; public OperationStatus(string value) { throw null; } public static Azure.Communication.CallingServer.OperationStatus Completed { get { throw null; } } public static Azure.Communication.CallingServer.OperationStatus Failed { get { throw null; } } public static Azure.Communication.CallingServer.OperationStatus NotStarted { get { throw null; } } public static Azure.Communication.CallingServer.OperationStatus Running { get { throw null; } } public bool Equals(Azure.Communication.CallingServer.OperationStatus other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Communication.CallingServer.OperationStatus left, Azure.Communication.CallingServer.OperationStatus right) { throw null; } public static implicit operator Azure.Communication.CallingServer.OperationStatus (string value) { throw null; } public static bool operator !=(Azure.Communication.CallingServer.OperationStatus left, Azure.Communication.CallingServer.OperationStatus right) { throw null; } public override string ToString() { throw null; } } public partial class ParticipantsUpdatedEvent : Azure.Communication.CallingServer.CallingServerEventBase { internal ParticipantsUpdatedEvent() { } public string CallConnectionId { get { throw null; } } public System.Collections.Generic.IEnumerable<Azure.Communication.CallingServer.CallParticipant> Participants { get { throw null; } } public static Azure.Communication.CallingServer.ParticipantsUpdatedEvent Deserialize(string content) { throw null; } } public partial class PlayAudioOptions { public PlayAudioOptions() { } public string AudioFileId { get { throw null; } set { } } public System.Uri AudioFileUri { get { throw null; } set { } } public System.Uri CallbackUri { get { throw null; } set { } } public bool? Loop { get { throw null; } set { } } public string OperationContext { get { throw null; } set { } } } public partial class PlayAudioResult { internal PlayAudioResult() { } public string OperationContext { get { throw null; } } public string OperationId { get { throw null; } } public Azure.Communication.CallingServer.ResultInfo ResultInfo { get { throw null; } } public Azure.Communication.CallingServer.OperationStatus Status { get { throw null; } } } public partial class PlayAudioResultEvent : Azure.Communication.CallingServer.CallingServerEventBase { internal PlayAudioResultEvent() { } public string OperationContext { get { throw null; } } public Azure.Communication.CallingServer.ResultInfo ResultInfo { get { throw null; } } public Azure.Communication.CallingServer.OperationStatus Status { get { throw null; } } public static Azure.Communication.CallingServer.PlayAudioResultEvent Deserialize(string content) { throw null; } } public enum RecordingChannel { Mixed = 0, Unmixed = 1, } public enum RecordingContent { Audio = 0, AudioVideo = 1, } public enum RecordingFormat { Wav = 0, Mp3 = 1, Mp4 = 2, } public partial class ResultInfo { internal ResultInfo() { } public int Code { get { throw null; } } public string Message { get { throw null; } } public int Subcode { get { throw null; } } } public partial class ServerCall { protected ServerCall() { } public virtual Azure.Response<Azure.Communication.CallingServer.AddParticipantResult> AddParticipant(Azure.Communication.CommunicationIdentifier participant, System.Uri callbackUri, string alternateCallerId = null, string operationContext = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Communication.CallingServer.AddParticipantResult>> AddParticipantAsync(Azure.Communication.CommunicationIdentifier participant, System.Uri callbackUri, string alternateCallerId = null, string operationContext = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Communication.CallingServer.CallRecordingProperties> GetRecordingState(string recordingId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Communication.CallingServer.CallRecordingProperties>> GetRecordingStateAsync(string recordingId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response PauseRecording(string recordingId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> PauseRecordingAsync(string recordingId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Communication.CallingServer.PlayAudioResult> PlayAudio(System.Uri audioFileUri, string audioFileId, System.Uri callbackUri, string operationContext = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Communication.CallingServer.PlayAudioResult>> PlayAudioAsync(System.Uri audioFileUri, string audioFileId, System.Uri callbackUri, string operationContext = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response RemoveParticipant(string participantId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> RemoveParticipantAsync(string participantId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response ResumeRecording(string recordingId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> ResumeRecordingAsync(string recordingId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Communication.CallingServer.StartRecordingResult> StartRecording(System.Uri recordingStateCallbackUri, Azure.Communication.CallingServer.RecordingContent? content = default(Azure.Communication.CallingServer.RecordingContent?), Azure.Communication.CallingServer.RecordingChannel? channel = default(Azure.Communication.CallingServer.RecordingChannel?), Azure.Communication.CallingServer.RecordingFormat? format = default(Azure.Communication.CallingServer.RecordingFormat?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Communication.CallingServer.StartRecordingResult>> StartRecordingAsync(System.Uri recordingStateCallbackUri, Azure.Communication.CallingServer.RecordingContent? content = default(Azure.Communication.CallingServer.RecordingContent?), Azure.Communication.CallingServer.RecordingChannel? channel = default(Azure.Communication.CallingServer.RecordingChannel?), Azure.Communication.CallingServer.RecordingFormat? format = default(Azure.Communication.CallingServer.RecordingFormat?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response StopRecording(string recordingId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> StopRecordingAsync(string recordingId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class StartRecordingResult { internal StartRecordingResult() { } public string RecordingId { get { throw null; } } } public partial class ToneInfo { internal ToneInfo() { } public int SequenceId { get { throw null; } } public Azure.Communication.CallingServer.ToneValue Tone { get { throw null; } } } public partial class ToneReceivedEvent : Azure.Communication.CallingServer.CallingServerEventBase { internal ToneReceivedEvent() { } public string CallConnectionId { get { throw null; } } public Azure.Communication.CallingServer.ToneInfo ToneInfo { get { throw null; } } public static Azure.Communication.CallingServer.ToneReceivedEvent Deserialize(string content) { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct ToneValue : System.IEquatable<Azure.Communication.CallingServer.ToneValue> { private readonly object _dummy; private readonly int _dummyPrimitive; public ToneValue(string value) { throw null; } public static Azure.Communication.CallingServer.ToneValue A { get { throw null; } } public static Azure.Communication.CallingServer.ToneValue B { get { throw null; } } public static Azure.Communication.CallingServer.ToneValue C { get { throw null; } } public static Azure.Communication.CallingServer.ToneValue D { get { throw null; } } public static Azure.Communication.CallingServer.ToneValue Flash { get { throw null; } } public static Azure.Communication.CallingServer.ToneValue Pound { get { throw null; } } public static Azure.Communication.CallingServer.ToneValue Star { get { throw null; } } public static Azure.Communication.CallingServer.ToneValue Tone0 { get { throw null; } } public static Azure.Communication.CallingServer.ToneValue Tone1 { get { throw null; } } public static Azure.Communication.CallingServer.ToneValue Tone2 { get { throw null; } } public static Azure.Communication.CallingServer.ToneValue Tone3 { get { throw null; } } public static Azure.Communication.CallingServer.ToneValue Tone4 { get { throw null; } } public static Azure.Communication.CallingServer.ToneValue Tone5 { get { throw null; } } public static Azure.Communication.CallingServer.ToneValue Tone6 { get { throw null; } } public static Azure.Communication.CallingServer.ToneValue Tone7 { get { throw null; } } public static Azure.Communication.CallingServer.ToneValue Tone8 { get { throw null; } } public static Azure.Communication.CallingServer.ToneValue Tone9 { get { throw null; } } public bool Equals(Azure.Communication.CallingServer.ToneValue other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Communication.CallingServer.ToneValue left, Azure.Communication.CallingServer.ToneValue right) { throw null; } public static implicit operator Azure.Communication.CallingServer.ToneValue (string value) { throw null; } public static bool operator !=(Azure.Communication.CallingServer.ToneValue left, Azure.Communication.CallingServer.ToneValue right) { throw null; } public override string ToString() { throw null; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Options.cs" company="The Watcher"> // Copyright (c) The Watcher Partial Rights Reserved. // This software is licensed under the MIT license. See license.txt for details. // </copyright> // <summary> // Code Named: PG-Ripper // Function : Extracts Images posted on VB forums and attempts to fetch them to disk. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Ripper { using System; using System.Reflection; using System.Resources; using System.Windows.Forms; using Ripper.Core.Components; /// <summary> /// Options Dialog /// </summary> public partial class Options : Form { /// <summary> /// The Resource Manager Instance /// </summary> private ResourceManager resourceManager; /// <summary> /// Initializes a new instance of the <see cref="Options"/> class. /// </summary> public Options() { this.InitializeComponent(); this.LoadSettings(); } /// <summary> /// Loads the settings. /// </summary> public void LoadSettings() { #if (PGRIPPERX) checkBox9.Enabled = false; showTrayPopups.Enabled = false; checkBox10.Enabled = false; #endif // Load "Show Tray PopUps" Setting this.showTrayPopups.Checked = CacheController.Instance().UserSettings.ShowPopUps; // Load "Download Folder" Setting this.textBox2.Text = CacheController.Instance().UserSettings.DownloadFolder; // Load "Thread Limit" Setting this.numericUDThreads.Text = CacheController.Instance().UserSettings.ThreadLimit.ToString(); ThreadManager.GetInstance().SetThreadThreshHold(Convert.ToInt32(this.numericUDThreads.Text)); // min. Image Count for Thanks this.numericUDThanks.Text = CacheController.Instance().UserSettings.MinImageCount.ToString(); // Load "Create Subdirctories" Setting this.checkBox1.Checked = CacheController.Instance().UserSettings.SubDirs; // Load Show Last Download Image Setting this.checkBox11.Checked = CacheController.Instance().UserSettings.ShowLastDownloaded; // Load "Automaticly Thank You Button" Setting if (CacheController.Instance().UserSettings.AutoThank) { this.checkBox8.Checked = true; } else { this.checkBox8.Checked = false; this.numericUDThanks.Enabled = false; } // Load "Clipboard Watch" Setting this.checkBox10.Checked = CacheController.Instance().UserSettings.ClipBWatch; // Load "Always on Top" Setting this.checkBox5.Checked = CacheController.Instance().UserSettings.TopMost; this.TopMost = CacheController.Instance().UserSettings.TopMost; // Load "Download each post in its own folder" Setting this.mDownInSepFolderChk.Checked = CacheController.Instance().UserSettings.DownInSepFolder; if (!this.checkBox1.Checked) { this.mDownInSepFolderChk.Checked = false; this.mDownInSepFolderChk.Enabled = false; } // Load "Save Ripped posts for checking" Setting this.saveHistoryChk.Checked = CacheController.Instance().UserSettings.SavePids; // Load "Show Downloads Complete PopUp" Setting this.checkBox9.Checked = CacheController.Instance().UserSettings.ShowCompletePopUp; // Load Language Setting try { switch (CacheController.Instance().UserSettings.Language) { case "de-DE": this.resourceManager = new ResourceManager("Ripper.Languages.german", Assembly.GetExecutingAssembly()); this.languageSelector.SelectedIndex = 0; this.pictureBox2.Image = Languages.english.de; break; case "fr-FR": this.resourceManager = new ResourceManager("Ripper.Languages.french", Assembly.GetExecutingAssembly()); this.languageSelector.SelectedIndex = 1; this.pictureBox2.Image = Languages.english.fr; break; case "en-EN": this.resourceManager = new ResourceManager("Ripper.Languages.english", Assembly.GetExecutingAssembly()); this.languageSelector.SelectedIndex = 2; this.pictureBox2.Image = Languages.english.us; break; default: this.resourceManager = new ResourceManager("Ripper.Languages.english", Assembly.GetExecutingAssembly()); this.languageSelector.SelectedIndex = 2; this.pictureBox2.Image = Languages.english.us; break; } this.AdjustCulture(); } catch (Exception) { this.languageSelector.SelectedIndex = 2; this.pictureBox2.Image = Languages.english.us; } } /// <summary> /// Set Language Strings /// </summary> private void AdjustCulture() { this.groupBox1.Text = this.resourceManager.GetString("downloadOptions"); this.label2.Text = this.resourceManager.GetString("lblDownloadFolder"); this.button4.Text = this.resourceManager.GetString("btnBrowse"); this.checkBox1.Text = this.resourceManager.GetString("chbSubdirectories"); this.checkBox8.Text = this.resourceManager.GetString("chbAutoTKButton"); this.showTrayPopups.Text = this.resourceManager.GetString("chbShowPopUps"); this.checkBox5.Text = this.resourceManager.GetString("chbAlwaysOnTop"); this.checkBox9.Text = this.resourceManager.GetString("chbShowDCPopUps"); this.mDownInSepFolderChk.Text = this.resourceManager.GetString("chbSubThreadRip"); this.saveHistoryChk.Text = this.resourceManager.GetString("chbSaveHistory"); this.label6.Text = this.resourceManager.GetString("lblThreadLimit"); this.label1.Text = this.resourceManager.GetString("lblminImageCount"); this.groupBox3.Text = this.resourceManager.GetString("gbMainOptions"); this.checkBox11.Text = this.resourceManager.GetString("ShowLastDownloaded"); this.checkBox10.Text = this.resourceManager.GetString("clipboardWatch"); } /// <summary> /// Switch Language /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void LanguageSelectorSelectedIndexChanged(object sender, EventArgs e) { switch (this.languageSelector.SelectedIndex) { case 0: this.pictureBox2.Image = Languages.english.de; break; case 1: this.pictureBox2.Image = Languages.english.fr; break; case 2: this.pictureBox2.Image = Languages.english.us; break; } } /// <summary> /// Open Browse Download Folder Dialog /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void Button4Click(object sender, EventArgs e) { this.FBD.ShowDialog(this); if (this.FBD.SelectedPath.Length <= 1) { return; } this.textBox2.Text = this.FBD.SelectedPath; CacheController.Instance().UserSettings.DownloadFolder = this.textBox2.Text; SettingsHelper.SaveSettings(CacheController.Instance().UserSettings); } /// <summary> /// Close Dialog and Save Changes /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void OkButtonClick(object sender, EventArgs e) { try { string mbThreadNum = this.resourceManager.GetString("mbThreadNum"), mbThreadbetw = this.resourceManager.GetString("mbThreadbetw"), mbNum = this.resourceManager.GetString("mbNum"); if (!Utility.IsNumeric(this.numericUDThreads.Text)) { MessageBox.Show(this, mbThreadNum); return; } if (!Utility.IsNumeric(this.numericUDThanks.Text)) { MessageBox.Show(this, mbNum); return; } if (Convert.ToInt32(this.numericUDThreads.Text) > 20 || Convert.ToInt32(this.numericUDThreads.Text) < 1) { MessageBox.Show(this, mbThreadbetw); return; } ThreadManager.GetInstance().SetThreadThreshHold(Convert.ToInt32(this.numericUDThreads.Text)); CacheController.Instance().UserSettings.ThreadLimit = Convert.ToInt32(this.numericUDThreads.Text); CacheController.Instance().UserSettings.MinImageCount = Convert.ToInt32(this.numericUDThanks.Text); CacheController.Instance().UserSettings.SubDirs = this.checkBox1.Checked; CacheController.Instance().UserSettings.AutoThank = this.checkBox8.Checked; CacheController.Instance().UserSettings.ClipBWatch = this.checkBox10.Checked; CacheController.Instance().UserSettings.ShowPopUps = this.showTrayPopups.Checked; CacheController.Instance().UserSettings.TopMost = this.checkBox5.Checked; CacheController.Instance().UserSettings.DownInSepFolder = this.mDownInSepFolderChk.Checked; CacheController.Instance().UserSettings.SavePids = this.saveHistoryChk.Checked; CacheController.Instance().UserSettings.ShowCompletePopUp = this.checkBox9.Checked; CacheController.Instance().UserSettings.ShowLastDownloaded = this.checkBox11.Checked; switch (this.languageSelector.SelectedIndex) { case 0: CacheController.Instance().UserSettings.Language = "de-DE"; break; case 1: CacheController.Instance().UserSettings.Language = "fr-FR"; break; case 2: CacheController.Instance().UserSettings.Language = "en-EN"; break; } } finally { SettingsHelper.SaveSettings(CacheController.Instance().UserSettings); this.Close(); } } /// <summary> /// Checks the box8 checked changed. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void CheckBox8CheckedChanged(object sender, EventArgs e) { this.numericUDThanks.Enabled = this.checkBox8.Checked; } /// <summary> /// Checks the box1 checked changed. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void CheckBox1CheckedChanged(object sender, EventArgs e) { if (this.checkBox1.Checked) { this.mDownInSepFolderChk.Enabled = true; } else { this.mDownInSepFolderChk.Enabled = false; this.mDownInSepFolderChk.Checked = false; } } /// <summary> /// Check if Input is a Number between 1-20 /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void NumericUdThreadsValueChanged(object sender, EventArgs e) { if (Convert.ToInt32(this.numericUDThreads.Text) <= 20 && Convert.ToInt32(this.numericUDThreads.Text) >= 1) { return; } MessageBox.Show(this, this.resourceManager.GetString("mbThreadbetw")); this.numericUDThreads.Text = "3"; } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Internal.FileAppenders { using System; using System.IO; using System.Text; using Xunit; using NLog.Targets; using NLog.Internal.FileAppenders; public class FileAppenderCacheTests : NLogTestBase { [Fact] public void FileAppenderCache_Empty() { FileAppenderCache cache = FileAppenderCache.Empty; // An empty FileAppenderCache will have Size = 0 as well as Factory and CreateFileParameters parameters equal to null. Assert.True(cache.Size == 0); Assert.Null(cache.Factory); Assert.Null(cache.CreateFileParameters); } [Fact] public void FileAppenderCache_Construction() { IFileAppenderFactory appenderFactory = SingleProcessFileAppender.TheFactory; ICreateFileParameters fileTarget = new FileTarget(); FileAppenderCache cache = new FileAppenderCache(3, appenderFactory, fileTarget); Assert.True(cache.Size == 3); Assert.NotNull(cache.Factory); Assert.NotNull(cache.CreateFileParameters); } [Fact] public void FileAppenderCache_Allocate() { // Allocate on an Empty FileAppenderCache. FileAppenderCache emptyCache = FileAppenderCache.Empty; Assert.Throws<NullReferenceException>(() => emptyCache.AllocateAppender("file.txt")); // Construct a on non-empty FileAppenderCache. IFileAppenderFactory appenderFactory = SingleProcessFileAppender.TheFactory; ICreateFileParameters fileTarget = new FileTarget(); String tempFile = Path.Combine( Path.GetTempPath(), Path.Combine(Guid.NewGuid().ToString(), "file.txt") ); // Allocate an appender. FileAppenderCache cache = new FileAppenderCache(3, appenderFactory, fileTarget); BaseFileAppender appender = cache.AllocateAppender(tempFile); // // Note: Encoding is ASSUMED to be Unicode. There is no explicit reference to which encoding will be used // for the file. // // Write, flush the content into the file and release the file. // We need to release the file before invoking AssertFileContents() method. appender.Write(StringToBytes("NLog test string.")); appender.Flush(); appender.Close(); // Verify the appender has been allocated correctly. AssertFileContents(tempFile, "NLog test string.", Encoding.Unicode); } [Fact] public void FileAppenderCache_InvalidateAppender() { // Invoke InvalidateAppender() on an Empty FileAppenderCache. FileAppenderCache emptyCache = FileAppenderCache.Empty; emptyCache.InvalidateAppender("file.txt"); // Construct a on non-empty FileAppenderCache. IFileAppenderFactory appenderFactory = SingleProcessFileAppender.TheFactory; ICreateFileParameters fileTarget = new FileTarget(); String tempFile = Path.Combine( Path.GetTempPath(), Path.Combine(Guid.NewGuid().ToString(), "file.txt") ); // Allocate an appender. FileAppenderCache cache = new FileAppenderCache(3, appenderFactory, fileTarget); BaseFileAppender appender = cache.AllocateAppender(tempFile); // // Note: Encoding is ASSUMED to be Unicode. There is no explicit reference to which encoding will be used // for the file. // // Write, flush the content into the file and release the file. This happens through the // InvalidateAppender() method. We need to release the file before invoking AssertFileContents() method. appender.Write(StringToBytes("NLog test string.")); cache.InvalidateAppender(tempFile); // Verify the appender has been allocated correctly. AssertFileContents(tempFile, "NLog test string.", Encoding.Unicode); } [Fact] public void FileAppenderCache_CloseAppenders() { // Invoke CloseAppenders() on an Empty FileAppenderCache. FileAppenderCache emptyCache = FileAppenderCache.Empty; emptyCache.CloseAppenders(string.Empty); IFileAppenderFactory appenderFactory = SingleProcessFileAppender.TheFactory; ICreateFileParameters fileTarget = new FileTarget(); FileAppenderCache cache = new FileAppenderCache(3, appenderFactory, fileTarget); // Invoke CloseAppenders() on non-empty FileAppenderCache - Before allocating any appenders. cache.CloseAppenders(string.Empty); // Invoke CloseAppenders() on non-empty FileAppenderCache - After allocating N appenders. cache.AllocateAppender("file1.txt"); cache.AllocateAppender("file2.txt"); cache.CloseAppenders(string.Empty); // Invoke CloseAppenders() on non-empty FileAppenderCache - After allocating N appenders. cache.AllocateAppender("file1.txt"); cache.AllocateAppender("file2.txt"); cache.CloseAppenders(string.Empty); FileAppenderCache cache2 = new FileAppenderCache(3, appenderFactory, fileTarget); // Invoke CloseAppenders() on non-empty FileAppenderCache - Before allocating any appenders. cache2.CloseAppenders(DateTime.Now); // Invoke CloseAppenders() on non-empty FileAppenderCache - After allocating N appenders. cache.AllocateAppender("file1.txt"); cache.AllocateAppender("file2.txt"); cache.CloseAppenders(DateTime.Now); } [Fact] public void FileAppenderCache_GetFileCharacteristics_Single() { IFileAppenderFactory appenderFactory = SingleProcessFileAppender.TheFactory; ICreateFileParameters fileTarget = new FileTarget() { ArchiveNumbering = ArchiveNumberingMode.Date }; FileAppenderCache_GetFileCharacteristics(appenderFactory, fileTarget); } [Fact] public void FileAppenderCache_GetFileCharacteristics_Multi() { IFileAppenderFactory appenderFactory = MutexMultiProcessFileAppender.TheFactory; ICreateFileParameters fileTarget = new FileTarget() { ArchiveNumbering = ArchiveNumberingMode.Date, ForceManaged = true }; FileAppenderCache_GetFileCharacteristics(appenderFactory, fileTarget); } #if !MONO && !NETSTANDARD [Fact] public void FileAppenderCache_GetFileCharacteristics_Windows() { if (NLog.Internal.PlatformDetector.IsWin32) { IFileAppenderFactory appenderFactory = WindowsMultiProcessFileAppender.TheFactory; ICreateFileParameters fileTarget = new FileTarget() { ArchiveNumbering = ArchiveNumberingMode.Date }; FileAppenderCache_GetFileCharacteristics(appenderFactory, fileTarget); } } #endif private void FileAppenderCache_GetFileCharacteristics(IFileAppenderFactory appenderFactory, ICreateFileParameters fileParameters) { // Invoke GetFileCharacteristics() on an Empty FileAppenderCache. FileAppenderCache emptyCache = FileAppenderCache.Empty; Assert.Null(emptyCache.GetFileCreationTimeSource("file.txt")); Assert.Null(emptyCache.GetFileLastWriteTimeUtc("file.txt")); Assert.Null(emptyCache.GetFileLength("file.txt")); FileAppenderCache cache = new FileAppenderCache(3, appenderFactory, fileParameters); // Invoke GetFileCharacteristics() on non-empty FileAppenderCache - Before allocating any appenders. Assert.Null(emptyCache.GetFileCreationTimeSource("file.txt")); Assert.Null(emptyCache.GetFileLastWriteTimeUtc("file.txt")); Assert.Null(emptyCache.GetFileLength("file.txt")); String tempFile = Path.Combine( Path.GetTempPath(), Path.Combine(Guid.NewGuid().ToString(), "file.txt") ); // Allocate an appender. BaseFileAppender appender = cache.AllocateAppender(tempFile); appender.Write(StringToBytes("NLog test string.")); // // Note: Encoding is ASSUMED to be Unicode. There is no explicit reference to which encoding will be used // for the file. // // File information should be returned. var fileCreationTimeUtc = cache.GetFileCreationTimeSource(tempFile); Assert.NotNull(fileCreationTimeUtc); Assert.True(fileCreationTimeUtc > Time.TimeSource.Current.FromSystemTime(DateTime.UtcNow.AddMinutes(-2)),"creationtime is wrong"); var fileLastWriteTimeUtc = cache.GetFileLastWriteTimeUtc(tempFile); Assert.NotNull(fileLastWriteTimeUtc); Assert.True(fileLastWriteTimeUtc > DateTime.UtcNow.AddMinutes(-2), "lastwrite is wrong"); Assert.Equal(34, cache.GetFileLength(tempFile)); // Clean up. appender.Flush(); appender.Close(); } /// <summary> /// Converts a string to byte array. /// </summary> private static byte[] StringToBytes(string text) { byte[] bytes = new byte[sizeof(char) * text.Length]; Buffer.BlockCopy(text.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; } } }
/* * 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.Collections.Generic; using NUnit.Framework; using QuantConnect.Data.Consolidators; using QuantConnect.Data.Market; using QuantConnect.Indicators; namespace QuantConnect.Tests.Common.Data { [TestFixture] public class ClassicRenkoConsolidatorTests { [Test] public void ClassicOutputTypeIsRenkoBar() { var consolidator = new ClassicRenkoConsolidator(10, x => x.Value, x => 0); Assert.AreEqual(typeof(RenkoBar), consolidator.OutputType); } [Test] public void ClassicConsolidatesOnBrickHigh() { RenkoBar bar = null; var consolidator = new ClassicRenkoConsolidator(10, x => x.Value, x => 0); consolidator.DataConsolidated += (sender, consolidated) => { bar = consolidated; }; var reference = DateTime.Today; consolidator.Update(new IndicatorDataPoint(reference, 0m)); Assert.IsNull(bar); consolidator.Update(new IndicatorDataPoint(reference.AddHours(1), 5m)); Assert.IsNull(bar); consolidator.Update(new IndicatorDataPoint(reference.AddHours(2), 10m)); Assert.IsNotNull(bar); Assert.AreEqual(0m, bar.Open); Assert.AreEqual(10m, bar.Close); Assert.IsTrue(bar.IsClosed); } [Test] public void ClassicConsolidatesOnBrickLow() { RenkoBar bar = null; var consolidator = new ClassicRenkoConsolidator(10, x => x.Value, x => 0); consolidator.DataConsolidated += (sender, consolidated) => { bar = consolidated; }; var reference = DateTime.Today; consolidator.Update(new IndicatorDataPoint(reference, 10m)); Assert.IsNull(bar); consolidator.Update(new IndicatorDataPoint(reference.AddHours(1), 2m)); Assert.IsNull(bar); consolidator.Update(new IndicatorDataPoint(reference.AddHours(2), 0m)); Assert.IsNotNull(bar); Assert.AreEqual(10m, bar.Open); Assert.AreEqual(0m, bar.Close); Assert.IsTrue(bar.IsClosed); } [Test] public void ConsistentRenkos() { // Test Renko bar consistency amongst three consolidators starting at different times var time = new DateTime(2016, 1, 1); var testValues = new List<decimal> { 1.38687m, 1.38688m, 1.38687m, 1.38686m, 1.38685m, 1.38683m, 1.38682m, 1.38682m, 1.38684m, 1.38682m, 1.38682m, 1.38680m, 1.38681m, 1.38686m, 1.38688m, 1.38688m, 1.38690m, 1.38690m, 1.38691m, 1.38692m, 1.38694m, 1.38695m, 1.38697m, 1.38697m, 1.38700m, 1.38699m, 1.38699m, 1.38699m, 1.38698m, 1.38699m, 1.38697m, 1.38698m, 1.38698m, 1.38697m, 1.38698m, 1.38698m, 1.38697m, 1.38697m, 1.38700m, 1.38702m, 1.38701m, 1.38699m, 1.38697m, 1.38698m, 1.38696m, 1.38698m, 1.38697m, 1.38695m, 1.38695m, 1.38696m, 1.38693m, 1.38692m, 1.38693m, 1.38693m, 1.38692m, 1.38693m, 1.38692m, 1.38690m, 1.38686m, 1.38685m, 1.38687m, 1.38686m, 1.38686m, 1.38686m, 1.38686m, 1.38685m, 1.38684m, 1.38678m, 1.38679m, 1.38680m, 1.38680m, 1.38681m, 1.38685m, 1.38685m, 1.38683m, 1.38682m, 1.38682m, 1.38683m, 1.38682m, 1.38683m, 1.38682m, 1.38681m, 1.38680m, 1.38681m, 1.38681m, 1.38681m, 1.38682m, 1.38680m, 1.38679m, 1.38678m, 1.38675m, 1.38678m, 1.38678m, 1.38678m, 1.38682m, 1.38681m, 1.38682m, 1.38680m, 1.38682m, 1.38683m, 1.38685m, 1.38683m, 1.38683m, 1.38684m, 1.38683m, 1.38683m, 1.38684m, 1.38685m, 1.38684m, 1.38683m, 1.38686m, 1.38685m, 1.38685m, 1.38684m, 1.38685m, 1.38682m, 1.38684m, 1.38683m, 1.38682m, 1.38683m, 1.38685m, 1.38685m, 1.38685m, 1.38683m, 1.38685m, 1.38684m, 1.38686m, 1.38693m, 1.38695m, 1.38693m, 1.38694m, 1.38693m, 1.38692m, 1.38693m, 1.38695m, 1.38697m, 1.38698m, 1.38695m, 1.38696m }; var consolidator1 = new ClassicRenkoConsolidator(0.0001m); var consolidator2 = new ClassicRenkoConsolidator(0.0001m); var consolidator3 = new ClassicRenkoConsolidator(0.0001m); // Update each of our consolidators starting at different indexes of test values for (int i = 0; i < testValues.Count; i++) { var data = new IndicatorDataPoint(time.AddSeconds(i), testValues[i]); consolidator1.Update(data); if (i > 10) { consolidator2.Update(data); } if (i > 20) { consolidator3.Update(data); } } // Assert that consolidator 2 and 3 price is the same as 1. Even though they started at different // indexes they should be the same var bar1 = consolidator1.Consolidated as RenkoBar; var bar2 = consolidator2.Consolidated as RenkoBar; var bar3 = consolidator3.Consolidated as RenkoBar; Assert.AreEqual(bar1.Close, bar2.Close); Assert.AreEqual(bar1.Close, bar3.Close); consolidator1.Dispose(); consolidator2.Dispose(); consolidator3.Dispose(); } [Test] public void ClassicCyclesUpAndDown() { RenkoBar bar = null; int rcount = 0; var consolidator = new ClassicRenkoConsolidator(1m, x => x.Value, x => 0); consolidator.DataConsolidated += (sender, consolidated) => { rcount++; bar = consolidated; }; var reference = DateTime.Today; // opens at 0 consolidator.Update(new IndicatorDataPoint(reference, 0)); Assert.IsNull(bar); consolidator.Update(new IndicatorDataPoint(reference.AddSeconds(1), .5m)); Assert.IsNull(bar); consolidator.Update(new IndicatorDataPoint(reference.AddSeconds(2), 1m)); Assert.IsNotNull(bar); Assert.AreEqual(0m, bar.Open); Assert.AreEqual(1m, bar.Close); Assert.AreEqual(0, bar.Volume); Assert.AreEqual(1m, bar.High); Assert.AreEqual(0m, bar.Low); Assert.IsTrue(bar.IsClosed); Assert.AreEqual(reference, bar.Start); Assert.AreEqual(reference.AddSeconds(2), bar.EndTime); bar = null; consolidator.Update(new IndicatorDataPoint(reference.AddSeconds(3), 1.5m)); Assert.IsNull(bar); consolidator.Update(new IndicatorDataPoint(reference.AddSeconds(4), 1m)); Assert.IsNull(bar); consolidator.Update(new IndicatorDataPoint(reference.AddSeconds(5), .5m)); Assert.IsNull(bar); consolidator.Update(new IndicatorDataPoint(reference.AddSeconds(6), 0m)); Assert.IsNotNull(bar); // ReSharper disable HeuristicUnreachableCode - ReSharper doesn't realiz this can be set via the event handler Assert.AreEqual(1m, bar.Open); Assert.AreEqual(0m, bar.Close); Assert.AreEqual(0, bar.Volume); Assert.AreEqual(1.5m, bar.High); Assert.AreEqual(0m, bar.Low); Assert.IsTrue(bar.IsClosed); Assert.AreEqual(reference.AddSeconds(2), bar.Start); Assert.AreEqual(reference.AddSeconds(6), bar.EndTime); bar = null; consolidator.Update(new IndicatorDataPoint(reference.AddSeconds(7), -0.5m)); Assert.IsNull(bar); consolidator.Update(new IndicatorDataPoint(reference.AddSeconds(8), -0.9999999m)); Assert.IsNull(bar); consolidator.Update(new IndicatorDataPoint(reference.AddSeconds(9), -0.01m)); Assert.IsNull(bar); consolidator.Update(new IndicatorDataPoint(reference.AddSeconds(10), 0.25m)); Assert.IsNull(bar); consolidator.Update(new IndicatorDataPoint(reference.AddSeconds(9), 0.75m)); Assert.IsNull(bar); consolidator.Update(new IndicatorDataPoint(reference.AddSeconds(10), 0.9999999m)); Assert.IsNull(bar); consolidator.Update(new IndicatorDataPoint(reference.AddSeconds(10), 0.25m)); Assert.IsNull(bar); consolidator.Update(new IndicatorDataPoint(reference.AddSeconds(9), -0.25m)); Assert.IsNull(bar); consolidator.Update(new IndicatorDataPoint(reference.AddSeconds(10), -1m)); Assert.IsNotNull(bar); Assert.AreEqual(0m, bar.Open); Assert.AreEqual(-1m, bar.Close); Assert.AreEqual(0, bar.Volume); Assert.AreEqual(0.9999999m, bar.High); Assert.AreEqual(-1m, bar.Low); Assert.IsTrue(bar.IsClosed); Assert.AreEqual(reference.AddSeconds(6), bar.Start); Assert.AreEqual(reference.AddSeconds(10), bar.EndTime); // ReSharper restore HeuristicUnreachableCode } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcav = Google.Cloud.AIPlatform.V1; using sys = System; namespace Google.Cloud.AIPlatform.V1 { /// <summary>Resource name for the <c>SpecialistPool</c> resource.</summary> public sealed partial class SpecialistPoolName : gax::IResourceName, sys::IEquatable<SpecialistPoolName> { /// <summary>The possible contents of <see cref="SpecialistPoolName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/specialistPools/{specialist_pool}</c>. /// </summary> ProjectLocationSpecialistPool = 1, } private static gax::PathTemplate s_projectLocationSpecialistPool = new gax::PathTemplate("projects/{project}/locations/{location}/specialistPools/{specialist_pool}"); /// <summary>Creates a <see cref="SpecialistPoolName"/> 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="SpecialistPoolName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static SpecialistPoolName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new SpecialistPoolName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="SpecialistPoolName"/> with the pattern /// <c>projects/{project}/locations/{location}/specialistPools/{specialist_pool}</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="specialistPoolId">The <c>SpecialistPool</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="SpecialistPoolName"/> constructed from the provided ids.</returns> public static SpecialistPoolName FromProjectLocationSpecialistPool(string projectId, string locationId, string specialistPoolId) => new SpecialistPoolName(ResourceNameType.ProjectLocationSpecialistPool, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), specialistPoolId: gax::GaxPreconditions.CheckNotNullOrEmpty(specialistPoolId, nameof(specialistPoolId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="SpecialistPoolName"/> with pattern /// <c>projects/{project}/locations/{location}/specialistPools/{specialist_pool}</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="specialistPoolId">The <c>SpecialistPool</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SpecialistPoolName"/> with pattern /// <c>projects/{project}/locations/{location}/specialistPools/{specialist_pool}</c>. /// </returns> public static string Format(string projectId, string locationId, string specialistPoolId) => FormatProjectLocationSpecialistPool(projectId, locationId, specialistPoolId); /// <summary> /// Formats the IDs into the string representation of this <see cref="SpecialistPoolName"/> with pattern /// <c>projects/{project}/locations/{location}/specialistPools/{specialist_pool}</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="specialistPoolId">The <c>SpecialistPool</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SpecialistPoolName"/> with pattern /// <c>projects/{project}/locations/{location}/specialistPools/{specialist_pool}</c>. /// </returns> public static string FormatProjectLocationSpecialistPool(string projectId, string locationId, string specialistPoolId) => s_projectLocationSpecialistPool.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(specialistPoolId, nameof(specialistPoolId))); /// <summary> /// Parses the given resource name string into a new <see cref="SpecialistPoolName"/> 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}/specialistPools/{specialist_pool}</c></description> /// </item> /// </list> /// </remarks> /// <param name="specialistPoolName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="SpecialistPoolName"/> if successful.</returns> public static SpecialistPoolName Parse(string specialistPoolName) => Parse(specialistPoolName, false); /// <summary> /// Parses the given resource name string into a new <see cref="SpecialistPoolName"/> 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}/specialistPools/{specialist_pool}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="specialistPoolName">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="SpecialistPoolName"/> if successful.</returns> public static SpecialistPoolName Parse(string specialistPoolName, bool allowUnparsed) => TryParse(specialistPoolName, allowUnparsed, out SpecialistPoolName 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="SpecialistPoolName"/> 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}/specialistPools/{specialist_pool}</c></description> /// </item> /// </list> /// </remarks> /// <param name="specialistPoolName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="SpecialistPoolName"/>, 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 specialistPoolName, out SpecialistPoolName result) => TryParse(specialistPoolName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="SpecialistPoolName"/> 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}/specialistPools/{specialist_pool}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="specialistPoolName">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="SpecialistPoolName"/>, 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 specialistPoolName, bool allowUnparsed, out SpecialistPoolName result) { gax::GaxPreconditions.CheckNotNull(specialistPoolName, nameof(specialistPoolName)); gax::TemplatedResourceName resourceName; if (s_projectLocationSpecialistPool.TryParseName(specialistPoolName, out resourceName)) { result = FromProjectLocationSpecialistPool(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(specialistPoolName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private SpecialistPoolName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string specialistPoolId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; ProjectId = projectId; SpecialistPoolId = specialistPoolId; } /// <summary> /// Constructs a new instance of a <see cref="SpecialistPoolName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/specialistPools/{specialist_pool}</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="specialistPoolId">The <c>SpecialistPool</c> ID. Must not be <c>null</c> or empty.</param> public SpecialistPoolName(string projectId, string locationId, string specialistPoolId) : this(ResourceNameType.ProjectLocationSpecialistPool, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), specialistPoolId: gax::GaxPreconditions.CheckNotNullOrEmpty(specialistPoolId, nameof(specialistPoolId))) { } /// <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>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>SpecialistPool</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string SpecialistPoolId { 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.ProjectLocationSpecialistPool: return s_projectLocationSpecialistPool.Expand(ProjectId, LocationId, SpecialistPoolId); 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 SpecialistPoolName); /// <inheritdoc/> public bool Equals(SpecialistPoolName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(SpecialistPoolName a, SpecialistPoolName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(SpecialistPoolName a, SpecialistPoolName b) => !(a == b); } public partial class SpecialistPool { /// <summary> /// <see cref="gcav::SpecialistPoolName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcav::SpecialistPoolName SpecialistPoolName { get => string.IsNullOrEmpty(Name) ? null : gcav::SpecialistPoolName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Compute.Tests.DiskRPTests; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Azure.Management.Storage.Models; using Microsoft.Azure.Test.HttpRecorder; using Microsoft.Rest.Azure; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; using Newtonsoft.Json; using Xunit; namespace Compute.Tests { public class GalleryTests : VMTestBase { protected const string ResourceGroupPrefix = "galleryPsTestRg"; protected const string GalleryNamePrefix = "galleryPsTestGallery"; protected const string GalleryImageNamePrefix = "galleryPsTestGalleryImage"; protected const string GalleryApplicationNamePrefix = "galleryPsTestGalleryApplication"; private string galleryHomeLocation = "eastus2"; [Fact] public void Gallery_CRUD_Tests() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); string rgName = ComputeManagementTestUtilities.GenerateName(ResourceGroupPrefix); string rgName2 = rgName + "New"; m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = galleryHomeLocation }); Trace.TraceInformation("Created the resource group: " + rgName); string galleryName = ComputeManagementTestUtilities.GenerateName(GalleryNamePrefix); Gallery galleryIn = GetTestInputGallery(); m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, galleryIn); Trace.TraceInformation(string.Format("Created the gallery: {0} in resource group: {1}", galleryName, rgName)); Gallery galleryOut = m_CrpClient.Galleries.Get(rgName, galleryName); Trace.TraceInformation("Got the gallery."); Assert.NotNull(galleryOut); ValidateGallery(galleryIn, galleryOut); galleryIn.Description = "This is an updated description"; m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, galleryIn); Trace.TraceInformation("Updated the gallery."); galleryOut = m_CrpClient.Galleries.Get(rgName, galleryName); ValidateGallery(galleryIn, galleryOut); Trace.TraceInformation("Listing galleries."); string galleryName2 = galleryName + "New"; m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName2, new ResourceGroup { Location = galleryHomeLocation }); Trace.TraceInformation("Created the resource group: " + rgName2); ComputeManagementTestUtilities.WaitSeconds(10); m_CrpClient.Galleries.CreateOrUpdate(rgName2, galleryName2, galleryIn); Trace.TraceInformation(string.Format("Created the gallery: {0} in resource group: {1}", galleryName2, rgName2)); IPage<Gallery> listGalleriesInRgResult = m_CrpClient.Galleries.ListByResourceGroup(rgName); Assert.Single(listGalleriesInRgResult); Assert.Null(listGalleriesInRgResult.NextPageLink); IPage<Gallery> listGalleriesInSubIdResult = m_CrpClient.Galleries.List(); // Below, >= instead of == is used because this subscription is shared in the group so other developers // might have created galleries in this subscription. Assert.True(listGalleriesInSubIdResult.Count() >= 2); Trace.TraceInformation("Deleting 2 galleries."); m_CrpClient.Galleries.Delete(rgName, galleryName); m_CrpClient.Galleries.Delete(rgName2, galleryName2); listGalleriesInRgResult = m_CrpClient.Galleries.ListByResourceGroup(rgName); Assert.Empty(listGalleriesInRgResult); // resource groups cleanup is taken cared by MockContext.Dispose() method. } } [Fact] public void GalleryImage_CRUD_Tests() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); string rgName = ComputeManagementTestUtilities.GenerateName(ResourceGroupPrefix); m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = galleryHomeLocation }); Trace.TraceInformation("Created the resource group: " + rgName); string galleryName = ComputeManagementTestUtilities.GenerateName(GalleryNamePrefix); Gallery gallery = GetTestInputGallery(); m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, gallery); Trace.TraceInformation(string.Format("Created the gallery: {0} in resource group: {1}", galleryName, rgName)); string galleryImageName = ComputeManagementTestUtilities.GenerateName(GalleryImageNamePrefix); GalleryImage inputGalleryImage = GetTestInputGalleryImage(); m_CrpClient.GalleryImages.CreateOrUpdate(rgName, galleryName, galleryImageName, inputGalleryImage); Trace.TraceInformation(string.Format("Created the gallery image: {0} in gallery: {1}", galleryImageName, galleryName)); GalleryImage galleryImageFromGet = m_CrpClient.GalleryImages.Get(rgName, galleryName, galleryImageName); Assert.NotNull(galleryImageFromGet); ValidateGalleryImage(inputGalleryImage, galleryImageFromGet); inputGalleryImage.Description = "Updated description."; m_CrpClient.GalleryImages.CreateOrUpdate(rgName, galleryName, galleryImageName, inputGalleryImage); Trace.TraceInformation(string.Format("Updated the gallery image: {0} in gallery: {1}", galleryImageName, galleryName)); galleryImageFromGet = m_CrpClient.GalleryImages.Get(rgName, galleryName, galleryImageName); Assert.NotNull(galleryImageFromGet); ValidateGalleryImage(inputGalleryImage, galleryImageFromGet); IPage<GalleryImage> listGalleryImagesResult = m_CrpClient.GalleryImages.ListByGallery(rgName, galleryName); Assert.Single(listGalleryImagesResult); Assert.Null(listGalleryImagesResult.NextPageLink); m_CrpClient.GalleryImages.Delete(rgName, galleryName, galleryImageName); listGalleryImagesResult = m_CrpClient.GalleryImages.ListByGallery(rgName, galleryName); Assert.Empty(listGalleryImagesResult); Trace.TraceInformation(string.Format("Deleted the gallery image: {0} in gallery: {1}", galleryImageName, galleryName)); m_CrpClient.Galleries.Delete(rgName, galleryName); } } [Fact] public void GalleryImageVersion_CRUD_Tests() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); using (MockContext context = MockContext.Start(this.GetType())) { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", galleryHomeLocation); EnsureClientsInitialized(context); string rgName = ComputeManagementTestUtilities.GenerateName(ResourceGroupPrefix); VirtualMachine vm = null; string imageName = ComputeManagementTestUtilities.GenerateName("psTestSourceImage"); try { string sourceImageId = ""; vm = CreateCRPImage(rgName, imageName, ref sourceImageId); Assert.False(string.IsNullOrEmpty(sourceImageId)); Trace.TraceInformation(string.Format("Created the source image id: {0}", sourceImageId)); string galleryName = ComputeManagementTestUtilities.GenerateName(GalleryNamePrefix); Gallery gallery = GetTestInputGallery(); m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, gallery); Trace.TraceInformation(string.Format("Created the gallery: {0} in resource group: {1}", galleryName, rgName)); string galleryImageName = ComputeManagementTestUtilities.GenerateName(GalleryImageNamePrefix); GalleryImage inputGalleryImage = GetTestInputGalleryImage(); m_CrpClient.GalleryImages.CreateOrUpdate(rgName, galleryName, galleryImageName, inputGalleryImage); Trace.TraceInformation(string.Format("Created the gallery image: {0} in gallery: {1}", galleryImageName, galleryName)); string galleryImageVersionName = "1.0.0"; GalleryImageVersion inputImageVersion = GetTestInputGalleryImageVersion(sourceImageId); m_CrpClient.GalleryImageVersions.CreateOrUpdate(rgName, galleryName, galleryImageName, galleryImageVersionName, inputImageVersion); Trace.TraceInformation(string.Format("Created the gallery image version: {0} in gallery image: {1}", galleryImageVersionName, galleryImageName)); GalleryImageVersion imageVersionFromGet = m_CrpClient.GalleryImageVersions.Get(rgName, galleryName, galleryImageName, galleryImageVersionName); Assert.NotNull(imageVersionFromGet); ValidateGalleryImageVersion(inputImageVersion, imageVersionFromGet); imageVersionFromGet = m_CrpClient.GalleryImageVersions.Get(rgName, galleryName, galleryImageName, galleryImageVersionName, ReplicationStatusTypes.ReplicationStatus); Assert.Equal(StorageAccountType.StandardLRS, imageVersionFromGet.PublishingProfile.StorageAccountType); Assert.Equal(StorageAccountType.StandardLRS, imageVersionFromGet.PublishingProfile.TargetRegions.First().StorageAccountType); Assert.NotNull(imageVersionFromGet.ReplicationStatus); Assert.NotNull(imageVersionFromGet.ReplicationStatus.Summary); inputImageVersion.PublishingProfile.EndOfLifeDate = DateTime.Now.AddDays(100).Date; m_CrpClient.GalleryImageVersions.CreateOrUpdate(rgName, galleryName, galleryImageName, galleryImageVersionName, inputImageVersion); Trace.TraceInformation(string.Format("Updated the gallery image version: {0} in gallery image: {1}", galleryImageVersionName, galleryImageName)); imageVersionFromGet = m_CrpClient.GalleryImageVersions.Get(rgName, galleryName, galleryImageName, galleryImageVersionName); Assert.NotNull(imageVersionFromGet); ValidateGalleryImageVersion(inputImageVersion, imageVersionFromGet); Trace.TraceInformation("Listing the gallery image versions"); IPage<GalleryImageVersion> listGalleryImageVersionsResult = m_CrpClient.GalleryImageVersions. ListByGalleryImage(rgName, galleryName, galleryImageName); Assert.Single(listGalleryImageVersionsResult); Assert.Null(listGalleryImageVersionsResult.NextPageLink); m_CrpClient.GalleryImageVersions.Delete(rgName, galleryName, galleryImageName, galleryImageVersionName); listGalleryImageVersionsResult = m_CrpClient.GalleryImageVersions. ListByGalleryImage(rgName, galleryName, galleryImageName); Assert.Empty(listGalleryImageVersionsResult); Assert.Null(listGalleryImageVersionsResult.NextPageLink); Trace.TraceInformation(string.Format("Deleted the gallery image version: {0} in gallery image: {1}", galleryImageVersionName, galleryImageName)); ComputeManagementTestUtilities.WaitMinutes(5); m_CrpClient.Images.Delete(rgName, imageName); Trace.TraceInformation("Deleted the CRP image."); m_CrpClient.VirtualMachines.Delete(rgName, vm.Name); Trace.TraceInformation("Deleted the virtual machine."); m_CrpClient.GalleryImages.Delete(rgName, galleryName, galleryImageName); Trace.TraceInformation("Deleted the gallery image."); m_CrpClient.Galleries.Delete(rgName, galleryName); Trace.TraceInformation("Deleted the gallery."); } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); if (vm != null) { m_CrpClient.VirtualMachines.Delete(rgName, vm.Name); } m_CrpClient.Images.Delete(rgName, imageName); } } } [Fact] public void GalleryApplication_CRUD_Tests() { using (MockContext context = MockContext.Start(this.GetType())) { string location = ComputeManagementTestUtilities.DefaultLocation; EnsureClientsInitialized(context); string rgName = ComputeManagementTestUtilities.GenerateName(ResourceGroupPrefix); m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = location }); Trace.TraceInformation("Created the resource group: " + rgName); string galleryName = ComputeManagementTestUtilities.GenerateName(GalleryNamePrefix); Gallery gallery = GetTestInputGallery(); gallery.Location = location; m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, gallery); Trace.TraceInformation(string.Format("Created the gallery: {0} in resource group: {1}", galleryName, rgName)); string galleryApplicationName = ComputeManagementTestUtilities.GenerateName(GalleryApplicationNamePrefix); GalleryApplication inputGalleryApplication = GetTestInputGalleryApplication(); m_CrpClient.GalleryApplications.CreateOrUpdate(rgName, galleryName, galleryApplicationName, inputGalleryApplication); Trace.TraceInformation(string.Format("Created the gallery application: {0} in gallery: {1}", galleryApplicationName, galleryName)); GalleryApplication galleryApplicationFromGet = m_CrpClient.GalleryApplications.Get(rgName, galleryName, galleryApplicationName); Assert.NotNull(galleryApplicationFromGet); ValidateGalleryApplication(inputGalleryApplication, galleryApplicationFromGet); inputGalleryApplication.Description = "Updated description."; m_CrpClient.GalleryApplications.CreateOrUpdate(rgName, galleryName, galleryApplicationName, inputGalleryApplication); Trace.TraceInformation(string.Format("Updated the gallery application: {0} in gallery: {1}", galleryApplicationName, galleryName)); galleryApplicationFromGet = m_CrpClient.GalleryApplications.Get(rgName, galleryName, galleryApplicationName); Assert.NotNull(galleryApplicationFromGet); ValidateGalleryApplication(inputGalleryApplication, galleryApplicationFromGet); m_CrpClient.GalleryApplications.Delete(rgName, galleryName, galleryApplicationName); Trace.TraceInformation(string.Format("Deleted the gallery application: {0} in gallery: {1}", galleryApplicationName, galleryName)); m_CrpClient.Galleries.Delete(rgName, galleryName); } } [Fact] public void GalleryApplicationVersion_CRUD_Tests() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); using (MockContext context = MockContext.Start(this.GetType())) { string location = ComputeManagementTestUtilities.DefaultLocation; Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", location); EnsureClientsInitialized(context); string rgName = ComputeManagementTestUtilities.GenerateName(ResourceGroupPrefix); string applicationName = ComputeManagementTestUtilities.GenerateName("psTestSourceApplication"); string galleryName = ComputeManagementTestUtilities.GenerateName(GalleryNamePrefix); string galleryApplicationName = ComputeManagementTestUtilities.GenerateName(GalleryApplicationNamePrefix); string galleryApplicationVersionName = "1.0.0"; try { string applicationMediaLink = CreateApplicationMediaLink(rgName, "test.txt"); Assert.False(string.IsNullOrEmpty(applicationMediaLink)); Trace.TraceInformation(string.Format("Created the source application media link: {0}", applicationMediaLink)); Gallery gallery = GetTestInputGallery(); gallery.Location = location; m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, gallery); Trace.TraceInformation(string.Format("Created the gallery: {0} in resource group: {1}", galleryName, rgName)); GalleryApplication inputGalleryApplication = GetTestInputGalleryApplication(); m_CrpClient.GalleryApplications.CreateOrUpdate(rgName, galleryName, galleryApplicationName, inputGalleryApplication); Trace.TraceInformation(string.Format("Created the gallery application: {0} in gallery: {1}", galleryApplicationName, galleryName)); GalleryApplicationVersion inputApplicationVersion = GetTestInputGalleryApplicationVersion(applicationMediaLink); m_CrpClient.GalleryApplicationVersions.CreateOrUpdate(rgName, galleryName, galleryApplicationName, galleryApplicationVersionName, inputApplicationVersion); Trace.TraceInformation(string.Format("Created the gallery application version: {0} in gallery application: {1}", galleryApplicationVersionName, galleryApplicationName)); GalleryApplicationVersion applicationVersionFromGet = m_CrpClient.GalleryApplicationVersions.Get(rgName, galleryName, galleryApplicationName, galleryApplicationVersionName); Assert.NotNull(applicationVersionFromGet); ValidateGalleryApplicationVersion(inputApplicationVersion, applicationVersionFromGet); applicationVersionFromGet = m_CrpClient.GalleryApplicationVersions.Get(rgName, galleryName, galleryApplicationName, galleryApplicationVersionName, ReplicationStatusTypes.ReplicationStatus); Assert.Equal(StorageAccountType.StandardLRS, applicationVersionFromGet.PublishingProfile.StorageAccountType); Assert.Equal(StorageAccountType.StandardLRS, applicationVersionFromGet.PublishingProfile.TargetRegions.First().StorageAccountType); Assert.NotNull(applicationVersionFromGet.ReplicationStatus); Assert.NotNull(applicationVersionFromGet.ReplicationStatus.Summary); inputApplicationVersion.PublishingProfile.EndOfLifeDate = DateTime.Now.AddDays(100).Date; m_CrpClient.GalleryApplicationVersions.CreateOrUpdate(rgName, galleryName, galleryApplicationName, galleryApplicationVersionName, inputApplicationVersion); Trace.TraceInformation(string.Format("Updated the gallery application version: {0} in gallery application: {1}", galleryApplicationVersionName, galleryApplicationName)); applicationVersionFromGet = m_CrpClient.GalleryApplicationVersions.Get(rgName, galleryName, galleryApplicationName, galleryApplicationVersionName); Assert.NotNull(applicationVersionFromGet); ValidateGalleryApplicationVersion(inputApplicationVersion, applicationVersionFromGet); m_CrpClient.GalleryApplicationVersions.Delete(rgName, galleryName, galleryApplicationName, galleryApplicationVersionName); Trace.TraceInformation(string.Format("Deleted the gallery application version: {0} in gallery application: {1}", galleryApplicationVersionName, galleryApplicationName)); ComputeManagementTestUtilities.WaitSeconds(300); m_CrpClient.GalleryApplications.Delete(rgName, galleryName, galleryApplicationName); Trace.TraceInformation("Deleted the gallery application."); m_CrpClient.Galleries.Delete(rgName, galleryName); Trace.TraceInformation("Deleted the gallery."); } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } } [Fact] public void Gallery_SharingToSubscriptionAndTenant_CRUD_Tests() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); string rgName = ComputeManagementTestUtilities.GenerateName(ResourceGroupPrefix); try { m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = galleryHomeLocation }); Trace.TraceInformation("Created the resource group: " + rgName); string galleryName = ComputeManagementTestUtilities.GenerateName(GalleryNamePrefix); Gallery galleryIn = GetTestInputSharedGallery(); m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, galleryIn); Trace.TraceInformation(string.Format("Created the shared gallery: {0} in resource group: {1} with sharing profile permission: {2}", galleryName, rgName, galleryIn.SharingProfile.Permissions)); Gallery galleryOut = m_CrpClient.Galleries.Get(rgName, galleryName); Trace.TraceInformation("Got the gallery."); Assert.NotNull(galleryOut); ValidateGallery(galleryIn, galleryOut); Assert.Equal("Groups", galleryOut.SharingProfile.Permissions); Trace.TraceInformation("Update the sharing profile via post, add the sharing profile groups."); string newTenantId = "583d66a9-0041-4999-8838-75baece101d5"; SharingProfileGroup tenantGroups = new SharingProfileGroup() { Type = "AADTenants", Ids = new List<string> { newTenantId } }; string newSubId = "640c5810-13bf-4b82-b94d-f38c2565e3bc"; SharingProfileGroup subGroups = new SharingProfileGroup() { Type = "Subscriptions", Ids = new List<string> { newSubId } }; List<SharingProfileGroup> groups = new List<SharingProfileGroup> { tenantGroups, subGroups }; SharingUpdate sharingUpdate = new SharingUpdate() { OperationType = SharingUpdateOperationTypes.Add, Groups = groups }; m_CrpClient.GallerySharingProfile.Update(rgName, galleryName, sharingUpdate); Gallery galleryOutWithSharingProfile = m_CrpClient.Galleries.Get(rgName, galleryName, SelectPermissions.Permissions); Trace.TraceInformation("Got the gallery"); Assert.NotNull(galleryOutWithSharingProfile); ValidateSharingProfile(galleryIn, galleryOutWithSharingProfile, groups); Trace.TraceInformation("Reset this gallery to private before deleting it."); SharingUpdate resetPrivateUpdate = new SharingUpdate() { OperationType = SharingUpdateOperationTypes.Reset, Groups = null }; m_CrpClient.GallerySharingProfile.Update(rgName, galleryName, resetPrivateUpdate); Trace.TraceInformation("Deleting this gallery."); m_CrpClient.Galleries.Delete(rgName, galleryName); } finally { m_ResourcesClient.ResourceGroups.Delete(rgName); } // resource groups cleanup is taken cared by MockContext.Dispose() method. } } [Fact] public void Gallery_SharingToCommunity_CRUD_Tests() { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); string rgName = ComputeManagementTestUtilities.GenerateName(ResourceGroupPrefix); try { m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = galleryHomeLocation }); Trace.TraceInformation("Created the resource group: " + rgName); string galleryName = ComputeManagementTestUtilities.GenerateName(GalleryNamePrefix); Gallery galleryIn = GetTestInputCommunityGallery(); m_CrpClient.Galleries.CreateOrUpdate(rgName, galleryName, galleryIn); Trace.TraceInformation(string.Format("Created the community gallery: {0} in resource group: {1} with sharing profile permission: {2}", galleryName, rgName, galleryIn.SharingProfile.Permissions)); Gallery galleryOut = m_CrpClient.Galleries.Get(rgName, galleryName); Trace.TraceInformation("Got the gallery."); Assert.NotNull(galleryOut); ValidateGallery(galleryIn, galleryOut); Assert.NotNull(galleryOut.SharingProfile); Assert.NotNull(galleryOut.SharingProfile.CommunityGalleryInfo); Assert.Equal("Community", galleryOut.SharingProfile.Permissions); Trace.TraceInformation("Enable sharing to the public via post"); SharingUpdate sharingUpdate = new SharingUpdate() { OperationType = SharingUpdateOperationTypes.EnableCommunity }; m_CrpClient.GallerySharingProfile.Update(rgName, galleryName, sharingUpdate); Gallery galleryOutWithSharingProfile = m_CrpClient.Galleries.Get(rgName, galleryName, SelectPermissions.Permissions); Trace.TraceInformation("Got the gallery"); Assert.NotNull(galleryOutWithSharingProfile); CommunityGalleryInfo communityGalleryInfo = JsonConvert.DeserializeObject<CommunityGalleryInfo>(galleryOutWithSharingProfile.SharingProfile.CommunityGalleryInfo.ToString()); Assert.True(communityGalleryInfo.CommunityGalleryEnabled); Trace.TraceInformation("Reset this gallery to private before deleting it."); SharingUpdate resetPrivateUpdate = new SharingUpdate() { OperationType = SharingUpdateOperationTypes.Reset }; m_CrpClient.GallerySharingProfile.Update(rgName, galleryName, resetPrivateUpdate); Trace.TraceInformation("Deleting this gallery."); m_CrpClient.Galleries.Delete(rgName, galleryName); } finally { m_ResourcesClient.ResourceGroups.Delete(rgName); } // resource groups cleanup is taken cared by MockContext.Dispose() method. } } private void ValidateGallery(Gallery galleryIn, Gallery galleryOut) { Assert.False(string.IsNullOrEmpty(galleryOut.ProvisioningState)); if (galleryIn.Tags != null) { foreach (KeyValuePair<string, string> kvp in galleryIn.Tags) { Assert.Equal(kvp.Value, galleryOut.Tags[kvp.Key]); } } if (!string.IsNullOrEmpty(galleryIn.Description)) { Assert.Equal(galleryIn.Description, galleryOut.Description); } Assert.False(string.IsNullOrEmpty(galleryOut?.Identifier?.UniqueName)); } private void ValidateSharingProfile(Gallery galleryIn, Gallery galleryOut, List<SharingProfileGroup> groups) { if(galleryIn.SharingProfile != null) { Assert.Equal(galleryIn.SharingProfile.Permissions, galleryOut.SharingProfile.Permissions); Assert.Equal(groups.Count, galleryOut.SharingProfile.Groups.Count); foreach (SharingProfileGroup sharingProfileGroup in galleryOut.SharingProfile.Groups) { if (sharingProfileGroup.Ids != null) { List<string> outIds = sharingProfileGroup.Ids as List<string>; List<string> inIds = null; foreach(SharingProfileGroup inGroup in groups) { if(inGroup.Type == sharingProfileGroup.Type) { inIds = inGroup.Ids as List<string>; break; } } Assert.NotNull(inIds); Assert.Equal(inIds.Count, outIds.Count); for(int i = 0; i < inIds.Count; i++) { Assert.Equal(outIds[i], inIds[i]); } } } } } private void ValidateGalleryImage(GalleryImage imageIn, GalleryImage imageOut) { Assert.False(string.IsNullOrEmpty(imageOut.ProvisioningState)); if (imageIn.Tags != null) { foreach (KeyValuePair<string, string> kvp in imageIn.Tags) { Assert.Equal(kvp.Value, imageOut.Tags[kvp.Key]); } } Assert.Equal(imageIn.Identifier.Publisher, imageOut.Identifier.Publisher); Assert.Equal(imageIn.Identifier.Offer, imageOut.Identifier.Offer); Assert.Equal(imageIn.Identifier.Sku, imageOut.Identifier.Sku); Assert.Equal(imageIn.Location, imageOut.Location); Assert.Equal(imageIn.OsState, imageOut.OsState); Assert.Equal(imageIn.OsType, imageOut.OsType); if (imageIn.HyperVGeneration == null) { Assert.Equal(HyperVGenerationType.V1, imageOut.HyperVGeneration); } else { Assert.Equal(imageIn.HyperVGeneration, imageOut.HyperVGeneration); } if (!string.IsNullOrEmpty(imageIn.Description)) { Assert.Equal(imageIn.Description, imageOut.Description); } } private void ValidateGalleryImageVersion(GalleryImageVersion imageVersionIn, GalleryImageVersion imageVersionOut) { Assert.False(string.IsNullOrEmpty(imageVersionOut.ProvisioningState)); if (imageVersionIn.Tags != null) { foreach (KeyValuePair<string, string> kvp in imageVersionIn.Tags) { Assert.Equal(kvp.Value, imageVersionOut.Tags[kvp.Key]); } } Assert.Equal(imageVersionIn.Location, imageVersionOut.Location); Assert.False(string.IsNullOrEmpty(imageVersionOut.StorageProfile.Source.Id), "imageVersionOut.PublishingProfile.Source.ManagedImage.Id is null or empty."); Assert.NotNull(imageVersionOut.PublishingProfile.EndOfLifeDate); Assert.NotNull(imageVersionOut.PublishingProfile.PublishedDate); Assert.NotNull(imageVersionOut.StorageProfile); } private Gallery GetTestInputGallery() { return new Gallery { Location = galleryHomeLocation, Description = "This is a sample gallery description" }; } private Gallery GetTestInputSharedGallery() { return new Gallery { Location = galleryHomeLocation, Description = "This is a sample gallery description", SharingProfile = new SharingProfile { Permissions = "Groups" } }; } private Gallery GetTestInputCommunityGallery() { return new Gallery { Location = galleryHomeLocation, Description = "This is a sample gallery description", SharingProfile = new SharingProfile { Permissions = "Community", CommunityGalleryInfo = new CommunityGalleryInfo() { PublicNamePrefix = "PsTestCg", Eula = "PsEual", PublisherUri = "PsTestUri", PublisherContact = "SIG@microsoft.com" } } }; } private GalleryImage GetTestInputGalleryImage() { return new GalleryImage { Identifier = new GalleryImageIdentifier { Publisher = "testPub", Offer = "testOffer", Sku = "testSku" }, Location = galleryHomeLocation, OsState = OperatingSystemStateTypes.Generalized, OsType = OperatingSystemTypes.Windows, Description = "This is the gallery image description.", HyperVGeneration = null }; } private GalleryImageVersion GetTestInputGalleryImageVersion(string sourceImageId) { return new GalleryImageVersion { Location = galleryHomeLocation, PublishingProfile = new GalleryImageVersionPublishingProfile { ReplicaCount = 1, StorageAccountType = StorageAccountType.StandardLRS, TargetRegions = new List<TargetRegion> { new TargetRegion { Name = galleryHomeLocation, RegionalReplicaCount = 1, StorageAccountType = StorageAccountType.StandardLRS } }, EndOfLifeDate = DateTime.Today.AddDays(10).Date }, StorageProfile = new GalleryImageVersionStorageProfile { Source = new GalleryArtifactVersionSource { Id = sourceImageId } } }; } private VirtualMachine CreateCRPImage(string rgName, string imageName, ref string sourceImageId) { string storageAccountName = ComputeManagementTestUtilities.GenerateName("saforgallery"); string asName = ComputeManagementTestUtilities.GenerateName("asforgallery"); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); StorageAccount storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); // resource group is also created in this method. VirtualMachine inputVM = null; VirtualMachine createdVM = CreateVM(rgName, asName, storageAccountOutput, imageRef, out inputVM); Image imageInput = new Image() { Location = m_location, Tags = new Dictionary<string, string>() { {"RG", "rg"}, {"testTag", "1"}, }, StorageProfile = new ImageStorageProfile() { OsDisk = new ImageOSDisk() { BlobUri = createdVM.StorageProfile.OsDisk.Vhd.Uri, OsState = OperatingSystemStateTypes.Generalized, OsType = OperatingSystemTypes.Windows, }, ZoneResilient = true }, HyperVGeneration = HyperVGenerationTypes.V1 }; m_CrpClient.Images.CreateOrUpdate(rgName, imageName, imageInput); Image getImage = m_CrpClient.Images.Get(rgName, imageName); sourceImageId = getImage.Id; return createdVM; } private string CreateApplicationMediaLink(string rgName, string fileName) { string storageAccountName = ComputeManagementTestUtilities.GenerateName("saforgallery"); string asName = ComputeManagementTestUtilities.GenerateName("asforgallery"); StorageAccount storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); // resource group is also created in this method. string applicationMediaLink = @"https://saforgallery1969.blob.core.windows.net/sascontainer/test.txt\"; if (HttpMockServer.Mode == HttpRecorderMode.Record) { var accountKeyResult = m_SrpClient.StorageAccounts.ListKeysWithHttpMessagesAsync(rgName, storageAccountName).Result; CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(storageAccountName, accountKeyResult.Body.Key1), useHttps: true); var blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("sascontainer"); bool created = container.CreateIfNotExistsAsync().Result; CloudPageBlob pageBlob = container.GetPageBlobReference(fileName); byte[] blobContent = Encoding.UTF8.GetBytes("Application Package Test"); byte[] bytes = new byte[512]; // Page blob must be multiple of 512 System.Buffer.BlockCopy(blobContent, 0, bytes, 0, blobContent.Length); pageBlob.UploadFromByteArrayAsync(bytes, 0, bytes.Length); SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy(); sasConstraints.SharedAccessStartTime = DateTime.UtcNow.AddDays(-1); sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddDays(2); sasConstraints.Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write; //Generate the shared access signature on the blob, setting the constraints directly on the signature. string sasContainerToken = pageBlob.GetSharedAccessSignature(sasConstraints); //Return the URI string for the container, including the SAS token. applicationMediaLink = pageBlob.Uri + sasContainerToken; } return applicationMediaLink; } private GalleryApplication GetTestInputGalleryApplication() { return new GalleryApplication { Eula = "This is the gallery application EULA.", Location = ComputeManagementTestUtilities.DefaultLocation, SupportedOSType = OperatingSystemTypes.Windows, PrivacyStatementUri = "www.privacystatement.com", ReleaseNoteUri = "www.releasenote.com", Description = "This is the gallery application description.", }; } private GalleryApplicationVersion GetTestInputGalleryApplicationVersion(string applicationMediaLink) { return new GalleryApplicationVersion { Location = ComputeManagementTestUtilities.DefaultLocation, PublishingProfile = new GalleryApplicationVersionPublishingProfile { Source = new UserArtifactSource { MediaLink = applicationMediaLink }, ManageActions = new UserArtifactManage { Install = "powershell -command \"Expand-Archive -Path test.zip -DestinationPath C:\\package\"", Remove = "del C:\\package " }, ReplicaCount = 1, StorageAccountType = StorageAccountType.StandardLRS, TargetRegions = new List<TargetRegion> { new TargetRegion { Name = ComputeManagementTestUtilities.DefaultLocation, RegionalReplicaCount = 1, StorageAccountType = StorageAccountType.StandardLRS } }, EndOfLifeDate = DateTime.Today.AddDays(10).Date } }; } private void ValidateGalleryApplication(GalleryApplication applicationIn, GalleryApplication applicationOut) { if (applicationIn.Tags != null) { foreach (KeyValuePair<string, string> kvp in applicationIn.Tags) { Assert.Equal(kvp.Value, applicationOut.Tags[kvp.Key]); } } Assert.Equal(applicationIn.Eula, applicationOut.Eula); Assert.Equal(applicationIn.PrivacyStatementUri, applicationOut.PrivacyStatementUri); Assert.Equal(applicationIn.ReleaseNoteUri, applicationOut.ReleaseNoteUri); Assert.Equal(applicationIn.Location.ToLower(), applicationOut.Location.ToLower()); Assert.Equal(applicationIn.SupportedOSType, applicationOut.SupportedOSType); if (!string.IsNullOrEmpty(applicationIn.Description)) { Assert.Equal(applicationIn.Description, applicationOut.Description); } } private void ValidateGalleryApplicationVersion(GalleryApplicationVersion applicationVersionIn, GalleryApplicationVersion applicationVersionOut) { Assert.False(string.IsNullOrEmpty(applicationVersionOut.ProvisioningState)); if (applicationVersionIn.Tags != null) { foreach (KeyValuePair<string, string> kvp in applicationVersionIn.Tags) { Assert.Equal(kvp.Value, applicationVersionOut.Tags[kvp.Key]); } } Assert.Equal(applicationVersionIn.Location.ToLower(), applicationVersionOut.Location.ToLower()); Assert.False(string.IsNullOrEmpty(applicationVersionOut.PublishingProfile.Source.MediaLink), "applicationVersionOut.PublishingProfile.Source.MediaLink is null or empty."); Assert.NotNull(applicationVersionOut.PublishingProfile.EndOfLifeDate); Assert.NotNull(applicationVersionOut.PublishingProfile.PublishedDate); Assert.NotNull(applicationVersionOut.Id); } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Xml; using System.Xml.Linq; using NUnit.Framework; using SIL.Keyboarding; using SIL.TestUtilities; namespace SIL.WritingSystems.Tests { [TestFixture] public class LdmlInFolderWritingSystemRepositoryInterfaceTests : WritingSystemRepositoryTests { private List<string> _testPaths; [SetUp] public override void SetUp() { _testPaths = new List<string>(); base.SetUp(); } [TearDown] public override void TearDown() { base.TearDown(); foreach (string testPath in _testPaths) { if (Directory.Exists(testPath)) { Directory.Delete(testPath, true); } } } public override IWritingSystemRepository CreateNewStore() { string testPath = Path.GetTempPath() + "PalasoTest" + _testPaths.Count; if (Directory.Exists(testPath)) { Directory.Delete(testPath, true); } _testPaths.Add(testPath); LdmlInFolderWritingSystemRepository repository = LdmlInFolderWritingSystemRepository.Initialize(testPath); //repository.DontAddDefaultDefinitions = true; return repository; } } [TestFixture] public class LdmlInFolderWritingSystemRepositoryTests { private class TestEnvironment : IDisposable { private readonly TemporaryFolder _localRepoFolder; private readonly WritingSystemDefinition _writingSystem; private readonly TemporaryFolder _templateFolder; private readonly TemporaryFolder _globalRepoFolder; private readonly TestWritingSystemCustomDataMapper _writingSystemCustomDataMapper; public TestEnvironment() { _localRepoFolder = new TemporaryFolder("LdmlInFolderWritingSystemRepositoryTests"); _templateFolder = new TemporaryFolder("Templates"); _globalRepoFolder = new TemporaryFolder("GlobalWritingSystemRepository"); _writingSystem = new WritingSystemDefinition(); _writingSystemCustomDataMapper = new TestWritingSystemCustomDataMapper(); ResetRepositories(); } public void ResetRepositories() { if (GlobalRepository != null) GlobalRepository.Dispose(); GlobalRepository = new GlobalWritingSystemRepository(_globalRepoFolder.Path); LocalRepository = new TestLdmlInFolderWritingSystemRepository(_localRepoFolder.Path, new[] {_writingSystemCustomDataMapper}, GlobalRepository); LocalRepository.WritingSystemFactory.TemplateFolder = _templateFolder.Path; } public void Dispose() { GlobalRepository.Dispose(); _globalRepoFolder.Dispose(); _templateFolder.Dispose(); _localRepoFolder.Dispose(); } public TestLdmlInFolderWritingSystemRepository LocalRepository { get; private set; } public GlobalWritingSystemRepository GlobalRepository { get; private set; } public string LocalRepositoryPath { get { return _localRepoFolder.Path; } } public WritingSystemDefinition WritingSystem { get { return _writingSystem; } } public string GetPathForLocalWSId(string id) { string path = Path.Combine(_localRepoFolder.Path, id + ".ldml"); return path; } public string GetPathForGlobalWSId(string id) { string path = Path.Combine(GlobalWritingSystemRepository.CurrentVersionPath(_globalRepoFolder.Path), id + ".ldml"); return path; } public void AssertWritingSystemFileExists(string id) { Assert.IsTrue(File.Exists(GetPathForLocalWSId(id))); } } [Test] public void LatestVersion_IsThree() { Assert.AreEqual(3, LdmlDataMapper.CurrentLdmlVersion); } [Test] public void PathToCollection_SameAsGiven() { using (var environment = new TestEnvironment()) { Assert.AreEqual(environment.LocalRepositoryPath, environment.LocalRepository.PathToWritingSystems); } } [Test] public void SaveDefinitionsThenLoad_CountEquals2() { using (var environment = new TestEnvironment()) { environment.WritingSystem.Language = "one"; environment.LocalRepository.SaveDefinition(environment.WritingSystem); var ws2 = new WritingSystemDefinition { Language = "two" }; environment.LocalRepository.SaveDefinition(ws2); environment.ResetRepositories(); Assert.AreEqual(2, environment.LocalRepository.Count); } } [Test] public void SavesWhenNotPreexisting() { using (var environment = new TestEnvironment()) { environment.LocalRepository.SaveDefinition(environment.WritingSystem); environment.AssertWritingSystemFileExists(environment.WritingSystem.LanguageTag); } } [Test] public void SavesWhenPreexisting() { using (var environment = new TestEnvironment()) { environment.WritingSystem.Language = "en"; environment.LocalRepository.SaveDefinition(environment.WritingSystem); environment.LocalRepository.SaveDefinition(environment.WritingSystem); var ws2 = new WritingSystemDefinition(); environment.WritingSystem.Language = "en"; environment.LocalRepository.SaveDefinition(ws2); } } [Test] public void RegressionWhereUnchangedDefDeleted() { using (var environment = new TestEnvironment()) { environment.WritingSystem.Language = "qaa"; environment.LocalRepository.SaveDefinition(environment.WritingSystem); var ws2 = environment.LocalRepository.Get(environment.WritingSystem.Id); environment.LocalRepository.SaveDefinition(ws2); environment.AssertWritingSystemFileExists(environment.WritingSystem.LanguageTag); } } [Test] public void SavesWhenDirectoryNotFound() { using (var environment = new TestEnvironment()) { string newRepoPath = Path.Combine(environment.LocalRepositoryPath, "newguy"); var newRepository = new LdmlInFolderWritingSystemRepository(newRepoPath); newRepository.SaveDefinition(environment.WritingSystem); Assert.That(File.Exists(Path.Combine(newRepoPath, environment.WritingSystem.LanguageTag + ".ldml"))); } } [Test] public void Save_WritingSystemIdChanged_ChangeLogUpdated() { using (var e = new TestEnvironment()) { LdmlInFolderWritingSystemRepository repo = LdmlInFolderWritingSystemRepository.Initialize(Path.Combine(e.LocalRepositoryPath, "idchangedtest1")); var ws = new WritingSystemDefinition("en"); repo.Set(ws); repo.Save(); ws.Script = "Latn"; repo.Set(ws); ws.Script = "Thai"; repo.Set(ws); var ws2 = new WritingSystemDefinition("de"); repo.Set(ws2); ws2.Script = "Latn"; repo.Save(); string logFilePath = Path.Combine(repo.PathToWritingSystems, "idchangelog.xml"); AssertThatXmlIn.File(logFilePath).HasAtLeastOneMatchForXpath("/WritingSystemChangeLog/Changes/Change/From[text()='en']"); AssertThatXmlIn.File(logFilePath).HasAtLeastOneMatchForXpath("/WritingSystemChangeLog/Changes/Change/To[text()='en-Thai']"); // writing systems added for the first time shouldn't be in the log as a change AssertThatXmlIn.File(logFilePath).HasNoMatchForXpath("/WritingSystemChangeLog/Changes/Change/From[text()='de']"); } } [Test] public void Save_WritingSystemIdConflated_ChangeLogUpdatedAndDoesNotContainDelete() { using (var e = new TestEnvironment()) { LdmlInFolderWritingSystemRepository repo = LdmlInFolderWritingSystemRepository.Initialize(Path.Combine(e.LocalRepositoryPath, "idchangedtest1")); var ws = new WritingSystemDefinition("en"); repo.Set(ws); repo.Save(); var ws2 = new WritingSystemDefinition("de"); repo.Set(ws2); repo.Save(); repo.Conflate(ws.Id, ws2.Id); repo.Save(); string logFilePath = Path.Combine(repo.PathToWritingSystems, "idchangelog.xml"); AssertThatXmlIn.File(logFilePath).HasAtLeastOneMatchForXpath("/WritingSystemChangeLog/Changes/Merge/From[text()='en']"); AssertThatXmlIn.File(logFilePath).HasAtLeastOneMatchForXpath("/WritingSystemChangeLog/Changes/Merge/To[text()='de']"); AssertThatXmlIn.File(logFilePath).HasNoMatchForXpath("/WritingSystemChangeLog/Changes/Delete/Id[text()='en']"); } } [Test] public void IdAfterSave_SameAsFileNameWithoutExtension() { using (var environment = new TestEnvironment()) { environment.WritingSystem.Language = "en"; environment.LocalRepository.SaveDefinition(environment.WritingSystem); Assert.AreEqual("en", environment.WritingSystem.Id); } } [Test] public void IdAfterLoad_SameAsFileNameWithoutExtension() { using (var environment = new TestEnvironment()) { environment.WritingSystem.Language = "en"; Assert.AreNotEqual(0, Directory.GetFiles(environment.LocalRepositoryPath, "*.ldml")); environment.LocalRepository.SaveDefinition(environment.WritingSystem); environment.ResetRepositories(); WritingSystemDefinition ws2 = environment.LocalRepository.Get("en"); Assert.AreEqual( Path.GetFileNameWithoutExtension(Directory.GetFiles(environment.LocalRepositoryPath, "*.ldml")[0]), ws2.Id); } } [Test] public void UpdatesFileNameWhenIsoChanges() { using (var environment = new TestEnvironment()) { environment.WritingSystem.Language = "en"; environment.LocalRepository.SaveDefinition(environment.WritingSystem); string path = Path.Combine(environment.LocalRepository.PathToWritingSystems, "en.ldml"); Assert.IsTrue(File.Exists(path)); var ws2 = environment.LocalRepository.Get(environment.WritingSystem.LanguageTag); ws2.Language = "de"; Assert.AreEqual("en", ws2.Id); environment.LocalRepository.SaveDefinition(ws2); Assert.AreEqual("de", ws2.Id); Assert.IsFalse(File.Exists(path)); path = Path.Combine(environment.LocalRepository.PathToWritingSystems, "de.ldml"); Assert.IsTrue(File.Exists(path)); } } [Test] public void MakesNewFileIfNeeded() { using (var environment = new TestEnvironment()) { environment.WritingSystem.Language = "en"; environment.LocalRepository.SaveDefinition(environment.WritingSystem); AssertThatXmlIn.File(environment.GetPathForLocalWSId(environment.WritingSystem.LanguageTag)).HasAtLeastOneMatchForXpath("ldml/identity/language[@type='en']"); } } [Test] public void CanAddVariantToLdmlUsingSameWS() { using (var environment = new TestEnvironment()) { environment.LocalRepository.SaveDefinition(environment.WritingSystem); environment.WritingSystem.Variants.Add("1901"); environment.LocalRepository.SaveDefinition(environment.WritingSystem); AssertThatXmlIn.File(environment.GetPathForLocalWSId(environment.WritingSystem.LanguageTag)).HasAtLeastOneMatchForXpath("ldml/identity/variant[@type='1901']"); } } [Test] public void CanAddVariantToExistingLdml() { using (var environment = new TestEnvironment()) { environment.WritingSystem.Language = "en"; environment.WritingSystem.Script = "Latn"; environment.WritingSystem.WindowsLcid = "12345"; environment.LocalRepository.SaveDefinition(environment.WritingSystem); environment.ResetRepositories(); WritingSystemDefinition ws2 = environment.LocalRepository.Get(environment.WritingSystem.Id); ws2.Variants.Add("piglatin"); environment.LocalRepository.SaveDefinition(ws2); string path = Path.Combine(environment.LocalRepository.PathToWritingSystems, environment.GetPathForLocalWSId(ws2.LanguageTag)); AssertThatXmlIn.File(path).HasAtLeastOneMatchForXpath("ldml/identity/variant[@type='x-piglatin']"); var manager = new XmlNamespaceManager(new NameTable()); manager.AddNamespace("sil", "urn://www.sil.org/ldml/0.1"); AssertThatXmlIn.File(path).HasAtLeastOneMatchForXpath("ldml/identity/special/sil:identity[@windowsLCID='12345']", manager); } } [Test] public void CanReadVariant() { using (var environment = new TestEnvironment()) { environment.WritingSystem.Language = "en"; environment.WritingSystem.Variants.Add("piglatin"); environment.LocalRepository.SaveDefinition(environment.WritingSystem); environment.ResetRepositories(); WritingSystemDefinition ws2 = environment.LocalRepository.Get(environment.WritingSystem.Id); Assert.That(ws2.Variants, Is.EqualTo(new VariantSubtag[] {"piglatin"})); } } [Test] public void CanSaveAndReadKeyboardId() { using (var environment = new TestEnvironment()) { environment.WritingSystem.Language = "en"; var kbd1 = new DefaultKeyboardDefinition("Thai", "Thai"); kbd1.Format = KeyboardFormat.Msklc; environment.WritingSystem.KnownKeyboards.Add(kbd1); environment.LocalRepository.SaveDefinition(environment.WritingSystem); environment.ResetRepositories(); WritingSystemDefinition ws2 = environment.LocalRepository.Get("en"); Assert.AreEqual("Thai", ws2.KnownKeyboards[0].Id); } } [Test] public void CanSaveAndReadRightToLeft() { using (var environment = new TestEnvironment()) { environment.WritingSystem.Language = "en"; Assert.IsFalse(environment.WritingSystem.RightToLeftScript); environment.WritingSystem.RightToLeftScript = true; Assert.IsTrue(environment.WritingSystem.RightToLeftScript); environment.LocalRepository.SaveDefinition(environment.WritingSystem); environment.ResetRepositories(); WritingSystemDefinition ws2 = environment.LocalRepository.Get("en"); Assert.IsTrue(ws2.RightToLeftScript); } } [Test] public void CanRemoveVariant() { using (var environment = new TestEnvironment()) { environment.WritingSystem.Language = "en"; environment.WritingSystem.Variants.Add("piglatin"); environment.LocalRepository.SaveDefinition(environment.WritingSystem); string path = environment.GetPathForLocalWSId(environment.WritingSystem.LanguageTag); AssertThatXmlIn.File(path).HasAtLeastOneMatchForXpath("ldml/identity/variant"); environment.WritingSystem.Variants.Clear(); environment.LocalRepository.SaveDefinition(environment.WritingSystem); AssertThatXmlIn.File(environment.GetPathForLocalWSId(environment.WritingSystem.LanguageTag)).HasNoMatchForXpath("ldml/identity/variant"); } } [Test] public void CanDeleteFileThatIsNotInTrash() { using (var environment = new TestEnvironment()) { environment.WritingSystem.Language = "en"; environment.LocalRepository.SaveDefinition(environment.WritingSystem); string path = Path.Combine(environment.LocalRepository.PathToWritingSystems, environment.GetPathForLocalWSId(environment.WritingSystem.LanguageTag)); Assert.IsTrue(File.Exists(path)); environment.LocalRepository.Remove(environment.WritingSystem.Language); Assert.IsFalse(File.Exists(path)); AssertFileIsInTrash(environment); } } private static void AssertFileIsInTrash(TestEnvironment environment) { string path = Path.Combine(environment.LocalRepository.PathToWritingSystems, "trash"); path = Path.Combine(path,environment.WritingSystem.LanguageTag + ".ldml"); Assert.IsTrue(File.Exists(path)); } [Test] public void CanDeleteFileMatchingOneThatWasPreviouslyTrashed() { using (var environment = new TestEnvironment()) { environment.WritingSystem.Language = "en"; environment.LocalRepository.SaveDefinition(environment.WritingSystem); environment.LocalRepository.Remove(environment.WritingSystem.Id); AssertFileIsInTrash(environment); var ws2 = new WritingSystemDefinition {Language = "en"}; environment.LocalRepository.SaveDefinition(ws2); environment.LocalRepository.Remove(ws2.Id); string path = Path.Combine(environment.LocalRepository.PathToWritingSystems, environment.GetPathForLocalWSId(environment.WritingSystem.LanguageTag)); Assert.IsFalse(File.Exists(path)); AssertFileIsInTrash(environment); } } [Test] public void MarkedNotModifiedWhenNew() { using (var environment = new TestEnvironment()) { //not worth saving until has some data Assert.IsFalse(environment.WritingSystem.IsChanged); } } [Test] public void MarkedAsModifiedWhenIsoChanges() { using (var environment = new TestEnvironment()) { environment.WritingSystem.Language = "en"; Assert.IsTrue(environment.WritingSystem.IsChanged); } } [Test] public void MarkedAsNotModifiedWhenLoaded() { using (var environment = new TestEnvironment()) { environment.WritingSystem.Language = "en"; environment.LocalRepository.SaveDefinition(environment.WritingSystem); environment.ResetRepositories(); WritingSystemDefinition ws2 = environment.LocalRepository.Get(environment.WritingSystem.Id); Assert.IsFalse(ws2.IsChanged); } } [Test] public void MarkedAsNotModifiedWhenSaved() { using (var environment = new TestEnvironment()) { environment.WritingSystem.Language = "en"; Assert.IsTrue(environment.WritingSystem.IsChanged); environment.LocalRepository.SaveDefinition(environment.WritingSystem); Assert.IsFalse(environment.WritingSystem.IsChanged); environment.WritingSystem.Language = "de"; Assert.IsTrue(environment.WritingSystem.IsChanged); } } [Test] public void SystemWritingSystemProvider_Set_WritingSystemsAreIncludedInStore() { using (var environment = new TestEnvironment()) { environment.LocalRepository.SystemWritingSystemProvider = new DummyWritingSystemProvider(); var list = environment.LocalRepository.AllWritingSystems; Assert.IsTrue(ContainsLanguageWithName(list, "English")); } } [Test] public void DefaultLanguageNotAddedIfInTrash() { using (var environment = new TestEnvironment()) { environment.LocalRepository.SystemWritingSystemProvider = new DummyWritingSystemProvider(); var list = environment.LocalRepository.AllWritingSystems; Assert.IsTrue(ContainsLanguageWithName(list, "English")); var list2 = new List<WritingSystemDefinition>(environment.LocalRepository.AllWritingSystems); WritingSystemDefinition ws2 = list2[0]; environment.LocalRepository.Remove(ws2.Language); environment.ResetRepositories(); // repository.DontAddDefaultDefinitions = false; environment.LocalRepository.SystemWritingSystemProvider = new DummyWritingSystemProvider(); Assert.IsFalse(ContainsLanguageWithName(environment.LocalRepository.AllWritingSystems, "English")); } } [Test] public void Constructor_LdmlFolderStoreContainsMultipleFilesThatOnLoadDescribeWritingSystemsWithIdenticalRFC5646Tags_Throws() { using (var environment = new TestEnvironment()) { File.WriteAllText(Path.Combine(environment.LocalRepositoryPath, "de-Zxxx-x-audio.ldml"), LdmlContentForTests.CurrentVersion("de", WellKnownSubtags.UnwrittenScript, "", "x-audio")); File.WriteAllText(Path.Combine(environment.LocalRepositoryPath, "inconsistent-filename.ldml"), LdmlContentForTests.CurrentVersion("de", WellKnownSubtags.UnwrittenScript, "", "x-audio")); environment.ResetRepositories(); IList<WritingSystemRepositoryProblem> problems = environment.LocalRepository.LoadProblems; Assert.That(problems.Count, Is.EqualTo(2)); Assert.That( problems[0].Exception, Is.TypeOf<ApplicationException>().With.Property("Message"). ContainsSubstring(String.Format( @"The writing system file {0} seems to be named inconsistently. It contains the IETF language tag: 'de-Zxxx-x-audio'. The name should have been made consistent with its content upon migration of the writing systems.", Path.Combine(environment.LocalRepositoryPath, "inconsistent-filename.ldml") )) ); Assert.That( problems[1].Exception, Is.TypeOf<ArgumentException>().With.Property("Message"). ContainsSubstring("Unable to set writing system 'de-Zxxx-x-audio' because this id already exists. Please change this writing system id before setting it.") ); } } [Test] public void Conflate_ChangelogRecordsChange() { using(var e = new TestEnvironment()) { e.LocalRepository.Set(new WritingSystemDefinition("de")); e.LocalRepository.Set(new WritingSystemDefinition("en")); e.LocalRepository.Conflate("de", "en"); Assert.That(e.LocalRepository.WritingSystemIdHasChangedTo("de"), Is.EqualTo("en")); } } [Test] //This is not really a problem, but it would be nice if the file were made consistant. So make we will make them run it through the migrator, which they should be using anyway. public void Constructor_LdmlFolderStoreContainsInconsistentlyNamedFile_HasExpectedProblem() { using (var environment = new TestEnvironment()) { File.WriteAllText(Path.Combine(environment.LocalRepositoryPath, "tpi-Zxxx-x-audio.ldml"), LdmlContentForTests.CurrentVersion("de", "latn", "ch", "1901")); environment.ResetRepositories(); IList<WritingSystemRepositoryProblem> problems = environment.LocalRepository.LoadProblems; Assert.That(problems.Count, Is.EqualTo(1)); Assert.That( problems[0].Exception, Is.TypeOf<ApplicationException>().With.Property("Message"). ContainsSubstring(String.Format( @"The writing system file {0} seems to be named inconsistently. It contains the IETF language tag: 'de-CH-1901'. The name should have been made consistent with its content upon migration of the writing systems.", Path.Combine(environment.LocalRepositoryPath, "tpi-Zxxx-x-audio.ldml") )) ); } } [Test] public void Constructor_LdmlFolderStoreContainsInconsistentlyNamedFileDifferingInCaseOnly_HasNoProblem() { using (var environment = new TestEnvironment()) { File.WriteAllText(Path.Combine(environment.LocalRepositoryPath, "aa-cyrl.ldml"), LdmlContentForTests.CurrentVersion("aa", "Cyrl", "", "")); environment.ResetRepositories(); IList<WritingSystemRepositoryProblem> problems = environment.LocalRepository.LoadProblems; Assert.That(problems.Count, Is.EqualTo(0)); } } [Test] //this used to throw public void LoadAllDefinitions_FilenameDoesNotMatchRfc5646Tag_NoProblem() { using (var environment = new TestEnvironment()) { //Make the filepath inconsistant environment.WritingSystem.Language = "en"; environment.LocalRepository.SaveDefinition(environment.WritingSystem); File.Move(Path.Combine(environment.LocalRepositoryPath, "en.ldml"), Path.Combine(environment.LocalRepositoryPath, "de.ldml")); // Now try to load up. environment.ResetRepositories(); Assert.That(environment.LocalRepository.Contains("en")); } } [Test] public void Get_WritingSystemContainedInFileWithfilenameThatDoesNotMatchRfc5646Tag_ReturnsWritingSystem() { using (var environment = new TestEnvironment()) { //Make the filepath inconsistant environment.WritingSystem.Language = "en"; environment.LocalRepository.SaveDefinition(environment.WritingSystem); File.Move(Path.Combine(environment.LocalRepositoryPath, "en.ldml"), Path.Combine(environment.LocalRepositoryPath, "de.ldml")); // Now try to load up. environment.ResetRepositories(); var ws = environment.LocalRepository.Get("en"); Assert.That(ws.LanguageTag, Is.EqualTo("en")); } } [Test] public void LoadAllDefinitions_FilenameIsFlexConformPrivateUseAndDoesNotMatchRfc5646Tag_Migrates() { using (var environment = new TestEnvironment()) { var ldmlPath = Path.Combine(environment.LocalRepositoryPath, "x-kal-Zxxx.ldml"); File.WriteAllText(ldmlPath, LdmlContentForTests.Version0("x-kal", "Zxxx", "", "")); LdmlInFolderWritingSystemRepository repo = LdmlInFolderWritingSystemRepository.Initialize(environment.LocalRepositoryPath); // Now try to load up. Assert.That(repo.Get("qaa-Zxxx-x-kal").Language, Is.EqualTo(new LanguageSubtag("kal"))); } } [Test] public void Set_NewWritingSystem_StoreContainsWritingSystem() { using (var environment = new TestEnvironment()) { var ws = new WritingSystemDefinition("en"); environment.LocalRepository.Set(ws); Assert.That(environment.LocalRepository.Get("en").LanguageTag, Is.EqualTo("en")); } } [Test] public void SaveDefinition_WritingSystemCameFromValidRfc5646WritingSystemStartingWithX_FileNameIsChanged() { using (var environment = new TestEnvironment()) { var pathToFlexprivateUseLdml = Path.Combine(environment.LocalRepositoryPath, "x-Zxxx-x-audio.ldml"); File.WriteAllText(pathToFlexprivateUseLdml, LdmlContentForTests.CurrentVersion("xh", "", "", "")); environment.ResetRepositories(); Assert.That(File.Exists(Path.Combine(environment.LocalRepositoryPath, "xh.ldml"))); } } [Test] public void WritingSystemIdHasBeenChanged_IdNeverExisted_ReturnsFalse() { using (var environment = new TestEnvironment()) { //Add a writing system to the repo Assert.That(environment.LocalRepository.WritingSystemIdHasChanged("en"), Is.False); } } [Test] public void WritingSystemIdHasBeenChanged_IdChanged_ReturnsTrue() { using (var environment = new TestEnvironment()) { //Add a writing system to the repo var ws = new WritingSystemDefinition("en"); environment.LocalRepository.Set(ws); environment.LocalRepository.Save(); //Now change the Id ws.Variants.Add("bogus"); environment.LocalRepository.Save(); Assert.That(environment.LocalRepository.WritingSystemIdHasChanged("en"), Is.True); } } [Test] public void WritingSystemIdHasBeenChanged_IdChangedToMultipleDifferentNewIds_ReturnsTrue() { using (var environment = new TestEnvironment()) { //Add a writing system to the repo var wsEn = new WritingSystemDefinition("en"); environment.LocalRepository.Set(wsEn); environment.LocalRepository.Save(); //Now change the Id and create a duplicate of the original Id wsEn.Variants.Add("bogus"); environment.LocalRepository.Set(wsEn); var wsEnDup = new WritingSystemDefinition("en"); environment.LocalRepository.Set(wsEnDup); environment.LocalRepository.Save(); //Now change the duplicate's Id as well wsEnDup.Variants.Add("bogus2"); environment.LocalRepository.Set(wsEnDup); environment.LocalRepository.Save(); Assert.That(environment.LocalRepository.WritingSystemIdHasChanged("en"), Is.True); } } [Test] public void WritingSystemIdHasBeenChanged_IdExistsAndHasNeverChanged_ReturnsFalse() { using (var environment = new TestEnvironment()) { //Add a writing system to the repo var ws = new WritingSystemDefinition("en"); environment.LocalRepository.Set(ws); environment.LocalRepository.Save(); Assert.That(environment.LocalRepository.WritingSystemIdHasChanged("en"), Is.False); } } [Test] public void WritingSystemIdHasChangedTo_IdNeverExisted_ReturnsNull() { using (var environment = new TestEnvironment()) { //Add a writing system to the repo Assert.That(environment.LocalRepository.WritingSystemIdHasChangedTo("en"), Is.Null); } } [Test] public void WritingSystemIdHasChangedTo_IdChanged_ReturnsNewId() { using (var environment = new TestEnvironment()) { //Add a writing system to the repo var ws = new WritingSystemDefinition("en"); environment.LocalRepository.Set(ws); environment.LocalRepository.Save(); //Now change the Id ws.Variants.Add("bogus"); environment.LocalRepository.Save(); Assert.That(environment.LocalRepository.WritingSystemIdHasChangedTo("en"), Is.EqualTo("en-x-bogus")); } } [Test] public void WritingSystemIdHasChangedTo_IdChangedToMultipleDifferentNewIds_ReturnsNull() { using (var environment = new TestEnvironment()) { //Add a writing system to the repo var wsEn = new WritingSystemDefinition("en"); environment.LocalRepository.Set(wsEn); environment.LocalRepository.Save(); //Now change the Id and create a duplicate of the original Id wsEn.Variants.Add("bogus"); environment.LocalRepository.Set(wsEn); var wsEnDup = new WritingSystemDefinition("en"); environment.LocalRepository.Set(wsEnDup); environment.LocalRepository.Save(); //Now change the duplicate's Id as well wsEnDup.Variants.Add("bogus2"); environment.LocalRepository.Set(wsEnDup); environment.LocalRepository.Save(); Assert.That(environment.LocalRepository.WritingSystemIdHasChangedTo("en"), Is.Null); } } [Test] public void WritingSystemIdHasChangedTo_IdExistsAndHasNeverChanged_ReturnsId() { using (var environment = new TestEnvironment()) { //Add a writing system to the repo var ws = new WritingSystemDefinition("en"); environment.LocalRepository.Set(ws); environment.LocalRepository.Save(); Assert.That(environment.LocalRepository.WritingSystemIdHasChangedTo("en"), Is.EqualTo("en")); } } [Test] //This test checks that "old" ldml files are not overwritten on Save before they can be used to roundtrip unknown ldml (i.e. from flex) public void Save_IdOfWsIsSameAsOldIdOfOtherWs_LdmlUnknownToRepoIsMaintained() { using (var environment = new TestEnvironment()) { string germanFromFlex = #region fileContent @"<?xml version='1.0' encoding='utf-8'?> <ldml> <identity> <version number='' /> <generation date='2010-12-02T23:05:33' /> <language type='de' /> </identity> <collations /> <special xmlns:palaso='urn://palaso.org/ldmlExtensions/v1'> <palaso:abbreviation value='de' /> <palaso:defaultFontFamily value='FieldWorks Test SIL' /> <palaso:defaultKeyboard value='FwTest' /> <palaso:languageName value='German' /> <palaso:spellCheckingId value='de' /> <palaso:version value='1'/> </special> <special xmlns:fw='urn://fieldworks.sil.org/ldmlExtensions/v1'> <fw:graphiteEnabled value='False' /> <fw:windowsLCID value='1058' /> </special> </ldml>".Replace("'", "\""); #endregion var pathForFlexGerman = Path.Combine(environment.LocalRepositoryPath, "de.ldml"); var ws1 = new WritingSystemDefinition("en"); var ws2 = new WritingSystemDefinition("de"); //Create repo with english and flex german environment.LocalRepository.Set(ws1); environment.LocalRepository.Set(ws2); environment.LocalRepository.Save(); //The content of the file is switched out here as opposed to loading from this content in the first place //because order is extremely important for this test and if we loaded from this ldml "de" would be the //first writing system in the repo rather than the second. File.WriteAllText(pathForFlexGerman, germanFromFlex); //rename the ws ws1.Language = "de"; ws2.Language = "fr"; environment.LocalRepository.Set(ws2); environment.LocalRepository.Set(ws1); environment.LocalRepository.Save(); pathForFlexGerman = Path.Combine(environment.LocalRepositoryPath, "fr.ldml"); var manager = new XmlNamespaceManager(new NameTable()); manager.AddNamespace("fw", "urn://fieldworks.sil.org/ldmlExtensions/v1"); AssertThatXmlIn.File(pathForFlexGerman).HasAtLeastOneMatchForXpath("/ldml/special/fw:graphiteEnabled", manager); } } [Test] public void Save_IdOfWsIsSameAsOldIdOfOtherWs_RepoHasCorrectNumberOfWritingSystemsOnLoad() { using (var environment = new TestEnvironment()) { var ws1 = new WritingSystemDefinition("en"); var ws2 = new WritingSystemDefinition("de"); environment.LocalRepository.Set(ws1); environment.LocalRepository.Set(ws2); environment.LocalRepository.Save(); //rename the ws ws1.Language = "de"; ws2.Language = "fr"; environment.LocalRepository.Set(ws2); environment.LocalRepository.Set(ws1); environment.LocalRepository.Save(); environment.ResetRepositories(); Assert.That(environment.LocalRepository.Count, Is.EqualTo(2)); } } [Test] public void LoadAllDefinitions_LDMLV0_HasExpectedProblem() { using (var environment = new TestEnvironment()) { var ldmlPath = Path.Combine(environment.LocalRepositoryPath, "en.ldml"); File.WriteAllText(ldmlPath, LdmlContentForTests.Version0("en", "", "", "")); var repository = new LdmlInFolderWritingSystemRepository(environment.LocalRepositoryPath); var problems = repository.LoadProblems; Assert.That(problems.Count, Is.EqualTo(1)); Assert.That( problems[0].Exception, Is.TypeOf<ApplicationException>().With.Property("Message"). ContainsSubstring(String.Format( "The LDML tag 'en' is version 0. Version {0} was expected.", LdmlDataMapper.CurrentLdmlVersion )) ); } } [Test] public void LoadDefinitions_ValidLanguageTagStartingWithXButV0_Throws() { using (var environment = new TestEnvironment()) { var pathToFlexprivateUseLdml = Path.Combine(environment.LocalRepositoryPath, "xh.ldml"); File.WriteAllText(pathToFlexprivateUseLdml, LdmlContentForTests.Version0("xh", "", "", "")); var repository = new LdmlInFolderWritingSystemRepository(environment.LocalRepositoryPath); var problems = repository.LoadProblems; Assert.That(problems.Count, Is.EqualTo(1)); Assert.That( problems[0].Exception, Is.TypeOf<ApplicationException>().With.Property("Message"). ContainsSubstring(String.Format( "The LDML tag 'xh' is version 0. Version {0} was expected.", LdmlDataMapper.CurrentLdmlVersion )) ); } } [Test] public void FactoryCreate_TemplateAvailableInLocalRepo_UsedTemplateFromLocalRepo() { using (var environment = new TestEnvironment()) { File.WriteAllText(environment.GetPathForLocalWSId("en"), @"<?xml version='1.0' encoding='utf-8'?> <ldml> <identity> <version number='1.0'>From Repo</version> <generation date='0001-01-01T00:00:00' /> <language type='en' /> <script type='Latn' /> </identity> <layout> <orientation> <characterOrder>left-to-right</characterOrder> <lineOrder>top-to-bottom</lineOrder> </orientation> </layout> </ldml> "); environment.ResetRepositories(); WritingSystemDefinition enWS; Assert.That(environment.LocalRepository.WritingSystemFactory.Create("en", out enWS), Is.True); Assert.That(enWS.Language, Is.EqualTo((LanguageSubtag) "en")); Assert.That(enWS.Script, Is.EqualTo((ScriptSubtag) "Latn")); Assert.That(enWS.VersionDescription, Is.EqualTo("From Repo")); Assert.That(enWS.Template, Is.EqualTo(environment.GetPathForLocalWSId("en"))); // ensure that the template is used when the writing system is saved enWS.Region = "US"; environment.LocalRepository.Set(enWS); environment.LocalRepository.Save(); XElement ldmlElem = XElement.Load(environment.GetPathForLocalWSId("en-US")); Assert.That((string) ldmlElem.Elements("layout").Elements("orientation").Elements("lineOrder").First(), Is.EqualTo("top-to-bottom")); } } [Test] public void FactoryCreate_TemplateAvailableInSldr_UsedTemplateFromSldr() { using (var environment = new TestEnvironment()) { environment.LocalRepository.WritingSystemFactory.SldrLdmls["en"] = @"<?xml version='1.0' encoding='utf-8'?> <ldml> <identity> <version number='1.0'>From SLDR</version> <generation date='0001-01-01T00:00:00' /> <language type='en' /> <script type='Latn' /> </identity> <layout> <orientation> <characterOrder>left-to-right</characterOrder> <lineOrder>top-to-bottom</lineOrder> </orientation> </layout> </ldml> "; WritingSystemDefinition enWS; Assert.That(environment.LocalRepository.WritingSystemFactory.Create("en", out enWS), Is.True); Assert.That(enWS.Language, Is.EqualTo((LanguageSubtag) "en")); Assert.That(enWS.Script, Is.EqualTo((ScriptSubtag) "Latn")); Assert.That(enWS.VersionDescription, Is.EqualTo("From SLDR")); Assert.That(enWS.Template, Is.EqualTo(Path.Combine(Sldr.SldrCachePath, "en.ldml"))); // ensure that the template is used when the writing system is saved environment.LocalRepository.Set(enWS); environment.LocalRepository.Save(); XElement ldmlElem = XElement.Load(environment.GetPathForLocalWSId("en")); Assert.That((string) ldmlElem.Elements("layout").Elements("orientation").Elements("lineOrder").First(), Is.EqualTo("top-to-bottom")); } } [Test] public void FactoryCreate_TemplateNotAvailableInSldr_UsedTemplateFromTemplateFolder() { using (var environment = new TestEnvironment()) { File.WriteAllText(Path.Combine(environment.LocalRepository.WritingSystemFactory.TemplateFolder, "zh-CN.ldml"), @"<?xml version='1.0' encoding='utf-8'?> <ldml> <identity> <version number='1.0'>From Templates</version> <generation date='0001-01-01T00:00:00' /> <language type='zh' /> <script type='Hans' /> <territory type='CN' /> </identity> <layout> <orientation> <characterOrder>left-to-right</characterOrder> <lineOrder>top-to-bottom</lineOrder> </orientation> </layout> </ldml> "); WritingSystemDefinition chWS; Assert.That(environment.LocalRepository.WritingSystemFactory.Create("zh-CN", out chWS), Is.False); Assert.That(chWS.Language, Is.EqualTo((LanguageSubtag) "zh")); Assert.That(chWS.Script, Is.EqualTo((ScriptSubtag) "Hans")); Assert.That(chWS.Region, Is.EqualTo((RegionSubtag) "CN")); Assert.That(chWS.VersionDescription, Is.EqualTo("From Templates")); Assert.That(chWS.Template, Is.EqualTo(Path.Combine(environment.LocalRepository.WritingSystemFactory.TemplateFolder, "zh-CN.ldml"))); // ensure that the template is used when the writing system is saved environment.LocalRepository.Set(chWS); environment.LocalRepository.Save(); XElement ldmlElem = XElement.Load(environment.GetPathForLocalWSId("zh-CN")); Assert.That((string) ldmlElem.Elements("layout").Elements("orientation").Elements("lineOrder").First(), Is.EqualTo("top-to-bottom")); } } [Test] public void Save_UpdatesGlobalStore() { using (var environment = new TestEnvironment()) using (var testFolder2 = new TemporaryFolder("LdmlInFolderWritingSystemRepositoryTests2")) { var ws = new WritingSystemDefinition("en-US"); environment.LocalRepository.Set(ws); ws.RightToLeftScript = true; ws.DefaultCollation = new SystemCollationDefinition {LanguageTag = "en-US"}; environment.LocalRepository.Save(); Assert.IsTrue(File.Exists(environment.GetPathForLocalWSId("en-US"))); Assert.IsTrue(File.Exists(environment.GetPathForGlobalWSId("en-US"))); // ensure that the date modified actually changes Thread.Sleep(1000); DateTime lastModified = File.GetLastWriteTime(environment.GetPathForGlobalWSId("en-US")); var localRepo2 = new LdmlInFolderWritingSystemRepository(testFolder2.Path, environment.GlobalRepository); ws = new WritingSystemDefinition("en-US"); localRepo2.Set(ws); ws.RightToLeftScript = false; localRepo2.Save(); Assert.Less(lastModified, File.GetLastWriteTime(environment.GetPathForGlobalWSId("en-US"))); lastModified = File.GetLastWriteTime(environment.GetPathForLocalWSId("en-US")); environment.ResetRepositories(); ws = environment.LocalRepository.Get("en-US"); Assert.That(ws.RightToLeftScript, Is.True); WritingSystemDefinition[] sharedWSs = environment.LocalRepository.CheckForNewerGlobalWritingSystems().ToArray(); Assert.That(sharedWSs.Select(sharedWS => sharedWS.LanguageTag), Is.EqualTo(new[] {"en-US"})); environment.LocalRepository.Remove(sharedWSs[0].LanguageTag); environment.LocalRepository.Set(sharedWSs[0]); environment.LocalRepository.Save(); ws = environment.LocalRepository.Get("en-US"); Assert.That(ws.RightToLeftScript, Is.False); // ensure that application-specific settings are preserved Assert.That(ws.DefaultCollation.ValueEquals(new SystemCollationDefinition {LanguageTag = "en-US"}), Is.True); Assert.Less(lastModified, File.GetLastWriteTime(environment.GetPathForLocalWSId("en-US"))); } } [Test] public void Save_UpdatesWritingSystemsToIgnore() { using (var environment = new TestEnvironment()) using (var testFolder2 = new TemporaryFolder("LdmlInFolderWritingSystemRepositoryTests2")) { var ws = new WritingSystemDefinition("en-US"); environment.LocalRepository.Set(ws); ws.RightToLeftScript = true; environment.LocalRepository.Save(); // ensure that the date modified actually changes Thread.Sleep(1000); var localRepo2 = new LdmlInFolderWritingSystemRepository(testFolder2.Path, environment.GlobalRepository); ws = new WritingSystemDefinition("en-US"); localRepo2.Set(ws); ws.RightToLeftScript = false; localRepo2.Save(); environment.ResetRepositories(); ws = environment.LocalRepository.Get("en-US"); Assert.That(ws.RightToLeftScript, Is.True); WritingSystemDefinition[] sharedWSs = environment.LocalRepository.CheckForNewerGlobalWritingSystems().ToArray(); Assert.That(sharedWSs.Select(sharedWS => sharedWS.LanguageTag), Is.EqualTo(new[] {"en-US"})); environment.LocalRepository.Save(); environment.ResetRepositories(); Assert.That(environment.LocalRepository.CheckForNewerGlobalWritingSystems(), Is.Empty); environment.LocalRepository.Save(); // ensure that the date modified actually changes Thread.Sleep(1000); localRepo2 = new LdmlInFolderWritingSystemRepository(testFolder2.Path, environment.GlobalRepository); ws = localRepo2.Get("en-US"); ws.CharacterSets.Add(new CharacterSetDefinition("main")); localRepo2.Save(); environment.ResetRepositories(); ws = environment.LocalRepository.Get("en-US"); Assert.That(ws.CharacterSets, Is.Empty); sharedWSs = environment.LocalRepository.CheckForNewerGlobalWritingSystems().ToArray(); Assert.That(sharedWSs.Select(sharedWS => sharedWS.LanguageTag), Is.EqualTo(new[] {"en-US"})); environment.LocalRepository.Remove(sharedWSs[0].LanguageTag); environment.LocalRepository.Set(sharedWSs[0]); environment.LocalRepository.Save(); ws = environment.LocalRepository.Get("en-US"); Assert.That(ws.CharacterSets.Count, Is.EqualTo(1)); Assert.That(ws.CharacterSets[0].Type, Is.EqualTo("main")); } } private static bool ContainsLanguageWithName(IEnumerable<WritingSystemDefinition> list, string name) { return list.Any(definition => definition.Language.Name == name); } class DummyWritingSystemProvider : IEnumerable<WritingSystemDefinition> { public IEnumerator<WritingSystemDefinition> GetEnumerator() { yield return new WritingSystemDefinition("en", "", "", ""); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } }
/* * REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application * * The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists. * * OpenAPI spec version: v1 * * */ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Xunit; using HETSAPI; using System.Text; using System.Net; using Newtonsoft.Json; using HETSAPI.Models; using HETSAPI.ViewModels; namespace HETSAPI.Test { public class RoleApiIntegrationTest : ApiIntegrationTestBase { [Fact] /// <summary> /// Basic Integration test for Roles /// </summary> public async void TestRolesBasic() { string initialName = "InitialName"; string changedName = "ChangedName"; // first test the POST. var request = new HttpRequestMessage(HttpMethod.Post, "/api/roles"); // create a new object. RoleViewModel role = new RoleViewModel(); role.Name = initialName; string jsonString = role.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); role = JsonConvert.DeserializeObject<RoleViewModel>(jsonString); // get the id var id = role.Id; // change the name role.Name = changedName; // now do an update. request = new HttpRequestMessage(HttpMethod.Put, "/api/roles/" + id); request.Content = new StringContent(role.ToJson(), Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // do a get. request = new HttpRequestMessage(HttpMethod.Get, "/api/roles/" + id); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); role = JsonConvert.DeserializeObject<RoleViewModel>(jsonString); // verify the change went through. Assert.Equal(role.Name, changedName); // do a delete. request = new HttpRequestMessage(HttpMethod.Post, "/api/roles/" + id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // should get a 404 if we try a get now. request = new HttpRequestMessage(HttpMethod.Get, "/api/roles/" + id); response = await _client.SendAsync(request); Assert.Equal(response.StatusCode, HttpStatusCode.NotFound); } [Fact] /// <summary> /// Test Users and Roles /// </summary> public async void TestUserRoles() { // first create a role. string initialName = "InitialName"; var request = new HttpRequestMessage(HttpMethod.Post, "/api/roles"); RoleViewModel role = new RoleViewModel(); role.Name = initialName; role.Description = "test"; string jsonString = role.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); role = JsonConvert.DeserializeObject<RoleViewModel>(jsonString); // get the role id var role_id = role.Id; // now create a user. request = new HttpRequestMessage(HttpMethod.Post, "/api/users"); UserViewModel user = new UserViewModel(); user.GivenName = initialName; jsonString = user.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); user = JsonConvert.DeserializeObject<UserViewModel>(jsonString); // get the user id var user_id = user.Id; // now add the user to the role. UserRoleViewModel userRole = new UserRoleViewModel(); userRole.RoleId = role_id; userRole.UserId = user_id; userRole.EffectiveDate = DateTime.Now; UserRoleViewModel[] items = new UserRoleViewModel[1]; items[0] = userRole; // send the request. request = new HttpRequestMessage(HttpMethod.Put, "/api/roles/" + role_id + "/users"); jsonString = JsonConvert.SerializeObject(items, Formatting.Indented); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // if we do a get we should get the same items. request = new HttpRequestMessage(HttpMethod.Get, "/api/roles/" + role_id + "/users"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); User[] userRolesResponse = JsonConvert.DeserializeObject<User[]>(jsonString); Assert.Equal(items[0].UserId, userRolesResponse[0].Id); // cleanup // Delete user request = new HttpRequestMessage(HttpMethod.Post, "/api/users/" + user_id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // should get a 404 if we try a get now. request = new HttpRequestMessage(HttpMethod.Get, "/api/users/" + user_id); response = await _client.SendAsync(request); Assert.Equal(response.StatusCode, HttpStatusCode.NotFound); // Delete role request = new HttpRequestMessage(HttpMethod.Post, "/api/roles/" + role_id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // should get a 404 if we try a get now. request = new HttpRequestMessage(HttpMethod.Get, "/api/roles/" + role_id); response = await _client.SendAsync(request); Assert.Equal(response.StatusCode, HttpStatusCode.NotFound); } [Fact] /// <summary> /// Test Users and Roles /// </summary> public async void TestRolePermissions() { // first create a role. string initialName = "InitialName"; var request = new HttpRequestMessage(HttpMethod.Post, "/api/roles"); RoleViewModel roleViewModel = new RoleViewModel(); roleViewModel.Name = initialName; string jsonString = roleViewModel.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); roleViewModel = JsonConvert.DeserializeObject<RoleViewModel>(jsonString); // get the role id var role_id = roleViewModel.Id; // now create a permission. request = new HttpRequestMessage(HttpMethod.Post, "/api/permissions"); Permission permission = new Permission(); permission.Name = initialName; permission.Code = initialName; jsonString = permission.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); permission = JsonConvert.DeserializeObject<Permission>(jsonString); // get the permission id int permission_id = permission.Id; // now add the permission to the role. request = new HttpRequestMessage(HttpMethod.Post, "/api/roles/" + role_id + "/permissions"); jsonString = JsonConvert.SerializeObject(permission, Formatting.Indented); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // if we do a get we should get the same items. request = new HttpRequestMessage(HttpMethod.Get, "/api/roles/" + role_id + "/permissions"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); PermissionViewModel[] rolePermissionsResponse = JsonConvert.DeserializeObject<PermissionViewModel[]>(jsonString); bool found = false; foreach (var item in rolePermissionsResponse) { if (permission.Code.Equals (item.Code) && permission.Name.Equals (item.Name)) { found = true; } } Assert.Equal(found, true); // test the put. Permission[] items = new Permission[1]; items[0] = permission; request = new HttpRequestMessage(HttpMethod.Put, "/api/roles/" + role_id + "/permissions"); jsonString = JsonConvert.SerializeObject(items, Formatting.Indented); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); rolePermissionsResponse = JsonConvert.DeserializeObject<PermissionViewModel[]>(jsonString); found = false; foreach (var item in rolePermissionsResponse) { if (permission.Code.Equals(item.Code) && permission.Name.Equals(item.Name)) { found = true; } } Assert.Equal(found, true); // cleanup // Delete permission request = new HttpRequestMessage(HttpMethod.Post, "/api/permissions/" + permission_id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // should get a 404 if we try a get now. request = new HttpRequestMessage(HttpMethod.Get, "/api/permissions/" + permission_id); response = await _client.SendAsync(request); Assert.Equal(response.StatusCode, HttpStatusCode.NotFound); // Delete role request = new HttpRequestMessage(HttpMethod.Post, "/api/roles/" + role_id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // should get a 404 if we try a get now. request = new HttpRequestMessage(HttpMethod.Get, "/api/roles/" + role_id); response = await _client.SendAsync(request); Assert.Equal(response.StatusCode, HttpStatusCode.NotFound); } } }
#if UNITY_WINRT && !UNITY_EDITOR && !UNITY_WP8 using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Numerics; using System.Text; namespace Newtonsoft.Json.Serialization { internal class TraceJsonWriter : JsonWriter { private readonly JsonWriter _innerWriter; private readonly JsonTextWriter _textWriter; private readonly StringWriter _sw; public TraceJsonWriter(JsonWriter innerWriter) { _innerWriter = innerWriter; _sw = new StringWriter(CultureInfo.InvariantCulture); _textWriter = new JsonTextWriter(_sw); _textWriter.Formatting = Formatting.Indented; _textWriter.Culture = innerWriter.Culture; _textWriter.DateFormatHandling = innerWriter.DateFormatHandling; _textWriter.DateFormatString = innerWriter.DateFormatString; _textWriter.DateTimeZoneHandling = innerWriter.DateTimeZoneHandling; _textWriter.FloatFormatHandling = innerWriter.FloatFormatHandling; } public string GetJson() { return _sw.ToString(); } public override void WriteValue(decimal value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(bool value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(byte value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(byte? value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(char value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(byte[] value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(DateTime value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(DateTimeOffset value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(double value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteUndefined() { _textWriter.WriteUndefined(); _innerWriter.WriteUndefined(); base.WriteUndefined(); } public override void WriteNull() { _textWriter.WriteNull(); _innerWriter.WriteNull(); base.WriteUndefined(); } public override void WriteValue(float value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(Guid value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(int value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(long value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(object value) { if (value is BigInteger) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); InternalWriteValue(JsonToken.Integer); } else { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } } public override void WriteValue(sbyte value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(short value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(string value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(TimeSpan value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(uint value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(ulong value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(Uri value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteValue(ushort value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); base.WriteValue(value); } public override void WriteWhitespace(string ws) { _textWriter.WriteWhitespace(ws); _innerWriter.WriteWhitespace(ws); base.WriteWhitespace(ws); } public override void WriteComment(string text) { _textWriter.WriteComment(text); _innerWriter.WriteComment(text); base.WriteComment(text); } public override void WriteStartArray() { _textWriter.WriteStartArray(); _innerWriter.WriteStartArray(); base.WriteStartArray(); } public override void WriteEndArray() { _textWriter.WriteEndArray(); _innerWriter.WriteEndArray(); base.WriteEndArray(); } public override void WriteStartConstructor(string name) { _textWriter.WriteStartConstructor(name); _innerWriter.WriteStartConstructor(name); base.WriteStartConstructor(name); } public override void WriteEndConstructor() { _textWriter.WriteEndConstructor(); _innerWriter.WriteEndConstructor(); base.WriteEndConstructor(); } public override void WritePropertyName(string name) { _textWriter.WritePropertyName(name); _innerWriter.WritePropertyName(name); base.WritePropertyName(name); } public override void WritePropertyName(string name, bool escape) { _textWriter.WritePropertyName(name, escape); _innerWriter.WritePropertyName(name, escape); // method with escape will error base.WritePropertyName(name); } public override void WriteStartObject() { _textWriter.WriteStartObject(); _innerWriter.WriteStartObject(); base.WriteStartObject(); } public override void WriteEndObject() { _textWriter.WriteEndObject(); _innerWriter.WriteEndObject(); base.WriteEndObject(); } public override void WriteRaw(string json) { _textWriter.WriteRaw(json); _innerWriter.WriteRaw(json); base.WriteRaw(json); } public override void WriteRawValue(string json) { _textWriter.WriteRawValue(json); _innerWriter.WriteRawValue(json); base.WriteRawValue(json); } public override void Close() { _textWriter.Close(); _innerWriter.Close(); base.Close(); } public override void Flush() { _textWriter.Flush(); _innerWriter.Flush(); } } } #endif
// 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 Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class IOperationTests : SemanticModelTestBase { [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void SimpleArrayCreation_PrimitiveType() { string source = @" class C { public void F() { var a = /*<bind>*/new string[1]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.String[]) (Syntax: 'new string[1]') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void SimpleArrayCreation_UserDefinedType() { string source = @" class M { } class C { public void F() { var a = /*<bind>*/new M[1]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: M[]) (Syntax: 'new M[1]') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void SimpleArrayCreation_ConstantDimension() { string source = @" class M { } class C { public void F() { const int dimension = 1; var a = /*<bind>*/new M[dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: M[]) (Syntax: 'new M[dimension]') Dimension Sizes(1): ILocalReferenceExpression: dimension (OperationKind.LocalReferenceExpression, Type: System.Int32, Constant: 1) (Syntax: 'dimension') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void SimpleArrayCreation_NonConstantDimension() { string source = @" class M { } class C { public void F(int dimension) { var a = /*<bind>*/new M[dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: M[]) (Syntax: 'new M[dimension]') Dimension Sizes(1): IParameterReferenceExpression: dimension (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'dimension') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void SimpleArrayCreation_DimensionWithImplicitConversion() { string source = @" class M { } class C { public void F(char dimension) { var a = /*<bind>*/new M[dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: M[]) (Syntax: 'new M[dimension]') Dimension Sizes(1): IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Int32, IsImplicit) (Syntax: 'dimension') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceExpression: dimension (OperationKind.ParameterReferenceExpression, Type: System.Char) (Syntax: 'dimension') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void SimpleArrayCreation_DimensionWithExplicitConversion() { string source = @" class M { } class C { public void F(object dimension) { var a = /*<bind>*/new M[(int)dimension]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: M[]) (Syntax: 'new M[(int)dimension]') Dimension Sizes(1): IConversionExpression (Explicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Int32) (Syntax: '(int)dimension') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceExpression: dimension (OperationKind.ParameterReferenceExpression, Type: System.Object) (Syntax: 'dimension') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializer_PrimitiveType() { string source = @" class C { public void F() { var a = /*<bind>*/new string[] { string.Empty }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.String[]) (Syntax: 'new string[ ... ing.Empty }') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new string[ ... ing.Empty }') Initializer: IArrayInitializer (1 elements) (OperationKind.ArrayInitializer) (Syntax: '{ string.Empty }') Element Values(1): IFieldReferenceExpression: System.String System.String.Empty (Static) (OperationKind.FieldReferenceExpression, Type: System.String) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializer_PrimitiveTypeWithExplicitDimension() { string source = @" class C { public void F() { var a = /*<bind>*/new string[1] { string.Empty }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.String[]) (Syntax: 'new string[ ... ing.Empty }') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: IArrayInitializer (1 elements) (OperationKind.ArrayInitializer) (Syntax: '{ string.Empty }') Element Values(1): IFieldReferenceExpression: System.String System.String.Empty (Static) (OperationKind.FieldReferenceExpression, Type: System.String) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializerErrorCase_PrimitiveTypeWithIncorrectExplicitDimension() { string source = @" class C { public void F() { var a = /*<bind>*/new string[2] { string.Empty }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.String[], IsInvalid) (Syntax: 'new string[ ... ing.Empty }') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2) (Syntax: '2') Initializer: IArrayInitializer (1 elements) (OperationKind.ArrayInitializer, IsInvalid) (Syntax: '{ string.Empty }') Element Values(1): IFieldReferenceExpression: System.String System.String.Empty (Static) (OperationKind.FieldReferenceExpression, Type: System.String, IsInvalid) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0847: An array initializer of length '2' is expected // var a = /*<bind>*/new string[2] { string.Empty }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "{ string.Empty }").WithArguments("2").WithLocation(6, 41) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializerErrorCase_PrimitiveTypeWithNonConstantExplicitDimension() { string source = @" class C { public void F(int dimension) { var a = /*<bind>*/new string[dimension] { string.Empty }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.String[], IsInvalid) (Syntax: 'new string[ ... ing.Empty }') Dimension Sizes(1): IParameterReferenceExpression: dimension (OperationKind.ParameterReferenceExpression, Type: System.Int32, IsInvalid) (Syntax: 'dimension') Initializer: IArrayInitializer (1 elements) (OperationKind.ArrayInitializer) (Syntax: '{ string.Empty }') Element Values(1): IFieldReferenceExpression: System.String System.String.Empty (Static) (OperationKind.FieldReferenceExpression, Type: System.String) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0150: A constant value is expected // var a = /*<bind>*/new string[dimension] { string.Empty }/*</bind>*/; Diagnostic(ErrorCode.ERR_ConstantExpected, "dimension").WithLocation(6, 38) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializer_NoExplicitArrayCreationExpression() { string source = @" class C { public void F(int dimension) { /*<bind>*/int[] x = { 1, 2 };/*</bind>*/ } } "; string expectedOperationTree = @" IVariableDeclarationStatement (1 declarations) (OperationKind.VariableDeclarationStatement) (Syntax: 'int[] x = { 1, 2 };') IVariableDeclaration (1 variables) (OperationKind.VariableDeclaration) (Syntax: 'x = { 1, 2 }') Variables: Local_1: System.Int32[] x Initializer: IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Int32[]) (Syntax: '{ 1, 2 }') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '{ 1, 2 }') Initializer: IArrayInitializer (2 elements) (OperationKind.ArrayInitializer) (Syntax: '{ 1, 2 }') Element Values(2): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2) (Syntax: '2') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializer_UserDefinedType() { string source = @" class M { } class C { public void F() { var a = /*<bind>*/new M[] { new M() }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: M[]) (Syntax: 'new M[] { new M() }') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new M[] { new M() }') Initializer: IArrayInitializer (1 elements) (OperationKind.ArrayInitializer) (Syntax: '{ new M() }') Element Values(1): IObjectCreationExpression (Constructor: M..ctor()) (OperationKind.ObjectCreationExpression, Type: M) (Syntax: 'new M()') Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializer_ImplicitlyTyped() { string source = @" class M { } class C { public void F() { var a = /*<bind>*/new[] { new M() }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: M[]) (Syntax: 'new[] { new M() }') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new[] { new M() }') Initializer: IArrayInitializer (1 elements) (OperationKind.ArrayInitializer) (Syntax: '{ new M() }') Element Values(1): IObjectCreationExpression (Constructor: M..ctor()) (OperationKind.ObjectCreationExpression, Type: M) (Syntax: 'new M()') Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ImplicitArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializerErrorCase_ImplicitlyTypedWithoutInitializerAndDimension() { string source = @" class C { public void F(int dimension) { var x = /*<bind>*/new[]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: ?[], IsInvalid) (Syntax: 'new[]/*</bind>*/') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 0, IsInvalid, IsImplicit) (Syntax: 'new[]/*</bind>*/') Initializer: IArrayInitializer (0 elements) (OperationKind.ArrayInitializer, IsInvalid) (Syntax: '') Element Values(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1514: { expected // var x = /*<bind>*/new[]/*</bind>*/; Diagnostic(ErrorCode.ERR_LbraceExpected, ";").WithLocation(6, 43), // CS1513: } expected // var x = /*<bind>*/new[]/*</bind>*/; Diagnostic(ErrorCode.ERR_RbraceExpected, ";").WithLocation(6, 43), // CS0826: No best type found for implicitly-typed array // var x = /*<bind>*/new[]/*</bind>*/; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[]/*</bind>*/").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ImplicitArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializerErrorCase_ImplicitlyTypedWithoutInitializer() { string source = @" class C { public void F(int dimension) { var x = /*<bind>*/new[2]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Int32[], IsInvalid) (Syntax: 'new[2]/*</bind>*/') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'new[2]/*</bind>*/') Initializer: IArrayInitializer (1 elements) (OperationKind.ArrayInitializer, IsInvalid) (Syntax: '2]/*</bind>*/') Element Values(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1003: Syntax error, ']' expected // var x = /*<bind>*/new[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_SyntaxError, "2").WithArguments("]", "").WithLocation(6, 31), // CS1514: { expected // var x = /*<bind>*/new[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_LbraceExpected, "2").WithLocation(6, 31), // CS1003: Syntax error, ',' expected // var x = /*<bind>*/new[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_SyntaxError, "]").WithArguments(",", "]").WithLocation(6, 32), // CS1513: } expected // var x = /*<bind>*/new[2]/*</bind>*/; Diagnostic(ErrorCode.ERR_RbraceExpected, ";").WithLocation(6, 44) }; VerifyOperationTreeAndDiagnosticsForTest<ImplicitArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationWithInitializer_MultipleInitializersWithConversions() { string source = @" class C { public void F() { var a = """"; var b = /*<bind>*/new[] { ""hello"", a, null }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.String[]) (Syntax: 'new[] { ""he ... , a, null }') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: 'new[] { ""he ... , a, null }') Initializer: IArrayInitializer (3 elements) (OperationKind.ArrayInitializer) (Syntax: '{ ""hello"", a, null }') Element Values(3): ILiteralExpression (OperationKind.LiteralExpression, Type: System.String, Constant: ""hello"") (Syntax: '""hello""') ILocalReferenceExpression: a (OperationKind.LocalReferenceExpression, Type: System.String) (Syntax: 'a') IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.String, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralExpression (OperationKind.LiteralExpression, Type: null, Constant: null) (Syntax: 'null') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ImplicitArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void MultiDimensionalArrayCreation() { string source = @" class C { public void F() { byte[,,] b = /*<bind>*/new byte[1,2,3]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Byte[,,]) (Syntax: 'new byte[1,2,3]') Dimension Sizes(3): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 3) (Syntax: '3') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void MultiDimensionalArrayCreation_WithInitializer() { string source = @" class C { public void F() { byte[,,] b = /*<bind>*/new byte[,,] { { { 1, 2, 3 } }, { { 4, 5, 6 } } }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Byte[,,]) (Syntax: 'new byte[,, ... 5, 6 } } }') Dimension Sizes(3): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'new byte[,, ... 5, 6 } } }') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new byte[,, ... 5, 6 } } }') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: 'new byte[,, ... 5, 6 } } }') Initializer: IArrayInitializer (2 elements) (OperationKind.ArrayInitializer) (Syntax: '{ { { 1, 2, ... 5, 6 } } }') Element Values(2): IArrayInitializer (1 elements) (OperationKind.ArrayInitializer) (Syntax: '{ { 1, 2, 3 } }') Element Values(1): IArrayInitializer (3 elements) (OperationKind.ArrayInitializer) (Syntax: '{ 1, 2, 3 }') Element Values(3): IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Byte, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Byte, Constant: 2, IsImplicit) (Syntax: '2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2) (Syntax: '2') IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Byte, Constant: 3, IsImplicit) (Syntax: '3') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 3) (Syntax: '3') IArrayInitializer (1 elements) (OperationKind.ArrayInitializer) (Syntax: '{ { 4, 5, 6 } }') Element Values(1): IArrayInitializer (3 elements) (OperationKind.ArrayInitializer) (Syntax: '{ 4, 5, 6 }') Element Values(3): IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Byte, Constant: 4, IsImplicit) (Syntax: '4') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 4) (Syntax: '4') IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Byte, Constant: 5, IsImplicit) (Syntax: '5') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 5) (Syntax: '5') IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Byte, Constant: 6, IsImplicit) (Syntax: '6') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 6) (Syntax: '6') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationOfSingleDimensionalArrays() { string source = @" class C { public void F() { int[][] a = /*<bind>*/new int[][] { new[] { 1, 2, 3 }, new int[5] }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Int32[][]) (Syntax: 'new int[][] ... ew int[5] }') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'new int[][] ... ew int[5] }') Initializer: IArrayInitializer (2 elements) (OperationKind.ArrayInitializer) (Syntax: '{ new[] { 1 ... ew int[5] }') Element Values(2): IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Int32[]) (Syntax: 'new[] { 1, 2, 3 }') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 3, IsImplicit) (Syntax: 'new[] { 1, 2, 3 }') Initializer: IArrayInitializer (3 elements) (OperationKind.ArrayInitializer) (Syntax: '{ 1, 2, 3 }') Element Values(3): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 3) (Syntax: '3') IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Int32[]) (Syntax: 'new int[5]') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 5) (Syntax: '5') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationOfMultiDimensionalArrays() { string source = @" class C { public void F() { int[][,] a = /*<bind>*/new int[1][,]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Int32[][,]) (Syntax: 'new int[1][,]') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationOfImplicitlyTypedMultiDimensionalArrays_WithInitializer() { string source = @" class C { public void F() { var a = /*<bind>*/new[] { new[, ,] { { { 1, 2 } } }, new[, ,] { { { 3, 4 } } } }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Int32[][,,]) (Syntax: 'new[] { new ... , 4 } } } }') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'new[] { new ... , 4 } } } }') Initializer: IArrayInitializer (2 elements) (OperationKind.ArrayInitializer) (Syntax: '{ new[, ,] ... , 4 } } } }') Element Values(2): IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Int32[,,]) (Syntax: 'new[, ,] { ... 1, 2 } } }') Dimension Sizes(3): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new[, ,] { ... 1, 2 } } }') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new[, ,] { ... 1, 2 } } }') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'new[, ,] { ... 1, 2 } } }') Initializer: IArrayInitializer (1 elements) (OperationKind.ArrayInitializer) (Syntax: '{ { { 1, 2 } } }') Element Values(1): IArrayInitializer (1 elements) (OperationKind.ArrayInitializer) (Syntax: '{ { 1, 2 } }') Element Values(1): IArrayInitializer (2 elements) (OperationKind.ArrayInitializer) (Syntax: '{ 1, 2 }') Element Values(2): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2) (Syntax: '2') IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.Int32[,,]) (Syntax: 'new[, ,] { ... 3, 4 } } }') Dimension Sizes(3): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new[, ,] { ... 3, 4 } } }') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new[, ,] { ... 3, 4 } } }') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'new[, ,] { ... 3, 4 } } }') Initializer: IArrayInitializer (1 elements) (OperationKind.ArrayInitializer) (Syntax: '{ { { 3, 4 } } }') Element Values(1): IArrayInitializer (1 elements) (OperationKind.ArrayInitializer) (Syntax: '{ { 3, 4 } }') Element Values(1): IArrayInitializer (2 elements) (OperationKind.ArrayInitializer) (Syntax: '{ 3, 4 }') Element Values(2): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 3) (Syntax: '3') ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 4) (Syntax: '4') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ImplicitArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/18193"), WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationErrorCase_MissingDimension() { string source = @" class C { public void F() { var a = /*<bind>*/new string[]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationExpression (Dimension sizes: 0, Element Type: System.String) (OperationKind.ArrayCreationExpression, Type: System.String[], IsInvalid) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationErrorCase_InvalidInitializer() { string source = @" class C { public void F() { var a = /*<bind>*/new string[] { 1 }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.String[], IsInvalid) (Syntax: 'new string[] { 1 }') Dimension Sizes(1): ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'new string[] { 1 }') Initializer: IArrayInitializer (1 elements) (OperationKind.ArrayInitializer, IsInvalid) (Syntax: '{ 1 }') Element Values(1): IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.String, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralExpression (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0029: Cannot implicitly convert type 'int' to 'string' // var a = /*<bind>*/new string[] { 1 }/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "string").WithLocation(6, 42) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationErrorCase_MissingExplicitCast() { string source = @" class C { public void F(object b) { var a = /*<bind>*/new string[b]/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.String[], IsInvalid) (Syntax: 'new string[b]') Dimension Sizes(1): IConversionExpression (Implicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'b') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceExpression: b (OperationKind.ParameterReferenceExpression, Type: System.Object, IsInvalid) (Syntax: 'b') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0266: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?) // var a = /*<bind>*/new string[b]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "new string[b]").WithArguments("object", "int").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreation_InvocationExpressionAsDimension() { string source = @" class C { public void F() { var a = /*<bind>*/new string[M()]/*</bind>*/; } public int M() => 1; } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.String[]) (Syntax: 'new string[M()]') Dimension Sizes(1): IInvocationExpression ( System.Int32 C.M()) (OperationKind.InvocationExpression, Type: System.Int32) (Syntax: 'M()') Instance Receiver: IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: C, IsImplicit) (Syntax: 'M') Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreation_InvocationExpressionWithConversionAsDimension() { string source = @" class C { public void F() { var a = /*<bind>*/new string[(int)M()]/*</bind>*/; } public object M() => null; } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.String[]) (Syntax: 'new string[(int)M()]') Dimension Sizes(1): IConversionExpression (Explicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Int32) (Syntax: '(int)M()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationExpression ( System.Object C.M()) (OperationKind.InvocationExpression, Type: System.Object) (Syntax: 'M()') Instance Receiver: IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: C, IsImplicit) (Syntax: 'M') Arguments(0) Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationErrorCase_InvocationExpressionAsDimension() { string source = @" class C { public static void F() { var a = /*<bind>*/new string[M()]/*</bind>*/; } public object M() => null; } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.String[], IsInvalid) (Syntax: 'new string[M()]') Dimension Sizes(1): IInvocationExpression ( System.Object C.M()) (OperationKind.InvocationExpression, Type: System.Object, IsInvalid) (Syntax: 'M()') Instance Receiver: IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0120: An object reference is required for the non-static field, method, or property 'C.M()' // var a = /*<bind>*/new string[M()]/*</bind>*/; Diagnostic(ErrorCode.ERR_ObjectRequired, "M").WithArguments("C.M()").WithLocation(6, 38) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact, WorkItem(17596, "https://github.com/dotnet/roslyn/issues/17596")] public void ArrayCreationErrorCase_InvocationExpressionWithConversionAsDimension() { string source = @" class C { public void F() { var a = /*<bind>*/new string[(int)M()]/*</bind>*/; } public C M() => new C(); } "; string expectedOperationTree = @" IArrayCreationExpression (OperationKind.ArrayCreationExpression, Type: System.String[], IsInvalid) (Syntax: 'new string[(int)M()]') Dimension Sizes(1): IConversionExpression (Explicit, TryCast: False, Unchecked) (OperationKind.ConversionExpression, Type: System.Int32, IsInvalid) (Syntax: '(int)M()') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationExpression ( C C.M()) (OperationKind.InvocationExpression, Type: C, IsInvalid) (Syntax: 'M()') Instance Receiver: IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0030: Cannot convert type 'C' to 'int' // var a = /*<bind>*/new string[(int)M()]/*</bind>*/; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int)M()").WithArguments("C", "int").WithLocation(6, 38) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } } }
/// Credit BinaryX, SimonDarksideJ /// Sourced from - http://forum.unity3d.com/threads/scripts-useful-4-6-scripts-collection.264161/page-2#post-1945602 /// Updated by SimonDarksideJ - removed dependency on a custom ScrollRect script. Now implements drag interfaces and standard Scroll Rect. /// Updated by SimonDarksideJ - major refactoring on updating current position and scroll management using UnityEngine.EventSystems; namespace UnityEngine.UI.Extensions { [RequireComponent(typeof(ScrollRect))] [AddComponentMenu("Layout/Extensions/Vertical Scroll Snap")] public class VerticalScrollSnap : ScrollSnapBase, IEndDragHandler { void Start() { _isVertical = true; _childAnchorPoint = new Vector2(0.5f,0); _currentPage = StartingScreen; UpdateLayout(); } void Update() { if (!_lerp && _scroll_rect.velocity == Vector2.zero) { if (!_settled && !_pointerDown) { if (!IsRectSettledOnaPage(_screensContainer.localPosition)) { ScrollToClosestElement(); } } return; } else if (_lerp) { _screensContainer.localPosition = Vector3.Lerp(_screensContainer.localPosition, _lerp_target, transitionSpeed * Time.deltaTime); if (Vector3.Distance(_screensContainer.localPosition, _lerp_target) < 0.1f) { _lerp = false; EndScreenChange(); } } CurrentPage = GetPageforPosition(_screensContainer.localPosition); //If the container is moving check if it needs to settle on a page if (!_pointerDown) { if (_scroll_rect.velocity.y > 0.01 || _scroll_rect.velocity.y < -0.01) { // if the pointer is released and is moving slower than the threshold, then just land on a page if (IsRectMovingSlowerThanThreshold(0)) { ScrollToClosestElement(); } } } } private bool IsRectMovingSlowerThanThreshold(float startingSpeed) { return (_scroll_rect.velocity.y > startingSpeed && _scroll_rect.velocity.y < SwipeVelocityThreshold) || (_scroll_rect.velocity.y < startingSpeed && _scroll_rect.velocity.y > -SwipeVelocityThreshold); } public void DistributePages() { _screens = _screensContainer.childCount; _scroll_rect.verticalNormalizedPosition = 0; float _offset = 0; float _dimension = 0; Rect panelDimensions = gameObject.GetComponent<RectTransform>().rect; float currentYPosition = 0; var pageStepValue = _childSize = (int)panelDimensions.height * ((PageStep == 0) ? 3 : PageStep); for (int i = 0; i < _screensContainer.transform.childCount; i++) { RectTransform child = _screensContainer.transform.GetChild(i).gameObject.GetComponent<RectTransform>(); currentYPosition = _offset + i * pageStepValue; child.sizeDelta = new Vector2(panelDimensions.width, panelDimensions.height); child.anchoredPosition = new Vector2(0f, currentYPosition); child.anchorMin = child.anchorMax = child.pivot = _childAnchorPoint; } _dimension = currentYPosition + _offset * -1; _screensContainer.GetComponent<RectTransform>().offsetMax = new Vector2(0f, _dimension); } /// <summary> /// Add a new child to this Scroll Snap and recalculate it's children /// </summary> /// <param name="GO">GameObject to add to the ScrollSnap</param> public void AddChild(GameObject GO) { AddChild(GO, false); } /// <summary> /// Add a new child to this Scroll Snap and recalculate it's children /// </summary> /// <param name="GO">GameObject to add to the ScrollSnap</param> /// <param name="WorldPositionStays">Should the world position be updated to it's parent transform?</param> public void AddChild(GameObject GO, bool WorldPositionStays) { _scroll_rect.verticalNormalizedPosition = 0; GO.transform.SetParent(_screensContainer, WorldPositionStays); InitialiseChildObjectsFromScene(); DistributePages(); if (MaskArea) UpdateVisible(); SetScrollContainerPosition(); } /// <summary> /// Remove a new child to this Scroll Snap and recalculate it's children /// *Note, this is an index address (0-x) /// </summary> /// <param name="index"></param> /// <param name="ChildRemoved"></param> public void RemoveChild(int index, out GameObject ChildRemoved) { ChildRemoved = null; if (index < 0 || index > _screensContainer.childCount) { return; } _scroll_rect.verticalNormalizedPosition = 0; Transform child = _screensContainer.transform.GetChild(index); child.SetParent(null); ChildRemoved = child.gameObject; InitialiseChildObjectsFromScene(); DistributePages(); if (MaskArea) UpdateVisible(); if (_currentPage > _screens - 1) { CurrentPage = _screens - 1; } SetScrollContainerPosition(); } /// <summary> /// Remove all children from this ScrollSnap /// </summary> /// <param name="ChildrenRemoved"></param> public void RemoveAllChildren(out GameObject[] ChildrenRemoved) { var _screenCount = _screensContainer.childCount; ChildrenRemoved = new GameObject[_screenCount]; for (int i = _screenCount - 1; i >= 0; i--) { ChildrenRemoved[i] = _screensContainer.GetChild(i).gameObject; ChildrenRemoved[i].transform.SetParent(null); } _scroll_rect.verticalNormalizedPosition = 0; CurrentPage = 0; InitialiseChildObjectsFromScene(); DistributePages(); if (MaskArea) UpdateVisible(); } private void SetScrollContainerPosition() { _scrollStartPosition = _screensContainer.localPosition.y; _scroll_rect.verticalNormalizedPosition = (float)(_currentPage) / (_screens - 1); } /// <summary> /// used for changing / updating between screen resolutions /// </summary> public void UpdateLayout() { _lerp = false; DistributePages(); if (MaskArea) UpdateVisible(); SetScrollContainerPosition(); } private void OnRectTransformDimensionsChange() { if (_childAnchorPoint != Vector2.zero) { UpdateLayout(); } } #region Interfaces /// <summary> /// Release screen to swipe /// </summary> /// <param name="eventData"></param> public void OnEndDrag(PointerEventData eventData) { _pointerDown = false; if (_scroll_rect.vertical) { if (UseFastSwipe) { //If using fastswipe - then a swipe does page next / previous if ((_scroll_rect.velocity.y > 0 && _scroll_rect.velocity.y > FastSwipeThreshold) || _scroll_rect.velocity.y < 0 && _scroll_rect.velocity.y < -FastSwipeThreshold) { _scroll_rect.velocity = Vector3.zero; if (_startPosition.y - _screensContainer.localPosition.y > 0) { NextScreen(); } else { PreviousScreen(); } } else { ScrollToClosestElement(); } } } } #endregion } }
// // IsolatedStorageFileCas.cs - CAS unit tests for // System.IO.IsolatedStorage.IsolatedStorageFile // // Author: // Sebastien Pouliot <sebastien@ximian.com> // // Copyright (C) 2005 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 NUnit.Framework; using System; using System.IO; using System.IO.IsolatedStorage; using System.Security; using System.Security.Permissions; namespace MonoCasTests.System.IO.IsolatedStorageTest { [TestFixture] [Category ("CAS")] public class IsolatedStorageFileCas { [SetUp] public void SetUp () { if (!SecurityManager.SecurityEnabled) Assert.Ignore ("SecurityManager.SecurityEnabled is OFF"); } // use the caller stack to execute some read operations private void Read (IsolatedStorageFile isf) { Assert.IsNotNull (isf.GetDirectoryNames ("*"), "GetDirectoryNames"); Assert.IsNotNull (isf.GetFileNames ("*"), "GetFileNames"); try { Assert.IsTrue (isf.CurrentSize >= 0, "CurrentSize"); Assert.IsTrue (isf.MaximumSize >= isf.CurrentSize, "MaximumSize"); } catch (InvalidOperationException) { // roaming } } // use the caller stack to execute some write operations private void Write (IsolatedStorageFile isf) { isf.CreateDirectory ("testdir"); string filename = Path.Combine ("testdir", "file"); using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream (filename, FileMode.Create, isf)) { } isf.DeleteFile (filename); isf.DeleteDirectory ("testdir"); try { isf.Remove (); } catch (IsolatedStorageException) { // fx 1.x doesn't like removing when things "could" still be in use } } #if NET_2_0 [Test] [IsolatedStorageFilePermission (SecurityAction.Deny, UsageAllowed = IsolatedStorageContainment.ApplicationIsolationByMachine)] [ExpectedException (typeof (SecurityException))] [Ignore ("no manifest")] public void GetMachineStoreForApplication_Fail () { IsolatedStorageFile isf = IsolatedStorageFile.GetMachineStoreForApplication (); } [Test] [Ignore ("no manifest")] [IsolatedStorageFilePermission (SecurityAction.PermitOnly, UsageAllowed = IsolatedStorageContainment.ApplicationIsolationByMachine)] public void GetMachineStoreForApplication_Pass () { IsolatedStorageFile isf = IsolatedStorageFile.GetMachineStoreForApplication (); } [Test] [IsolatedStorageFilePermission (SecurityAction.Deny, UsageAllowed = IsolatedStorageContainment.AssemblyIsolationByMachine)] [ExpectedException (typeof (SecurityException))] public void GetMachineStoreForAssembly_Fail () { IsolatedStorageFile isf = IsolatedStorageFile.GetMachineStoreForAssembly (); } [Test] [IsolatedStorageFilePermission (SecurityAction.PermitOnly, UsageAllowed = IsolatedStorageContainment.AssemblyIsolationByMachine)] public void GetMachineStoreForAssembly_Pass () { IsolatedStorageFile isf = IsolatedStorageFile.GetMachineStoreForAssembly (); Read (isf); Write (isf); isf.Dispose (); isf.Close (); } [Test] [IsolatedStorageFilePermission (SecurityAction.PermitOnly, UsageAllowed = IsolatedStorageContainment.AdministerIsolatedStorageByUser)] public void GetMachineStoreForAssembly_Administer () { IsolatedStorageFile isf = IsolatedStorageFile.GetMachineStoreForAssembly (); Read (isf); Write (isf); isf.Dispose (); isf.Close (); } [Test] [IsolatedStorageFilePermission (SecurityAction.Deny, UsageAllowed = IsolatedStorageContainment.DomainIsolationByMachine)] [ExpectedException (typeof (SecurityException))] public void GetMachineStoreForDomain_Fail () { IsolatedStorageFile isf = IsolatedStorageFile.GetMachineStoreForDomain (); } [Test] [IsolatedStorageFilePermission (SecurityAction.PermitOnly, UsageAllowed = IsolatedStorageContainment.DomainIsolationByMachine)] public void GetMachineStoreForDomain_Pass () { IsolatedStorageFile isf = IsolatedStorageFile.GetMachineStoreForDomain (); Read (isf); Write (isf); isf.Dispose (); isf.Close (); } [Test] [IsolatedStorageFilePermission (SecurityAction.PermitOnly, UsageAllowed = IsolatedStorageContainment.AdministerIsolatedStorageByUser)] public void GetMachineStoreForDomain_Administer () { IsolatedStorageFile isf = IsolatedStorageFile.GetMachineStoreForDomain (); Read (isf); Write (isf); isf.Dispose (); isf.Close (); } [Test] [IsolatedStorageFilePermission (SecurityAction.Deny, UsageAllowed = IsolatedStorageContainment.ApplicationIsolationByUser)] [ExpectedException (typeof (SecurityException))] [Ignore ("no manifest")] public void GetUserStoreForApplication_Fail () { IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication (); } [Test] [Ignore ("no manifest")] [IsolatedStorageFilePermission (SecurityAction.PermitOnly, UsageAllowed = IsolatedStorageContainment.ApplicationIsolationByUser)] public void GetUserStoreForApplication_Pass () { IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication (); } #endif [Test] [IsolatedStorageFilePermission (SecurityAction.Deny, UsageAllowed = IsolatedStorageContainment.AssemblyIsolationByUser)] [ExpectedException (typeof (SecurityException))] public void GetUserStoreForAssembly_Fail () { IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly (); } [Test] [IsolatedStorageFilePermission (SecurityAction.PermitOnly, UsageAllowed = IsolatedStorageContainment.AssemblyIsolationByUser)] public void GetUserStoreForAssembly_Pass () { IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly (); Read (isf); Write (isf); isf.Dispose (); isf.Close (); } [Test] [IsolatedStorageFilePermission (SecurityAction.Deny, UsageAllowed = IsolatedStorageContainment.AssemblyIsolationByRoamingUser)] [ExpectedException (typeof (SecurityException))] public void GetUserStoreForAssembly_Roaming_Fail () { IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly (); } [Test] [IsolatedStorageFilePermission (SecurityAction.PermitOnly, UsageAllowed = IsolatedStorageContainment.AdministerIsolatedStorageByUser)] public void GetUserStoreForAssembly_Roaming_Pass () { IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly (); Read (isf); Write (isf); isf.Dispose (); isf.Close (); } [Test] [IsolatedStorageFilePermission (SecurityAction.PermitOnly, UsageAllowed = IsolatedStorageContainment.AssemblyIsolationByRoamingUser)] public void GetUserStoreForAssembly_Administer () { IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForAssembly (); Read (isf); Write (isf); isf.Dispose (); isf.Close (); } [Test] [IsolatedStorageFilePermission (SecurityAction.Deny, UsageAllowed = IsolatedStorageContainment.DomainIsolationByUser)] [ExpectedException (typeof (SecurityException))] public void GetUserStoreForDomain_Fail () { IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForDomain (); } [Test] [IsolatedStorageFilePermission (SecurityAction.PermitOnly, UsageAllowed = IsolatedStorageContainment.DomainIsolationByUser)] public void GetUserStoreForDomain_Pass () { IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForDomain (); Read (isf); Write (isf); isf.Dispose (); isf.Close (); } [Test] [IsolatedStorageFilePermission (SecurityAction.Deny, UsageAllowed = IsolatedStorageContainment.DomainIsolationByRoamingUser)] [ExpectedException (typeof (SecurityException))] public void GetUserStoreForDomain_Roaming_Fail () { IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForDomain (); } [Test] [IsolatedStorageFilePermission (SecurityAction.PermitOnly, UsageAllowed = IsolatedStorageContainment.DomainIsolationByRoamingUser)] public void GetUserStoreForDomain_Roaming_Pass () { IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForDomain (); Read (isf); Write (isf); isf.Dispose (); isf.Close (); } [Test] [IsolatedStorageFilePermission (SecurityAction.PermitOnly, UsageAllowed = IsolatedStorageContainment.AdministerIsolatedStorageByUser)] public void GetUserStoreForDomain_Administer () { IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForDomain (); Read (isf); Write (isf); isf.Dispose (); isf.Close (); } } }
using System; using System.Collections; using System.IO; using System.Text; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Encoders; namespace Org.BouncyCastle.Asn1.Utilities { public sealed class Asn1Dump { private static readonly string NewLine = Platform.NewLine; private Asn1Dump() { } private const string Tab = " "; private const int SampleSize = 32; /** * dump a Der object as a formatted string with indentation * * @param obj the Asn1Object to be dumped out. */ private static string AsString( string indent, bool verbose, Asn1Object obj) { if (obj is Asn1Sequence) { StringBuilder buf = new StringBuilder(indent); string tab = indent + Tab; if (obj is BerSequence) { buf.Append("BER Sequence"); } else if (obj is DerSequence) { buf.Append("DER Sequence"); } else { buf.Append("Sequence"); } buf.Append(NewLine); foreach (Asn1Encodable o in ((Asn1Sequence)obj)) { if (o == null || o is Asn1Null) { buf.Append(tab); buf.Append("NULL"); buf.Append(NewLine); } else { buf.Append(AsString(tab, verbose, o.ToAsn1Object())); } } return buf.ToString(); } else if (obj is DerTaggedObject) { StringBuilder buf = new StringBuilder(); string tab = indent + Tab; buf.Append(indent); if (obj is BerTaggedObject) { buf.Append("BER Tagged ["); } else { buf.Append("Tagged ["); } DerTaggedObject o = (DerTaggedObject)obj; buf.Append(((int)o.TagNo).ToString()); buf.Append(']'); if (!o.IsExplicit()) { buf.Append(" IMPLICIT "); } buf.Append(NewLine); if (o.IsEmpty()) { buf.Append(tab); buf.Append("EMPTY"); buf.Append(NewLine); } else { buf.Append(AsString(tab, verbose, o.GetObject())); } return buf.ToString(); } else if (obj is BerSet) { StringBuilder buf = new StringBuilder(); string tab = indent + Tab; buf.Append(indent); buf.Append("BER Set"); buf.Append(NewLine); foreach (Asn1Encodable o in ((Asn1Set)obj)) { if (o == null) { buf.Append(tab); buf.Append("NULL"); buf.Append(NewLine); } else { buf.Append(AsString(tab, verbose, o.ToAsn1Object())); } } return buf.ToString(); } else if (obj is DerSet) { StringBuilder buf = new StringBuilder(); string tab = indent + Tab; buf.Append(indent); buf.Append("DER Set"); buf.Append(NewLine); foreach (Asn1Encodable o in ((Asn1Set)obj)) { if (o == null) { buf.Append(tab); buf.Append("NULL"); buf.Append(NewLine); } else { buf.Append(AsString(tab, verbose, o.ToAsn1Object())); } } return buf.ToString(); } else if (obj is DerObjectIdentifier) { return indent + "ObjectIdentifier(" + ((DerObjectIdentifier)obj).Id + ")" + NewLine; } else if (obj is DerBoolean) { return indent + "Boolean(" + ((DerBoolean)obj).IsTrue + ")" + NewLine; } else if (obj is DerInteger) { return indent + "Integer(" + ((DerInteger)obj).Value + ")" + NewLine; } else if (obj is BerOctetString) { byte[] octets = ((Asn1OctetString)obj).GetOctets(); string extra = verbose ? dumpBinaryDataAsString(indent, octets) : ""; return indent + "BER Octet String" + "[" + octets.Length + "] " + extra + NewLine; } else if (obj is DerOctetString) { byte[] octets = ((Asn1OctetString)obj).GetOctets(); string extra = verbose ? dumpBinaryDataAsString(indent, octets) : ""; return indent + "DER Octet String" + "[" + octets.Length + "] " + extra + NewLine; } else if (obj is DerBitString) { DerBitString bt = (DerBitString)obj; byte[] bytes = bt.GetBytes(); string extra = verbose ? dumpBinaryDataAsString(indent, bytes) : ""; return indent + "DER Bit String" + "[" + bytes.Length + ", " + bt.PadBits + "] " + extra + NewLine; } else if (obj is DerIA5String) { return indent + "IA5String(" + ((DerIA5String)obj).GetString() + ") " + NewLine; } else if (obj is DerUtf8String) { return indent + "UTF8String(" + ((DerUtf8String)obj).GetString() + ") " + NewLine; } else if (obj is DerPrintableString) { return indent + "PrintableString(" + ((DerPrintableString)obj).GetString() + ") " + NewLine; } else if (obj is DerVisibleString) { return indent + "VisibleString(" + ((DerVisibleString)obj).GetString() + ") " + NewLine; } else if (obj is DerBmpString) { return indent + "BMPString(" + ((DerBmpString)obj).GetString() + ") " + NewLine; } else if (obj is DerT61String) { return indent + "T61String(" + ((DerT61String)obj).GetString() + ") " + NewLine; } else if (obj is DerUtcTime) { return indent + "UTCTime(" + ((DerUtcTime)obj).TimeString + ") " + NewLine; } else if (obj is DerGeneralizedTime) { return indent + "GeneralizedTime(" + ((DerGeneralizedTime)obj).GetTime() + ") " + NewLine; } else if (obj is DerUnknownTag) { byte[] hex = Hex.Encode(((DerUnknownTag)obj).GetData()); return indent + "Unknown " + ((int)((DerUnknownTag)obj).Tag).ToString("X") + " " + Encoding.ASCII.GetString(hex, 0, hex.Length) + NewLine; } else if (obj is BerApplicationSpecific) { return outputApplicationSpecific("BER", indent, verbose, (BerApplicationSpecific)obj); } else if (obj is DerApplicationSpecific) { return outputApplicationSpecific("DER", indent, verbose, (DerApplicationSpecific)obj); } else { return indent + obj.ToString() + NewLine; } } private static string outputApplicationSpecific( string type, string indent, bool verbose, DerApplicationSpecific app) { StringBuilder buf = new StringBuilder(); if (app.IsConstructed()) { try { Asn1Sequence s = Asn1Sequence.GetInstance(app.GetObject(Asn1Tags.Sequence)); buf.Append(indent + type + " ApplicationSpecific[" + app.ApplicationTag + "]" + NewLine); foreach (Asn1Encodable ae in s) { buf.Append(AsString(indent + Tab, verbose, ae.ToAsn1Object())); } } catch (IOException e) { buf.Append(e); } return buf.ToString(); } return indent + type + " ApplicationSpecific[" + app.ApplicationTag + "] (" + Encoding.ASCII.GetString(Hex.Encode(app.GetContents())) + ")" + NewLine; } [Obsolete("Use version accepting Asn1Encodable")] public static string DumpAsString( object obj) { if (obj is Asn1Encodable) { return AsString("", false, ((Asn1Encodable)obj).ToAsn1Object()); } return "unknown object type " + obj.ToString(); } /** * dump out a DER object as a formatted string, in non-verbose mode * * @param obj the Asn1Encodable to be dumped out. * @return the resulting string. */ public static string DumpAsString( Asn1Encodable obj) { return DumpAsString(obj, false); } /** * Dump out the object as a string * * @param obj the Asn1Encodable to be dumped out. * @param verbose if true, dump out the contents of octet and bit strings. * @return the resulting string. */ public static string DumpAsString( Asn1Encodable obj, bool verbose) { return AsString("", verbose, obj.ToAsn1Object()); } private static string dumpBinaryDataAsString(string indent, byte[] bytes) { indent += Tab; StringBuilder buf = new StringBuilder(NewLine); for (int i = 0; i < bytes.Length; i += SampleSize) { if (bytes.Length - i > SampleSize) { buf.Append(indent); buf.Append(Encoding.ASCII.GetString(Hex.Encode(bytes, i, SampleSize))); buf.Append(Tab); buf.Append(calculateAscString(bytes, i, SampleSize)); buf.Append(NewLine); } else { buf.Append(indent); buf.Append(Encoding.ASCII.GetString(Hex.Encode(bytes, i, bytes.Length - i))); for (int j = bytes.Length - i; j != SampleSize; j++) { buf.Append(" "); } buf.Append(Tab); buf.Append(calculateAscString(bytes, i, bytes.Length - i)); buf.Append(NewLine); } } return buf.ToString(); } private static string calculateAscString( byte[] bytes, int off, int len) { StringBuilder buf = new StringBuilder(); for (int i = off; i != off + len; i++) { char c = (char)bytes[i]; if (c >= ' ' && c <= '~') { buf.Append(c); } } return buf.ToString(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.CallStack; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Metadata; using Microsoft.VisualStudio.Debugger.Symbols; using Roslyn.Utilities; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; using TypeCode = Microsoft.VisualStudio.Debugger.Metadata.TypeCode; namespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation { public class DkmClrValue : DkmDataContainer { internal DkmClrValue( object value, object hostObjectValue, DkmClrType type, string alias, IDkmClrFormatter formatter, DkmEvaluationResultFlags evalFlags, DkmClrValueFlags valueFlags, DkmEvaluationResultCategory category = default(DkmEvaluationResultCategory), DkmEvaluationResultAccessType access = default(DkmEvaluationResultAccessType), ulong nativeComPointer = 0) { Debug.Assert(!type.GetLmrType().IsTypeVariables() || (valueFlags == DkmClrValueFlags.Synthetic)); Debug.Assert((alias == null) || evalFlags.Includes(DkmEvaluationResultFlags.HasObjectId)); // The "real" DkmClrValue will always have a value of zero for null pointers. Debug.Assert(!type.GetLmrType().IsPointer || (value != null)); this.RawValue = value; this.HostObjectValue = hostObjectValue; this.Type = type; _formatter = formatter; this.Alias = alias; this.EvalFlags = evalFlags; this.ValueFlags = valueFlags; this.Category = category; this.Access = access; this.NativeComPointer = nativeComPointer; } public readonly DkmEvaluationResultFlags EvalFlags; public readonly DkmClrValueFlags ValueFlags; public readonly DkmClrType Type; public readonly DkmStackWalkFrame StackFrame; public readonly DkmEvaluationResultCategory Category; public readonly DkmEvaluationResultAccessType Access; public readonly DkmEvaluationResultStorageType StorageType; public readonly DkmEvaluationResultTypeModifierFlags TypeModifierFlags; public readonly DkmDataAddress Address; public readonly object HostObjectValue; public readonly string Alias; public readonly ulong NativeComPointer; private readonly IDkmClrFormatter _formatter; internal readonly object RawValue; public void Close() { } public DkmClrValue Dereference(DkmInspectionContext inspectionContext) { if (inspectionContext == null) { throw new ArgumentNullException(nameof(inspectionContext)); } if (RawValue == null) { throw new InvalidOperationException("Cannot dereference invalid value"); } var elementType = this.Type.GetLmrType().GetElementType(); var evalFlags = DkmEvaluationResultFlags.None; var valueFlags = DkmClrValueFlags.None; object value; try { var intPtr = Environment.Is64BitProcess ? new IntPtr((long)RawValue) : new IntPtr((int)RawValue); value = Dereference(intPtr, elementType); } catch (Exception e) { value = e; evalFlags |= DkmEvaluationResultFlags.ExceptionThrown; } var valueType = new DkmClrType(this.Type.RuntimeInstance, (value == null || elementType.IsPointer) ? elementType : (TypeImpl)value.GetType()); return new DkmClrValue( value, value, valueType, alias: null, formatter: _formatter, evalFlags: evalFlags, valueFlags: valueFlags, category: DkmEvaluationResultCategory.Other, access: DkmEvaluationResultAccessType.None); } public bool IsNull { get { if (this.IsError()) { // Should not be checking value for Error. (Throw rather than // assert since the property may be called during debugging.) throw new InvalidOperationException(); } var lmrType = Type.GetLmrType(); return ((RawValue == null) && !lmrType.IsValueType) || (lmrType.IsPointer && (Convert.ToInt64(RawValue) == 0)); } } internal static object GetHostObjectValue(Type lmrType, object rawValue) { // NOTE: This is just a "for testing purposes" approximation of what the real DkmClrValue.HostObjectValue // will return. We will need to update this implementation to match the real behavior we add // specialized support for additional types. var typeCode = Metadata.Type.GetTypeCode(lmrType); return (lmrType.IsPointer || lmrType.IsEnum || typeCode != TypeCode.DateTime || typeCode != TypeCode.Object) ? rawValue : null; } public string GetValueString(DkmInspectionContext inspectionContext, ReadOnlyCollection<string> formatSpecifiers) { if (inspectionContext == null) { throw new ArgumentNullException(nameof(inspectionContext)); } // The real version does some sort of dynamic dispatch that ultimately calls this method. return _formatter.GetValueString(this, inspectionContext, formatSpecifiers); } public bool HasUnderlyingString(DkmInspectionContext inspectionContext) { if (inspectionContext == null) { throw new ArgumentNullException(nameof(inspectionContext)); } return _formatter.HasUnderlyingString(this, inspectionContext); } public string GetUnderlyingString(DkmInspectionContext inspectionContext) { if (inspectionContext == null) { throw new ArgumentNullException(nameof(inspectionContext)); } return _formatter.GetUnderlyingString(this, inspectionContext); } public string EvaluateToString(DkmInspectionContext inspectionContext) { if (inspectionContext == null) { throw new ArgumentNullException(nameof(inspectionContext)); } // This is a rough approximation of the real functionality. Basically, // if object.ToString is not overridden, we return null and it is the // caller's responsibility to compute a string. var type = this.Type.GetLmrType(); while (type != null) { if (type.IsObject() || type.IsValueType()) { return null; } // We should check the signature and virtual-ness, but this is // close enough for testing. if (type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Any(m => m.Name == "ToString")) { break; } type = type.BaseType; } var rawValue = RawValue; Debug.Assert(rawValue != null || this.Type.GetLmrType().IsVoid(), "In our mock system, this should only happen for void."); return rawValue == null ? null : rawValue.ToString(); } /// <remarks> /// Very simple expression evaluation (may not support all syntax supported by Concord). /// </remarks> public void EvaluateDebuggerDisplayString(DkmWorkList workList, DkmInspectionContext inspectionContext, DkmClrType targetType, string formatString, DkmCompletionRoutine<DkmEvaluateDebuggerDisplayStringAsyncResult> completionRoutine) { Debug.Assert(!this.IsNull, "Not supported by VIL"); if (inspectionContext == null) { throw new ArgumentNullException(nameof(inspectionContext)); } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; int openPos = -1; int length = formatString.Length; for (int i = 0; i < length; i++) { char ch = formatString[i]; if (ch == '{') { if (openPos >= 0) { throw new ArgumentException(string.Format("Nested braces in '{0}'", formatString)); } openPos = i; } else if (ch == '}') { if (openPos < 0) { throw new ArgumentException(string.Format("Unmatched closing brace in '{0}'", formatString)); } string name = formatString.Substring(openPos + 1, i - openPos - 1); openPos = -1; var formatSpecifiers = Formatter.NoFormatSpecifiers; int commaIndex = name.IndexOf(','); if (commaIndex >= 0) { var rawFormatSpecifiers = name.Substring(commaIndex + 1).Split(','); var trimmedFormatSpecifiers = ArrayBuilder<string>.GetInstance(rawFormatSpecifiers.Length); trimmedFormatSpecifiers.AddRange(rawFormatSpecifiers.Select(fs => fs.Trim())); formatSpecifiers = trimmedFormatSpecifiers.ToImmutableAndFree(); foreach (var formatSpecifier in formatSpecifiers) { if (formatSpecifier == "nq") { inspectionContext = new DkmInspectionContext(_formatter, inspectionContext.EvaluationFlags | DkmEvaluationFlags.NoQuotes, inspectionContext.Radix, inspectionContext.RuntimeInstance); } // If we need to support additional format specifiers, add them here... } name = name.Substring(0, commaIndex); } var type = ((TypeImpl)this.Type.GetLmrType()).Type; const System.Reflection.BindingFlags bindingFlags = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static; DkmClrValue exprValue; var appDomain = this.Type.AppDomain; var field = type.GetField(name, bindingFlags); if (field != null) { var fieldValue = field.GetValue(RawValue); exprValue = new DkmClrValue( fieldValue, fieldValue, DkmClrType.Create(appDomain, (TypeImpl)((fieldValue == null) ? field.FieldType : fieldValue.GetType())), alias: null, formatter: _formatter, evalFlags: GetEvaluationResultFlags(fieldValue), valueFlags: DkmClrValueFlags.None); } else { var property = type.GetProperty(name, bindingFlags); if (property != null) { var propertyValue = property.GetValue(RawValue); exprValue = new DkmClrValue( propertyValue, propertyValue, DkmClrType.Create(appDomain, (TypeImpl)((propertyValue == null) ? property.PropertyType : propertyValue.GetType())), alias: null, formatter: _formatter, evalFlags: GetEvaluationResultFlags(propertyValue), valueFlags: DkmClrValueFlags.None); } else { var openParenIndex = name.IndexOf('('); if (openParenIndex >= 0) { name = name.Substring(0, openParenIndex); } var method = type.GetMethod(name, bindingFlags); // The real implementation requires parens on method invocations, so // we'll return error if there wasn't at least an open paren... if ((openParenIndex >= 0) && method != null) { var methodValue = method.Invoke(RawValue, new object[] { }); exprValue = new DkmClrValue( methodValue, methodValue, DkmClrType.Create(appDomain, (TypeImpl)((methodValue == null) ? method.ReturnType : methodValue.GetType())), alias: null, formatter: _formatter, evalFlags: GetEvaluationResultFlags(methodValue), valueFlags: DkmClrValueFlags.None); } else { var stringValue = "Problem evaluating expression"; var stringType = DkmClrType.Create(appDomain, (TypeImpl)typeof(string)); exprValue = new DkmClrValue( stringValue, stringValue, stringType, alias: null, formatter: _formatter, evalFlags: DkmEvaluationResultFlags.None, valueFlags: DkmClrValueFlags.Error); } } } builder.Append(exprValue.GetValueString(inspectionContext, formatSpecifiers)); // Re-enter the formatter. } else if (openPos < 0) { builder.Append(ch); } } if (openPos >= 0) { throw new ArgumentException(string.Format("Unmatched open brace in '{0}'", formatString)); } workList.AddWork(() => completionRoutine(new DkmEvaluateDebuggerDisplayStringAsyncResult(pooled.ToStringAndFree()))); } public DkmClrValue GetMemberValue(string MemberName, int MemberType, string ParentTypeName, DkmInspectionContext InspectionContext) { if (InspectionContext == null) { throw new ArgumentNullException(nameof(InspectionContext)); } if (this.IsError()) { throw new InvalidOperationException(); } var runtime = this.Type.RuntimeInstance; var getMemberValue = runtime.GetMemberValue; if (getMemberValue != null) { var memberValue = getMemberValue(this, MemberName); if (memberValue != null) { return memberValue; } } var declaringType = this.Type.GetLmrType(); if (ParentTypeName != null) { declaringType = GetAncestorType(declaringType, ParentTypeName); Debug.Assert(declaringType != null); } // Special cases for nullables if (declaringType.IsNullable()) { if (MemberName == InternalWellKnownMemberNames.NullableHasValue) { // In our mock implementation, RawValue is null for null nullables, // so we have to compute HasValue some other way. var boolValue = RawValue != null; var boolType = runtime.GetType((TypeImpl)typeof(bool)); return new DkmClrValue( boolValue, boolValue, type: boolType, alias: null, formatter: _formatter, evalFlags: DkmEvaluationResultFlags.None, valueFlags: DkmClrValueFlags.None, category: DkmEvaluationResultCategory.Property, access: DkmEvaluationResultAccessType.Public); } else if (MemberName == InternalWellKnownMemberNames.NullableValue) { // In our mock implementation, RawValue is of type T rather than // Nullable<T> for nullables, so we'll just return that value // (no need to unwrap by getting "value" field). var valueType = runtime.GetType((TypeImpl)RawValue.GetType()); return new DkmClrValue( RawValue, RawValue, type: valueType, alias: null, formatter: _formatter, evalFlags: DkmEvaluationResultFlags.None, valueFlags: DkmClrValueFlags.None, category: DkmEvaluationResultCategory.Property, access: DkmEvaluationResultAccessType.Public); } } Type declaredType; object value; var evalFlags = DkmEvaluationResultFlags.None; var category = DkmEvaluationResultCategory.Other; var access = DkmEvaluationResultAccessType.None; const BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; switch ((MemberTypes)MemberType) { case MemberTypes.Field: var field = declaringType.GetField(MemberName, bindingFlags); declaredType = field.FieldType; category = DkmEvaluationResultCategory.Data; access = GetFieldAccess(field); if (field.Attributes.HasFlag(System.Reflection.FieldAttributes.Literal) || field.Attributes.HasFlag(System.Reflection.FieldAttributes.InitOnly)) { evalFlags |= DkmEvaluationResultFlags.ReadOnly; } try { value = field.GetValue(RawValue); } catch (System.Reflection.TargetInvocationException e) { var exception = e.InnerException; return new DkmClrValue( exception, exception, type: runtime.GetType((TypeImpl)exception.GetType()), alias: null, formatter: _formatter, evalFlags: evalFlags | DkmEvaluationResultFlags.ExceptionThrown, valueFlags: DkmClrValueFlags.None, category: category, access: access); } break; case MemberTypes.Property: var property = declaringType.GetProperty(MemberName, bindingFlags); declaredType = property.PropertyType; category = DkmEvaluationResultCategory.Property; access = GetPropertyAccess(property); if (property.GetSetMethod(nonPublic: true) == null) { evalFlags |= DkmEvaluationResultFlags.ReadOnly; } try { value = property.GetValue(RawValue, bindingFlags, null, null, null); } catch (System.Reflection.TargetInvocationException e) { var exception = e.InnerException; return new DkmClrValue( exception, exception, type: runtime.GetType((TypeImpl)exception.GetType()), alias: null, formatter: _formatter, evalFlags: evalFlags | DkmEvaluationResultFlags.ExceptionThrown, valueFlags: DkmClrValueFlags.None, category: category, access: access); } break; default: throw ExceptionUtilities.UnexpectedValue((MemberTypes)MemberType); } Type type; if (value is System.Reflection.Pointer) { value = UnboxPointer(value); type = declaredType; } else if (value == null || declaredType.IsNullable()) { type = declaredType; } else { type = (TypeImpl)value.GetType(); } return new DkmClrValue( value, value, type: runtime.GetType(type), alias: null, formatter: _formatter, evalFlags: evalFlags, valueFlags: DkmClrValueFlags.None, category: category, access: access); } internal static unsafe object UnboxPointer(object value) { unsafe { if (Environment.Is64BitProcess) { return (long)System.Reflection.Pointer.Unbox(value); } else { return (int)System.Reflection.Pointer.Unbox(value); } } } public DkmClrValue GetArrayElement(int[] indices, DkmInspectionContext inspectionContext) { if (inspectionContext == null) { throw new ArgumentNullException(nameof(inspectionContext)); } var array = (System.Array)RawValue; var element = array.GetValue(indices); var type = DkmClrType.Create(this.Type.AppDomain, (TypeImpl)((element == null) ? array.GetType().GetElementType() : element.GetType())); return new DkmClrValue( element, element, type: type, alias: null, formatter: _formatter, evalFlags: DkmEvaluationResultFlags.None, valueFlags: DkmClrValueFlags.None); } public ReadOnlyCollection<int> ArrayDimensions { get { var array = (Array)RawValue; if (array == null) { return null; } int rank = array.Rank; var builder = ArrayBuilder<int>.GetInstance(rank); for (int i = 0; i < rank; i++) { builder.Add(array.GetUpperBound(i) - array.GetLowerBound(i) + 1); } return builder.ToImmutableAndFree(); } } public ReadOnlyCollection<int> ArrayLowerBounds { get { var array = (Array)RawValue; if (array == null) { return null; } int rank = array.Rank; var builder = ArrayBuilder<int>.GetInstance(rank); for (int i = 0; i < rank; i++) { builder.Add(array.GetLowerBound(i)); } return builder.ToImmutableAndFree(); } } public DkmClrValue InstantiateProxyType(DkmInspectionContext inspectionContext, DkmClrType proxyType) { if (inspectionContext == null) { throw new ArgumentNullException(nameof(inspectionContext)); } var lmrType = proxyType.GetLmrType(); Debug.Assert(!lmrType.IsGenericTypeDefinition); const BindingFlags bindingFlags = BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; var constructor = lmrType.GetConstructors(bindingFlags).Single(); var value = constructor.Invoke(bindingFlags, null, new[] { RawValue }, null); return new DkmClrValue( value, value, type: proxyType, alias: null, formatter: _formatter, evalFlags: DkmEvaluationResultFlags.None, valueFlags: DkmClrValueFlags.None); } private static readonly ReadOnlyCollection<DkmClrType> s_noArguments = ArrayBuilder<DkmClrType>.GetInstance(0).ToImmutableAndFree(); public DkmClrValue InstantiateDynamicViewProxy(DkmInspectionContext inspectionContext) { if (inspectionContext == null) { throw new ArgumentNullException(nameof(inspectionContext)); } var module = new DkmClrModuleInstance( this.Type.AppDomain.RuntimeInstance, typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).Assembly, new DkmModule("Microsoft.CSharp.dll")); var proxyType = module.ResolveTypeName( "Microsoft.CSharp.RuntimeBinder.DynamicMetaObjectProviderDebugView", s_noArguments); return this.InstantiateProxyType(inspectionContext, proxyType); } public DkmClrValue InstantiateResultsViewProxy(DkmInspectionContext inspectionContext, DkmClrType enumerableType) { if (EvalFlags.Includes(DkmEvaluationResultFlags.ExceptionThrown)) { throw new InvalidOperationException(); } if (inspectionContext == null) { throw new ArgumentNullException(nameof(inspectionContext)); } var appDomain = enumerableType.AppDomain; var module = GetModule(appDomain, "System.Core.dll"); if (module == null) { return null; } var typeArgs = enumerableType.GenericArguments; Debug.Assert(typeArgs.Count <= 1); var proxyTypeName = (typeArgs.Count == 0) ? "System.Linq.SystemCore_EnumerableDebugView" : "System.Linq.SystemCore_EnumerableDebugView`1"; DkmClrType proxyType; try { proxyType = module.ResolveTypeName(proxyTypeName, typeArgs); } catch (ArgumentException) { // ResolveTypeName throws ArgumentException if type is not found. return null; } return this.InstantiateProxyType(inspectionContext, proxyType); } private static DkmClrModuleInstance GetModule(DkmClrAppDomain appDomain, string moduleName) { var modules = appDomain.GetClrModuleInstances(); foreach (var module in modules) { if (string.Equals(module.Name, moduleName, StringComparison.OrdinalIgnoreCase)) { return module; } } return null; } private static Type GetAncestorType(Type type, string ancestorTypeName) { if (type.FullName == ancestorTypeName) { return type; } // Search interfaces. foreach (var @interface in type.GetInterfaces()) { var ancestorType = GetAncestorType(@interface, ancestorTypeName); if (ancestorType != null) { return ancestorType; } } // Search base type. var baseType = type.BaseType; if (baseType != null) { return GetAncestorType(baseType, ancestorTypeName); } return null; } private static DkmEvaluationResultFlags GetEvaluationResultFlags(object value) { if (true.Equals(value)) { return DkmEvaluationResultFlags.BooleanTrue; } else if (value is bool) { return DkmEvaluationResultFlags.Boolean; } else { return DkmEvaluationResultFlags.None; } } private unsafe static object Dereference(IntPtr ptr, Type elementType) { // Only handling a subset of types currently. switch (Metadata.Type.GetTypeCode(elementType)) { case TypeCode.Int32: return *(int*)ptr; case TypeCode.Object: if (ptr == IntPtr.Zero) { throw new InvalidOperationException("Dereferencing null"); } var destinationType = elementType.IsPointer ? (Environment.Is64BitProcess ? typeof(long) : typeof(int)) : ((TypeImpl)elementType).Type; return Marshal.PtrToStructure(ptr, destinationType); default: throw new InvalidOperationException(); } } private static DkmEvaluationResultAccessType GetFieldAccess(Microsoft.VisualStudio.Debugger.Metadata.FieldInfo field) { if (field.IsPrivate) { return DkmEvaluationResultAccessType.Private; } else if (field.IsFamily) { return DkmEvaluationResultAccessType.Protected; } else if (field.IsAssembly) { return DkmEvaluationResultAccessType.Internal; } else { return DkmEvaluationResultAccessType.Public; } } private static DkmEvaluationResultAccessType GetPropertyAccess(Microsoft.VisualStudio.Debugger.Metadata.PropertyInfo property) { return GetMethodAccess(property.GetGetMethod(nonPublic: true)); } private static DkmEvaluationResultAccessType GetMethodAccess(Microsoft.VisualStudio.Debugger.Metadata.MethodBase method) { if (method.IsPrivate) { return DkmEvaluationResultAccessType.Private; } else if (method.IsFamily) { return DkmEvaluationResultAccessType.Protected; } else if (method.IsAssembly) { return DkmEvaluationResultAccessType.Internal; } else { return DkmEvaluationResultAccessType.Public; } } } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Google.Protobuf; using Grpc.Core; using Grpc.Core.Logging; using Grpc.Core.Utils; using NUnit.Framework; using Grpc.Testing; namespace Grpc.IntegrationTesting { /// <summary> /// Helper methods to start client runners for performance testing. /// </summary> public class ClientRunners { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<ClientRunners>(); /// <summary> /// Creates a started client runner. /// </summary> public static IClientRunner CreateStarted(ClientConfig config) { Logger.Debug("ClientConfig: {0}", config); if (config.AsyncClientThreads != 0) { Logger.Warning("ClientConfig.AsyncClientThreads is not supported for C#. Ignoring the value"); } if (config.CoreLimit != 0) { Logger.Warning("ClientConfig.CoreLimit is not supported for C#. Ignoring the value"); } if (config.CoreList.Count > 0) { Logger.Warning("ClientConfig.CoreList is not supported for C#. Ignoring the value"); } var channels = CreateChannels(config.ClientChannels, config.ServerTargets, config.SecurityParams); return new ClientRunnerImpl(channels, config.ClientType, config.RpcType, config.OutstandingRpcsPerChannel, config.LoadParams, config.PayloadConfig, config.HistogramParams); } private static List<Channel> CreateChannels(int clientChannels, IEnumerable<string> serverTargets, SecurityParams securityParams) { GrpcPreconditions.CheckArgument(clientChannels > 0, "clientChannels needs to be at least 1."); GrpcPreconditions.CheckArgument(serverTargets.Count() > 0, "at least one serverTarget needs to be specified."); var credentials = securityParams != null ? TestCredentials.CreateSslCredentials() : ChannelCredentials.Insecure; List<ChannelOption> channelOptions = null; if (securityParams != null && securityParams.ServerHostOverride != "") { channelOptions = new List<ChannelOption> { new ChannelOption(ChannelOptions.SslTargetNameOverride, securityParams.ServerHostOverride) }; } var result = new List<Channel>(); for (int i = 0; i < clientChannels; i++) { var target = serverTargets.ElementAt(i % serverTargets.Count()); var channel = new Channel(target, credentials, channelOptions); result.Add(channel); } return result; } } public class ClientRunnerImpl : IClientRunner { const double SecondsToNanos = 1e9; readonly List<Channel> channels; readonly ClientType clientType; readonly RpcType rpcType; readonly PayloadConfig payloadConfig; readonly Histogram histogram; readonly List<Task> runnerTasks; readonly CancellationTokenSource stoppedCts = new CancellationTokenSource(); readonly WallClockStopwatch wallClockStopwatch = new WallClockStopwatch(); public ClientRunnerImpl(List<Channel> channels, ClientType clientType, RpcType rpcType, int outstandingRpcsPerChannel, LoadParams loadParams, PayloadConfig payloadConfig, HistogramParams histogramParams) { GrpcPreconditions.CheckArgument(outstandingRpcsPerChannel > 0, "outstandingRpcsPerChannel"); this.channels = new List<Channel>(channels); this.clientType = clientType; this.rpcType = rpcType; this.payloadConfig = payloadConfig; this.histogram = new Histogram(histogramParams.Resolution, histogramParams.MaxPossible); this.runnerTasks = new List<Task>(); foreach (var channel in this.channels) { for (int i = 0; i < outstandingRpcsPerChannel; i++) { var timer = CreateTimer(loadParams, 1.0 / this.channels.Count / outstandingRpcsPerChannel); var threadBody = GetThreadBody(channel, timer); this.runnerTasks.Add(Task.Factory.StartNew(threadBody, TaskCreationOptions.LongRunning)); } } } public ClientStats GetStats(bool reset) { var histogramData = histogram.GetSnapshot(reset); var secondsElapsed = wallClockStopwatch.GetElapsedSnapshot(reset).TotalSeconds; // TODO: populate user time and system time return new ClientStats { Latencies = histogramData, TimeElapsed = secondsElapsed, TimeUser = 0, TimeSystem = 0 }; } public async Task StopAsync() { stoppedCts.Cancel(); foreach (var runnerTask in runnerTasks) { await runnerTask; } foreach (var channel in channels) { await channel.ShutdownAsync(); } } private void RunUnary(Channel channel, IInterarrivalTimer timer) { var client = BenchmarkService.NewClient(channel); var request = CreateSimpleRequest(); var stopwatch = new Stopwatch(); while (!stoppedCts.Token.IsCancellationRequested) { stopwatch.Restart(); client.UnaryCall(request); stopwatch.Stop(); // spec requires data point in nanoseconds. histogram.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos); timer.WaitForNext(); } } private async Task RunUnaryAsync(Channel channel, IInterarrivalTimer timer) { var client = BenchmarkService.NewClient(channel); var request = CreateSimpleRequest(); var stopwatch = new Stopwatch(); while (!stoppedCts.Token.IsCancellationRequested) { stopwatch.Restart(); await client.UnaryCallAsync(request); stopwatch.Stop(); // spec requires data point in nanoseconds. histogram.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos); await timer.WaitForNextAsync(); } } private async Task RunStreamingPingPongAsync(Channel channel, IInterarrivalTimer timer) { var client = BenchmarkService.NewClient(channel); var request = CreateSimpleRequest(); var stopwatch = new Stopwatch(); using (var call = client.StreamingCall()) { while (!stoppedCts.Token.IsCancellationRequested) { stopwatch.Restart(); await call.RequestStream.WriteAsync(request); await call.ResponseStream.MoveNext(); stopwatch.Stop(); // spec requires data point in nanoseconds. histogram.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos); await timer.WaitForNextAsync(); } // finish the streaming call await call.RequestStream.CompleteAsync(); Assert.IsFalse(await call.ResponseStream.MoveNext()); } } private async Task RunGenericStreamingAsync(Channel channel, IInterarrivalTimer timer) { var request = CreateByteBufferRequest(); var stopwatch = new Stopwatch(); var callDetails = new CallInvocationDetails<byte[], byte[]>(channel, GenericService.StreamingCallMethod, new CallOptions()); using (var call = Calls.AsyncDuplexStreamingCall(callDetails)) { while (!stoppedCts.Token.IsCancellationRequested) { stopwatch.Restart(); await call.RequestStream.WriteAsync(request); await call.ResponseStream.MoveNext(); stopwatch.Stop(); // spec requires data point in nanoseconds. histogram.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos); await timer.WaitForNextAsync(); } // finish the streaming call await call.RequestStream.CompleteAsync(); Assert.IsFalse(await call.ResponseStream.MoveNext()); } } private Action GetThreadBody(Channel channel, IInterarrivalTimer timer) { if (payloadConfig.PayloadCase == PayloadConfig.PayloadOneofCase.BytebufParams) { GrpcPreconditions.CheckArgument(clientType == ClientType.ASYNC_CLIENT, "Generic client only supports async API"); GrpcPreconditions.CheckArgument(rpcType == RpcType.STREAMING, "Generic client only supports streaming calls"); return () => { RunGenericStreamingAsync(channel, timer).Wait(); }; } GrpcPreconditions.CheckNotNull(payloadConfig.SimpleParams); if (clientType == ClientType.SYNC_CLIENT) { GrpcPreconditions.CheckArgument(rpcType == RpcType.UNARY, "Sync client can only be used for Unary calls in C#"); return () => RunUnary(channel, timer); } else if (clientType == ClientType.ASYNC_CLIENT) { switch (rpcType) { case RpcType.UNARY: return () => { RunUnaryAsync(channel, timer).Wait(); }; case RpcType.STREAMING: return () => { RunStreamingPingPongAsync(channel, timer).Wait(); }; } } throw new ArgumentException("Unsupported configuration."); } private SimpleRequest CreateSimpleRequest() { GrpcPreconditions.CheckNotNull(payloadConfig.SimpleParams); return new SimpleRequest { Payload = CreateZerosPayload(payloadConfig.SimpleParams.ReqSize), ResponseSize = payloadConfig.SimpleParams.RespSize }; } private byte[] CreateByteBufferRequest() { return new byte[payloadConfig.BytebufParams.ReqSize]; } private static Payload CreateZerosPayload(int size) { return new Payload { Body = ByteString.CopyFrom(new byte[size]) }; } private static IInterarrivalTimer CreateTimer(LoadParams loadParams, double loadMultiplier) { switch (loadParams.LoadCase) { case LoadParams.LoadOneofCase.ClosedLoop: return new ClosedLoopInterarrivalTimer(); case LoadParams.LoadOneofCase.Poisson: return new PoissonInterarrivalTimer(loadParams.Poisson.OfferedLoad * loadMultiplier); default: throw new ArgumentException("Unknown load type"); } } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.IO; using System.Xml.Serialization; using System.Text; using Amazon.Runtime; using Amazon.S3.Util; using Amazon.Util; using System.Globalization; namespace Amazon.S3.Model { /// <summary> /// Returns information about the GetObject response and response metadata. /// </summary> public partial class GetObjectResponse : StreamResponse { private string deleteMarker; private string acceptRanges; private Expiration expiration; private DateTime? restoreExpiration; private bool restoreInProgress; private DateTime? lastModified; private string eTag; private int? missingMeta; private string versionId; private DateTime? expires; private string websiteRedirectLocation; private ServerSideEncryptionMethod serverSideEncryption; private ServerSideEncryptionCustomerMethod serverSideEncryptionCustomerMethod; private string serverSideEncryptionKeyManagementServiceKeyId; private HeadersCollection headersCollection = new HeadersCollection(); private MetadataCollection metadataCollection = new MetadataCollection(); private string bucketName; private string key; /// <summary> /// Gets and sets the BucketName property. /// </summary> public string BucketName { get { return this.bucketName; } set { this.bucketName = value; } } /// <summary> /// Gets and sets the Key property. /// </summary> public string Key { get { return this.key; } set { this.key = value; } } /// <summary> /// Specifies whether the object retrieved was (true) or was not (false) a Delete Marker. If false, this response header does not appear in the /// response. /// /// </summary> public string DeleteMarker { get { return this.deleteMarker; } set { this.deleteMarker = value; } } // Check to see if DeleteMarker property is set internal bool IsSetDeleteMarker() { return this.deleteMarker != null; } /// <summary> /// The collection of headers for the request. /// </summary> public HeadersCollection Headers { get { if (this.headersCollection == null) this.headersCollection = new HeadersCollection(); return this.headersCollection; } } /// <summary> /// The collection of meta data for the request. /// </summary> public MetadataCollection Metadata { get { if (this.metadataCollection == null) this.metadataCollection = new MetadataCollection(); return this.metadataCollection; } } public string AcceptRanges { get { return this.acceptRanges; } set { this.acceptRanges = value; } } // Check to see if AcceptRanges property is set internal bool IsSetAcceptRanges() { return this.acceptRanges != null; } /// <summary> /// Gets and sets the Expiration property. /// Specifies the expiration date for the object and the /// rule governing the expiration. /// Is null if expiration is not applicable. /// </summary> public Expiration Expiration { get { return this.expiration; } set { this.expiration = value; } } // Check to see if Expiration property is set internal bool IsSetExpiration() { return this.expiration != null; } /// <summary> /// Gets and sets the RestoreExpiration property. /// RestoreExpiration will be set for objects that have been restored from Amazon Glacier. /// It indiciates for those objects how long the restored object will exist. /// </summary> public DateTime? RestoreExpiration { get { return this.restoreExpiration; } set { this.restoreExpiration = value; } } /// <summary> /// Gets and sets the RestoreInProgress /// Will be true when the object is in the process of being restored from Amazon Glacier. /// </summary> public bool RestoreInProgress { get { return this.restoreInProgress; } set { this.restoreInProgress = value; } } /// <summary> /// Last modified date of the object /// /// </summary> public DateTime LastModified { get { return this.lastModified ?? default(DateTime); } set { this.lastModified = value; } } // Check to see if LastModified property is set internal bool IsSetLastModified() { return this.lastModified.HasValue; } /// <summary> /// An ETag is an opaque identifier assigned by a web server to a specific version of a resource found at a URL /// /// </summary> public string ETag { get { return this.eTag; } set { this.eTag = value; } } // Check to see if ETag property is set internal bool IsSetETag() { return this.eTag != null; } /// <summary> /// This is set to the number of metadata entries not returned in x-amz-meta headers. This can happen if you create metadata using an API like /// SOAP that supports more flexible metadata than the REST API. For example, using SOAP, you can create metadata whose values are not legal /// HTTP headers. /// /// </summary> public int MissingMeta { get { return this.missingMeta ?? default(int); } set { this.missingMeta = value; } } // Check to see if MissingMeta property is set internal bool IsSetMissingMeta() { return this.missingMeta.HasValue; } /// <summary> /// Version of the object. /// /// </summary> public string VersionId { get { return this.versionId; } set { this.versionId = value; } } // Check to see if VersionId property is set internal bool IsSetVersionId() { return this.versionId != null; } /// <summary> /// The date and time at which the object is no longer cacheable. /// /// </summary> public DateTime Expires { get { return this.expires ?? default(DateTime); } set { this.expires = value; } } // Check to see if Expires property is set internal bool IsSetExpires() { return this.expires.HasValue; } /// <summary> /// If the bucket is configured as a website, redirects requests for this object to another object in the same bucket or to an external URL. /// Amazon S3 stores the value of this header in the object metadata. /// /// </summary> public string WebsiteRedirectLocation { get { return this.websiteRedirectLocation; } set { this.websiteRedirectLocation = value; } } // Check to see if WebsiteRedirectLocation property is set internal bool IsSetWebsiteRedirectLocation() { return this.websiteRedirectLocation != null; } /// <summary> /// The Server-side encryption algorithm used when storing this object in S3. /// /// </summary> public ServerSideEncryptionMethod ServerSideEncryptionMethod { get { return this.serverSideEncryption; } set { this.serverSideEncryption = value; } } // Check to see if ServerSideEncryptionMethod property is set internal bool IsSetServerSideEncryptionMethod() { return this.serverSideEncryption != null; } /// <summary> /// The id of the AWS Key Management Service key that Amazon S3 uses to encrypt and decrypt the object. /// </summary> public string ServerSideEncryptionKeyManagementServiceKeyId { get { return this.serverSideEncryptionKeyManagementServiceKeyId; } set { this.serverSideEncryptionKeyManagementServiceKeyId = value; } } /// <summary> /// Checks if ServerSideEncryptionKeyManagementServiceKeyId property is set. /// </summary> /// <returns>true if ServerSideEncryptionKeyManagementServiceKeyId property is set.</returns> internal bool IsSetServerSideEncryptionKeyManagementServiceKeyId() { return !System.String.IsNullOrEmpty(this.serverSideEncryptionKeyManagementServiceKeyId); } #if BCL || MOBILE /// <summary> /// Writes the content of the ResponseStream a file indicated by the filePath argument. /// </summary> /// <param name="filePath">The location where to write the ResponseStream</param> public void WriteResponseStreamToFile(string filePath) { WriteResponseStreamToFile(filePath, false); } /// <summary> /// Writes the content of the ResponseStream a file indicated by the filePath argument. /// </summary> /// <param name="filePath">The location where to write the ResponseStream</param> /// <param name="append">Whether or not to append to the file if it exists</param> public void WriteResponseStreamToFile(string filePath, bool append) { // Make sure the directory exists to write too. FileInfo fi = new FileInfo(filePath); Directory.CreateDirectory(fi.DirectoryName); Stream downloadStream; if (append && File.Exists(filePath)) downloadStream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.Read, S3Constants.DefaultBufferSize); else downloadStream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, S3Constants.DefaultBufferSize); try { long current = 0; BufferedStream bufferedStream = new BufferedStream(this.ResponseStream); byte[] buffer = new byte[S3Constants.DefaultBufferSize]; int bytesRead = 0; long totalIncrementTransferred = 0; while ((bytesRead = bufferedStream.Read(buffer, 0, buffer.Length)) > 0) { downloadStream.Write(buffer, 0, bytesRead); current += bytesRead; totalIncrementTransferred += bytesRead; if (totalIncrementTransferred >= AWSSDKUtils.DefaultProgressUpdateInterval || current == this.ContentLength) { this.OnRaiseProgressEvent(filePath, totalIncrementTransferred, current, this.ContentLength); totalIncrementTransferred = 0; } } ValidateWrittenStreamSize(current); } finally { downloadStream.Close(); } } #endif #region Progress Event /// <summary> /// The event for Write Object progress notifications. All /// subscribers will be notified when a new progress /// event is raised. /// </summary> /// <remarks> /// Subscribe to this event if you want to receive /// put object progress notifications. Here is how:<br /> /// 1. Define a method with a signature similar to this one: /// <code> /// private void displayProgress(object sender, WriteObjectProgressArgs args) /// { /// Console.WriteLine(args); /// } /// </code> /// 2. Add this method to the Put Object Progress Event delegate's invocation list /// <code> /// GetObjectResponse response = s3Client.GetObject(request); /// response.WriteObjectProgressEvent += displayProgress; /// </code> /// </remarks> public event EventHandler<WriteObjectProgressArgs> WriteObjectProgressEvent; #endregion /// <summary> /// This method is called by a producer of write object progress /// notifications. When called, all the subscribers in the /// invocation list will be called sequentially. /// </summary> /// <param name="file">The file being written.</param> /// <param name="incrementTransferred">The number of bytes transferred since last event</param> /// <param name="transferred">The number of bytes transferred</param> /// <param name="total">The total number of bytes to be transferred</param> internal void OnRaiseProgressEvent(string file, long incrementTransferred, long transferred, long total) { AWSSDKUtils.InvokeInBackground(WriteObjectProgressEvent, new WriteObjectProgressArgs(this.BucketName, this.Key, file, this.VersionId, incrementTransferred, transferred, total), this); } /// <summary> /// The Server-side encryption algorithm to be used with the customer provided key. /// /// </summary> public ServerSideEncryptionCustomerMethod ServerSideEncryptionCustomerMethod { get { if (this.serverSideEncryptionCustomerMethod == null) return ServerSideEncryptionCustomerMethod.None; return this.serverSideEncryptionCustomerMethod; } set { this.serverSideEncryptionCustomerMethod = value; } } private void ValidateWrittenStreamSize(long bytesWritten) { #if !(WIN_RT || WINDOWS_PHONE || MOBILE) // Check if response stream or it's base stream is a AESDecryptionStream var stream = Runtime.Internal.Util.WrapperStream.SearchWrappedStream(this.ResponseStream, (s => s is Runtime.Internal.Util.DecryptStream)); // Don't validate length if response is an encrypted object. if (stream!=null) return; #endif if (bytesWritten != this.ContentLength) { string amzId2; this.ResponseMetadata.Metadata.TryGetValue(HeaderKeys.XAmzId2Header, out amzId2); amzId2 = amzId2 ?? string.Empty; var message = string.Format(CultureInfo.InvariantCulture, "The total bytes read {0} from response stream is not equal to the Content-Length {1} for the object {2} in bucket {3}."+ " Request ID = {4} , AmzId2 = {5}.", bytesWritten, this.ContentLength, this.Key, this.BucketName, this.ResponseMetadata.RequestId, amzId2); throw new StreamSizeMismatchException(message, this.ContentLength, bytesWritten, this.ResponseMetadata.RequestId, amzId2); } } } /// <summary> /// Encapsulates the information needed to provide /// download progress for the Write Object Event. /// </summary> public class WriteObjectProgressArgs : TransferProgressArgs { /// <summary> /// The constructor takes the number of /// currently transferred bytes and the /// total number of bytes to be transferred /// </summary> /// <param name="bucketName">The bucket name for the S3 object being written.</param> /// <param name="key">The object key for the S3 object being written.</param> /// <param name="versionId">The version-id of the S3 object.</param> /// <param name="incrementTransferred">The number of bytes transferred since last event</param> /// <param name="transferred">The number of bytes transferred</param> /// <param name="total">The total number of bytes to be transferred</param> internal WriteObjectProgressArgs(string bucketName, string key, string versionId, long incrementTransferred, long transferred, long total) : base(incrementTransferred, transferred, total) { this.BucketName = bucketName; this.Key = key; this.VersionId = versionId; } /// <summary> /// The constructor takes the number of /// currently transferred bytes and the /// total number of bytes to be transferred /// </summary> /// <param name="bucketName">The bucket name for the S3 object being written.</param> /// <param name="key">The object key for the S3 object being written.</param> /// <param name="filePath">The file for the S3 object being written.</param> /// <param name="versionId">The version-id of the S3 object.</param> /// <param name="incrementTransferred">The number of bytes transferred since last event</param> /// <param name="transferred">The number of bytes transferred</param> /// <param name="total">The total number of bytes to be transferred</param> internal WriteObjectProgressArgs(string bucketName, string key, string filePath, string versionId, long incrementTransferred, long transferred, long total) : base(incrementTransferred, transferred, total) { this.BucketName = bucketName; this.Key = key; this.VersionId = versionId; this.FilePath = filePath; } /// <summary> /// Gets the bucket name for the S3 object being written. /// </summary> public string BucketName { get; private set; } /// <summary> /// Gets the object key for the S3 object being written. /// </summary> public string Key { get; private set; } /// <summary> /// Gets the version-id of the S3 object. /// </summary> public string VersionId { get; private set; } /// <summary> /// The file for the S3 object being written. /// </summary> public string FilePath { get; private set; } } }
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Toggl.Phoebe.Logging { public sealed class LogStore { private const long FileTrimThresholdSize = 1024 * 1024; private const long FileTrimTargetSize = 512 * 1024; private const string FileName = "diagnostics.log"; private const string FileTempName = "diagnostics.log.tmp"; private readonly object syncRoot = new Object (); private readonly Queue<string> writeQueue = new Queue<string> (); private readonly string logDir; private bool isProcessing; private TaskCompletionSource<byte[]> compressionTcs; public LogStore () { logDir = Environment.GetFolderPath (Environment.SpecialFolder.Personal); } public Task<byte[]> Compress () { Task<byte[]> ret; lock (syncRoot) { if (compressionTcs == null) { compressionTcs = new TaskCompletionSource<byte[]> (); } ret = compressionTcs.Task; } EnsureProcessing (); return ret; } public void Record (LogLevel level, string tag, string message, Exception exc) { var sb = new StringBuilder (); sb.AppendFormat ("[{0}] {1} - {2}: {3}", Time.Now, level, tag, message); if (exc != null) { var lines = exc.ToString ().Replace ("\r\n", "\n").Split ('\n', '\r'); foreach (var line in lines) { sb.AppendLine (); sb.Append ('\t'); sb.Append (line); } } Record (sb.ToString ()); } private void Record (string data) { lock (syncRoot) { writeQueue.Enqueue (data); } EnsureProcessing (); } private void EnsureProcessing () { lock (syncRoot) { if (isProcessing) { return; } isProcessing = true; } ThreadPool.QueueUserWorkItem (Process); } private void Process (object state) { var logFile = new FileInfo (Path.Combine (logDir, FileName)); // Always start out by trimming the logs TrimLog (logFile); while (true) { var shouldCompress = false; var shouldFlush = false; // Determine what to do: lock (syncRoot) { if (compressionTcs != null) { shouldCompress = true; } else if (writeQueue.Count > 0) { shouldFlush = true; } else { // Nothing left to do, shutdown worker thread isProcessing = false; break; } } // Do the actual work outside of lock if (shouldCompress) { CompressLogs (logFile); } else if (shouldFlush) { FlushLogs (logFile); } } } private void TrimLog (FileInfo logFile) { // Check if we need to trim the log file: if (logFile.Exists && logFile.Length >= FileTrimThresholdSize) { var tmpFile = new FileInfo (Path.Combine (logDir, FileTempName)); try { if (tmpFile.Exists) { tmpFile.Delete (); } File.Move (logFile.FullName, tmpFile.FullName); logFile.Refresh (); tmpFile.Refresh (); // Copy data over to new file using (var tmpReader = new StreamReader (tmpFile.FullName, Encoding.UTF8)) using (var logWriter = new StreamWriter (logFile.FullName, false, Encoding.UTF8)) { // Skip to where we can start copying tmpReader.BaseStream.Seek (-FileTrimTargetSize, SeekOrigin.End); tmpReader.DiscardBufferedData (); tmpReader.ReadLine (); string line; while ((line = tmpReader.ReadLine ()) != null) { logWriter.WriteLine (line); } } } catch (SystemException ex) { Console.WriteLine ("Failed to trim log file."); Console.WriteLine (ex); // Make sure that the log file is deleted so we can start a new one try { logFile.Delete (); } catch (SystemException ex2) { Console.WriteLine ("Failed to clean up log file."); Console.WriteLine (ex2); } } finally { try { tmpFile.Delete (); } catch (SystemException ex) { Console.WriteLine ("Failed to clean up temporary log file."); Console.WriteLine (ex); } } } } private void FlushLogs (FileInfo logFile) { // Flush queue to log file: try { using (var logWriter = new StreamWriter (logFile.FullName, true, Encoding.UTF8)) { while (true) { String data; // Get data to write: lock (syncRoot) { if (writeQueue.Count < 1) { return; } data = writeQueue.Dequeue (); } // Write data to file: try { logWriter.WriteLine (data); } catch (SystemException ex2) { // Couldn't write to log file.. nothing to do really. Console.WriteLine ("Failed to append to log file."); Console.WriteLine (ex2); } } } } catch (SystemException ex) { // Probably opening of the log file failed, clean up Console.WriteLine ("Failed to open the log file."); Console.WriteLine (ex); lock (syncRoot) { writeQueue.Clear (); } } } private void CompressLogs (FileInfo logFile) { byte[] data = null; using (var logStream = logFile.OpenRead ()) using (var buffer = new MemoryStream ()) using (var zipStream = new GZipStream (buffer, CompressionMode.Compress)) { logStream.CopyTo (zipStream); zipStream.Close (); data = buffer.ToArray (); } lock (syncRoot) { compressionTcs.SetResult (data); compressionTcs = null; } } } }
//+----------------------------------------------------------------------- // // Microsoft Windows Client Platform // Copyright (C) Microsoft Corporation, 2002 // // File: Sustitution.cs // // Contents: OpentTypeLayout substitution classes // // contact: sergeym // // History: 2002-03-23 Created (sergeym) // //------------------------------------------------------------------------ using System.Diagnostics; using System.Security; using System.Security.Permissions; using System; using System.IO; namespace MS.Internal.Shaping { // [SecurityCritical(SecurityCriticalScope.Everything)] internal struct SingleSubstitutionSubtable { private const int offsetFormat = 0; private const int offsetCoverage = 2; private const int offsetFormat1DeltaGlyphId = 4; private const int offsetFormat2GlyphCount = 4; private const int offsetFormat2SubstitutehArray = 6; private const int sizeFormat2SubstituteSize = 2; private ushort Format(FontTable Table) { return Table.GetUShort(offset + offsetFormat); } private CoverageTable Coverage(FontTable Table) { return new CoverageTable(offset+Table.GetUShort(offset + offsetCoverage)); } private short Format1DeltaGlyphId(FontTable Table) { Invariant.Assert(Format(Table)==1); return Table.GetShort(offset + offsetFormat1DeltaGlyphId); } // Not used. This value should be equal to glyph count in Coverage. // Keeping it for future reference //private ushort Foramt2GlyphCount(FontTable Table) //{ // Debug.Assert(Format(Table)==2); // return Table.GetUShort(offset + offsetFormat2GlyphCount); //} private ushort Format2SubstituteGlyphId(FontTable Table,ushort Index) { Invariant.Assert(Format(Table)==2); return Table.GetUShort(offset + offsetFormat2SubstitutehArray + Index * sizeFormat2SubstituteSize); } public bool Apply( FontTable Table, GlyphInfoList GlyphInfo, // List of GlyphInfo structs int FirstGlyph, // where to apply it out int NextGlyph // Next glyph to process ) { Invariant.Assert(FirstGlyph >= 0); NextGlyph = FirstGlyph + 1; //In case we don't match; ushort GlyphId = GlyphInfo.Glyphs[FirstGlyph]; int CoverageIndex = Coverage(Table).GetGlyphIndex(Table,GlyphId); if (CoverageIndex == -1) return false; switch(Format(Table)) { case 1: GlyphInfo.Glyphs[FirstGlyph] = (ushort)(GlyphId + Format1DeltaGlyphId(Table)); GlyphInfo.GlyphFlags[FirstGlyph] = (ushort)(GlyphFlags.Unresolved | GlyphFlags.Substituted); NextGlyph = FirstGlyph + 1; return true; case 2: GlyphInfo.Glyphs[FirstGlyph] = Format2SubstituteGlyphId(Table,(ushort)CoverageIndex); GlyphInfo.GlyphFlags[FirstGlyph] = (ushort)(GlyphFlags.Unresolved | GlyphFlags.Substituted); NextGlyph = FirstGlyph + 1; return true; default: NextGlyph = FirstGlyph+1; return false; } } public bool IsLookupCovered( FontTable table, uint[] glyphBits, ushort minGlyphId, ushort maxGlyphId) { return Coverage(table).IsAnyGlyphCovered(table, glyphBits, minGlyphId, maxGlyphId ); } public CoverageTable GetPrimaryCoverage(FontTable table) { return Coverage(table); } public SingleSubstitutionSubtable(int Offset) { offset = Offset; } private int offset; } /// <SecurityNote> /// Critical - Everything in this struct is considered critical /// because they either operate on raw font table bits or unsafe pointers. /// </SecurityNote> [SecurityCritical(SecurityCriticalScope.Everything)] internal struct LigatureSubstitutionSubtable { private const int offsetFormat = 0; private const int offsetCoverage = 2; private const int offsetLigatureSetCount = 4; private const int offsetLigatureSetArray = 6; private const int sizeLigatureSet = 2; private ushort Format(FontTable Table) { return Table.GetUShort(offset + offsetFormat); } private CoverageTable Coverage(FontTable Table) { return new CoverageTable(offset + Table.GetUShort(offset + offsetCoverage)); } private ushort LigatureSetCount(FontTable Table) { return Table.GetUShort(offset + offsetLigatureSetCount); } private LigatureSetTable LigatureSet(FontTable Table, ushort Index) { return new LigatureSetTable(offset+Table.GetUShort(offset+ offsetLigatureSetArray + Index * sizeLigatureSet)); } #region Ligature Substitution subtable private structures /// <SecurityNote> /// Critical - Everything in this struct is considered critical /// because they either operate on raw font table bits or unsafe pointers. /// </SecurityNote> [SecurityCritical(SecurityCriticalScope.Everything)] private struct LigatureSetTable { private const int offsetLigatureCount = 0; private const int offsetLigatureArray = 2; private const int sizeLigatureOffset = 2; public ushort LigatureCount(FontTable Table) { return Table.GetUShort(offset + offsetLigatureCount); } public LigatureTable Ligature(FontTable Table, ushort Index) { return new LigatureTable(offset + Table.GetUShort(offset + offsetLigatureArray + Index * sizeLigatureOffset)); } public LigatureSetTable(int Offset) { offset = Offset; } private int offset; } /// <SecurityNote> /// Critical - Everything in this struct is considered critical /// because they either operate on raw font table bits or unsafe pointers. /// </SecurityNote> [SecurityCritical(SecurityCriticalScope.Everything)] private struct LigatureTable { private const int offsetLigatureGlyph = 0; private const int offsetComponentCount = 2; private const int offsetComponentArray = 4; private const int sizeComponent = 2; public ushort LigatureGlyph(FontTable Table) { return Table.GetUShort(offset + offsetLigatureGlyph); } public ushort ComponentCount(FontTable Table) { return Table.GetUShort(offset + offsetComponentCount); } public ushort Component(FontTable Table, ushort Index) { //LigaTable includes comps from 1 to N. So, (Index-1) return Table.GetUShort(offset + offsetComponentArray + (Index-1) * sizeComponent); } public LigatureTable(int Offset) { offset = Offset; } private int offset; } #endregion public unsafe bool Apply( IOpenTypeFont Font, FontTable Table, int CharCount, UshortList Charmap, // Character to glyph map GlyphInfoList GlyphInfo, // List of GlyphInfo ushort LookupFlags, // Lookup flags for glyph lookups int FirstGlyph, // where to apply it int AfterLastGlyph, // how long is a context we can use out int NextGlyph // Next glyph to process ) { Invariant.Assert(FirstGlyph>=0); Invariant.Assert(AfterLastGlyph<=GlyphInfo.Length); NextGlyph = FirstGlyph + 1; //In case we don't match; if (Format(Table) != 1) return false; // Unknown format int glyphCount=GlyphInfo.Length; ushort glyphId = GlyphInfo.Glyphs[FirstGlyph]; int CoverageIndex = Coverage(Table).GetGlyphIndex(Table,glyphId); if (CoverageIndex==-1) return false; int curGlyph; ushort ligatureGlyph=0; bool match = false; ushort compCount=0; LigatureSetTable ligatureSet = LigatureSet(Table,(ushort)CoverageIndex); ushort ligaCount = ligatureSet.LigatureCount(Table); for(ushort liga=0; liga<ligaCount; liga++) { LigatureTable ligature = ligatureSet.Ligature(Table,liga); compCount = ligature.ComponentCount(Table); if (compCount == 0) { throw new FileFormatException(); } curGlyph=FirstGlyph; ushort comp=1; for(comp=1;comp<compCount;comp++) { curGlyph = LayoutEngine.GetNextGlyphInLookup(Font,GlyphInfo,curGlyph+1,LookupFlags,LayoutEngine.LookForward); if (curGlyph>=AfterLastGlyph) break; if (GlyphInfo.Glyphs[curGlyph]!=ligature.Component(Table,comp)) break; } if (comp==compCount) //liga matched { match=true; ligatureGlyph = ligature.LigatureGlyph(Table); break; //Liga found } } //If no ligature found, match will remain false after last iteration if (match) { //Fix character and glyph Mapping //PERF: localize ligature character range //Calculate Ligature CharCount int totalLigaCharCount=0; int firstLigaChar=int.MaxValue; curGlyph=FirstGlyph; for(ushort comp=0;comp<compCount;comp++) { Invariant.Assert(curGlyph<AfterLastGlyph); int curFirstChar = GlyphInfo.FirstChars[curGlyph]; int curLigaCount = GlyphInfo.LigatureCounts[curGlyph]; totalLigaCharCount += curLigaCount; if (curFirstChar<firstLigaChar) firstLigaChar=curFirstChar; curGlyph = LayoutEngine.GetNextGlyphInLookup(Font,GlyphInfo,curGlyph+1,LookupFlags,LayoutEngine.LookForward); } curGlyph=FirstGlyph; int prevGlyph=FirstGlyph; ushort shift=0; for(ushort comp=1;comp<=compCount;comp++) { prevGlyph=curGlyph; if (comp<compCount) { curGlyph = LayoutEngine. GetNextGlyphInLookup(Font,GlyphInfo, curGlyph+1, LookupFlags, LayoutEngine.LookForward); } else curGlyph = GlyphInfo.Length; // to the end from last component // Set charmap for ligature component for(int curChar=0; curChar<CharCount; curChar++) { if (Charmap[curChar]==prevGlyph) { Charmap[curChar] = (ushort)FirstGlyph; } } //Shift glyphInfo if (shift>0) { for(int glyph=prevGlyph+1; glyph<curGlyph; glyph++) { GlyphInfo.Glyphs[glyph-shift] = GlyphInfo.Glyphs[glyph]; GlyphInfo.GlyphFlags[glyph-shift] = GlyphInfo.GlyphFlags[glyph]; GlyphInfo.FirstChars[glyph-shift] = GlyphInfo.FirstChars[glyph]; GlyphInfo.LigatureCounts[glyph-shift] = GlyphInfo.LigatureCounts[glyph]; } if (curGlyph-prevGlyph>1) //do fixing only if have glyphs in between { for(int curChar=0; curChar<CharCount; curChar++) { ushort curCharmap = Charmap[curChar]; if (curCharmap>prevGlyph && curCharmap<curGlyph) { Charmap[curChar] -= shift; } } } } ++shift; } //Place new glyph into position of first ligature glyph GlyphInfo.Glyphs[FirstGlyph] = ligatureGlyph; GlyphInfo.GlyphFlags[FirstGlyph] = (ushort)(GlyphFlags.Unresolved | GlyphFlags.Substituted); GlyphInfo.FirstChars[FirstGlyph] = (ushort)firstLigaChar; GlyphInfo.LigatureCounts[FirstGlyph] = (ushort)totalLigaCharCount; //remove empty space if (compCount > 1) { GlyphInfo.Remove(GlyphInfo.Length-compCount+1,compCount-1); } NextGlyph=prevGlyph-(compCount-1)+1; } return match; } public bool IsLookupCovered( FontTable table, uint[] glyphBits, ushort minGlyphId, ushort maxGlyphId) { if (!Coverage(table).IsAnyGlyphCovered(table, glyphBits, minGlyphId, maxGlyphId ) ) return false; ushort ligatureSetCount = LigatureSetCount(table); for(ushort setIndex = 0; setIndex < ligatureSetCount; setIndex++) { LigatureSetTable ligatureSet = LigatureSet(table, setIndex); ushort ligaCount = ligatureSet.LigatureCount(table); for (ushort liga = 0; liga < ligaCount; liga++) { LigatureTable ligature = ligatureSet.Ligature(table, liga); ushort compCount = ligature.ComponentCount(table); bool ligatureIsComplex = true; for(ushort compIndex = 1; compIndex < compCount; compIndex++) { ushort glyphId = ligature.Component(table,compIndex); if (glyphId > maxGlyphId || glyphId < minGlyphId || (glyphBits[glyphId >> 5] & (1 << (glyphId % 32))) == 0 ) { ligatureIsComplex = false; break; } } if (ligatureIsComplex) return true; } } return false; } public CoverageTable GetPrimaryCoverage(FontTable table) { return Coverage(table); } public LigatureSubstitutionSubtable(int Offset) { offset = Offset; } private int offset; } /// <SecurityNote> /// Critical - Everything in this struct is considered critical /// because they either operate on raw font table bits or unsafe pointers. /// </SecurityNote> [SecurityCritical(SecurityCriticalScope.Everything)] internal struct MultipleSubstitutionSequenceTable { private const int offsetGlyphCount = 0; private const int offsetGlyphArray = 2; private const int sizeGlyphId = 2; public ushort GlyphCount(FontTable Table) { return Table.GetUShort(offset + offsetGlyphCount); } public ushort Glyph(FontTable Table, ushort index) { return Table.GetUShort(offset + offsetGlyphArray + index * sizeGlyphId); } public MultipleSubstitutionSequenceTable(int Offset) { offset = Offset; } private int offset; } /// <SecurityNote> /// Critical - Everything in this struct is considered critical /// because they either operate on raw font table bits or unsafe pointers. /// </SecurityNote> [SecurityCritical(SecurityCriticalScope.Everything)] internal struct MultipleSubstitutionSubtable { private const int offsetFormat = 0; private const int offsetCoverage = 2; private const int offsetSequenceCount = 4; private const int offsetSequenceArray = 6; private const int sizeSequenceOffset = 2; private ushort Format(FontTable Table) { return Table.GetUShort(offset + offsetFormat); } private CoverageTable Coverage(FontTable Table) { return new CoverageTable(offset + Table.GetUShort(offset + offsetCoverage)); } // Not used. This value should be equal to glyph count in Coverage. // Keeping it for future reference //private ushort SequenceCount(FontTable Table) //{ // return Table.GetUShort(offset + offsetSequenceCount); //} private MultipleSubstitutionSequenceTable Sequence(FontTable Table, int Index) { return new MultipleSubstitutionSequenceTable( offset + Table.GetUShort(offset + offsetSequenceArray + Index * sizeSequenceOffset) ); } public unsafe bool Apply( IOpenTypeFont Font, FontTable Table, int CharCount, UshortList Charmap, // Character to glyph map GlyphInfoList GlyphInfo, // List of GlyphInfo ushort LookupFlags, // Lookup flags for glyph lookups int FirstGlyph, // where to apply it int AfterLastGlyph, // how long is a context we can use out int NextGlyph // Next glyph to process ) { NextGlyph = FirstGlyph + 1; // in case we don't match if (Format(Table) != 1) return false; //unknown format int oldGlyphCount=GlyphInfo.Length; ushort glyphId = GlyphInfo.Glyphs[FirstGlyph]; int coverageIndex = Coverage(Table).GetGlyphIndex(Table,glyphId); if (coverageIndex==-1) return false; MultipleSubstitutionSequenceTable sequence = Sequence(Table,coverageIndex); ushort sequenceLength = sequence.GlyphCount(Table); int lengthDelta = sequenceLength - 1; if (sequenceLength==0) { // This is illegal, because mapping will be broken - // corresponding char will be lost. Just leave it as it is. // (char will be attached to the following glyph). GlyphInfo.Remove(FirstGlyph,1); } else { ushort firstChar = GlyphInfo.FirstChars[FirstGlyph]; ushort ligatureCount = GlyphInfo.LigatureCounts[FirstGlyph]; if (lengthDelta > 0) { GlyphInfo.Insert(FirstGlyph,lengthDelta); } //put glyphs in place for(ushort gl=0; gl<sequenceLength; gl++) { GlyphInfo.Glyphs[FirstGlyph + gl] = sequence.Glyph(Table,gl); GlyphInfo.GlyphFlags[FirstGlyph + gl] = (ushort)(GlyphFlags.Unresolved | GlyphFlags.Substituted); GlyphInfo.FirstChars[FirstGlyph + gl] = firstChar; GlyphInfo.LigatureCounts[FirstGlyph + gl] = ligatureCount; } } //Fix char mapping - very simple for now. // Works only for arabic base+mark -> base and marks decomposition // for(int ch=0;ch<CharCount;ch++) { if (Charmap[ch]>FirstGlyph) Charmap[ch] = (ushort)(Charmap[ch]+lengthDelta); } NextGlyph = FirstGlyph + lengthDelta + 1; return true; } public bool IsLookupCovered( FontTable table, uint[] glyphBits, ushort minGlyphId, ushort maxGlyphId) { return Coverage(table).IsAnyGlyphCovered(table, glyphBits, minGlyphId, maxGlyphId ); } public CoverageTable GetPrimaryCoverage(FontTable table) { return Coverage(table); } public MultipleSubstitutionSubtable(int Offset) { offset = Offset; } private int offset; } /// <SecurityNote> /// Critical - Everything in this struct is considered critical /// because they either operate on raw font table bits or unsafe pointers. /// </SecurityNote> [SecurityCritical(SecurityCriticalScope.Everything)] struct AlternateSubstitutionSubtable { private const int offsetFormat = 0; private const int offsetCoverage = 2; private const int offsetAlternateSetCount = 4; private const int offsetAlternateSets = 6; private const int sizeAlternateSetOffset = 2; private const ushort InvalidAlternateGlyph = 0xFFFF; public ushort Format(FontTable Table) { return Table.GetUShort(offset + offsetFormat); } private CoverageTable Coverage(FontTable Table) { return new CoverageTable(offset + Table.GetUShort(offset + offsetCoverage)); } // Not used. This value should be equal to glyph count in Coverage. // Keeping it for future reference //private ushort AlternateSetCount(FontTable Table) //{ // return Table.GetUShort(offset + offsetAlternateSetCount); //} private AlternateSetTable AlternateSet(FontTable Table, int index) { return new AlternateSetTable(offset + Table.GetUShort(offset + offsetAlternateSets + index * sizeAlternateSetOffset) ); } /// <SecurityNote> /// Critical - Everything in this struct is considered critical /// because they either operate on raw font table bits or unsafe pointers. /// </SecurityNote> [SecurityCritical(SecurityCriticalScope.Everything)] private struct AlternateSetTable { private const int offsetGlyphCount = 0; private const int offsetGlyphs = 2; private const int sizeGlyph = 2; public ushort GlyphCount(FontTable Table) { return Table.GetUShort(offset + offsetGlyphCount); } public ushort Alternate(FontTable Table, uint FeatureParam) { Invariant.Assert(FeatureParam > 0); // Parameter 0 means feautre is disabled. //Should be filtered out in GetNextEnabledGlyphRange // Off by one - alternate number 1 is stored under index 0 uint index = FeatureParam - 1; if (index >= GlyphCount(Table)) { return AlternateSubstitutionSubtable.InvalidAlternateGlyph; } return Table.GetUShort(offset + offsetGlyphs + (ushort)index*sizeGlyph); } public AlternateSetTable(int Offset) { offset = Offset; } private int offset; } public unsafe bool Apply( FontTable Table, GlyphInfoList GlyphInfo, // List of GlyphInfo uint FeatureParam, // For this lookup - index of glyph alternate int FirstGlyph, // where to apply it out int NextGlyph // Next glyph to process ) { NextGlyph = FirstGlyph + 1; // always move one glyph forward, // doesn't matter whether we matched context if (Format(Table) != 1) return false; //Unknown format int oldGlyphCount=GlyphInfo.Length; int coverageIndex = Coverage(Table). GetGlyphIndex(Table,GlyphInfo.Glyphs[FirstGlyph]); if (coverageIndex==-1) return false; AlternateSetTable alternateSet = AlternateSet(Table,coverageIndex); ushort alternateGlyph = alternateSet.Alternate(Table, FeatureParam); if (alternateGlyph != InvalidAlternateGlyph) { GlyphInfo.Glyphs[FirstGlyph] = alternateGlyph; GlyphInfo.GlyphFlags[FirstGlyph] = (ushort)(GlyphFlags.Unresolved | GlyphFlags.Substituted); return true; } return false; } public bool IsLookupCovered( FontTable table, uint[] glyphBits, ushort minGlyphId, ushort maxGlyphId) { return Coverage(table).IsAnyGlyphCovered(table, glyphBits, minGlyphId, maxGlyphId ); } public CoverageTable GetPrimaryCoverage(FontTable table) { return Coverage(table); } public AlternateSubstitutionSubtable(int Offset) { offset = Offset; } private int offset; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. #pragma warning disable RS0007 // Avoid zero-length array allocations. using System; using System.Collections.ObjectModel; using System.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.CallStack; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Microsoft.VisualStudio.Debugger.Metadata; using Roslyn.Utilities; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal delegate void CompletionRoutine(); internal delegate void CompletionRoutine<TResult>(TResult result); /// <summary> /// Computes expansion of <see cref="DkmClrValue"/> instances. /// </summary> /// <remarks> /// This class provides implementation for the default ResultProvider component. /// </remarks> public abstract class ResultProvider : IDkmClrResultProvider { static ResultProvider() { FatalError.Handler = FailFast.OnFatalException; } // Fields should be removed and replaced with calls through DkmInspectionContext. // (see https://github.com/dotnet/roslyn/issues/6899). internal readonly IDkmClrFormatter2 Formatter2; internal readonly IDkmClrFullNameProvider FullNameProvider; internal ResultProvider(IDkmClrFormatter2 formatter2, IDkmClrFullNameProvider fullNameProvider) { Formatter2 = formatter2; FullNameProvider = fullNameProvider; } internal abstract string StaticMembersString { get; } internal abstract bool IsPrimitiveType(Type type); void IDkmClrResultProvider.GetResult(DkmClrValue value, DkmWorkList workList, DkmClrType declaredType, DkmClrCustomTypeInfo declaredTypeInfo, DkmInspectionContext inspectionContext, ReadOnlyCollection<string> formatSpecifiers, string resultName, string resultFullName, DkmCompletionRoutine<DkmEvaluationAsyncResult> completionRoutine) { if (formatSpecifiers == null) { formatSpecifiers = Formatter.NoFormatSpecifiers; } if (resultFullName != null) { ReadOnlyCollection<string> otherSpecifiers; resultFullName = FullNameProvider.GetClrExpressionAndFormatSpecifiers(inspectionContext, resultFullName, out otherSpecifiers); foreach (var formatSpecifier in otherSpecifiers) { formatSpecifiers = Formatter.AddFormatSpecifier(formatSpecifiers, formatSpecifier); } } var wl = new WorkList(workList, e => completionRoutine(DkmEvaluationAsyncResult.CreateErrorResult(e))); wl.ContinueWith( () => GetRootResultAndContinue( value, wl, declaredType, declaredTypeInfo, inspectionContext, resultName, resultFullName, formatSpecifiers, result => wl.ContinueWith(() => completionRoutine(new DkmEvaluationAsyncResult(result))))); } DkmClrValue IDkmClrResultProvider.GetClrValue(DkmSuccessEvaluationResult evaluationResult) { try { var dataItem = evaluationResult.GetDataItem<EvalResultDataItem>(); if (dataItem == null) { // We don't know about this result. Call next implementation return evaluationResult.GetClrValue(); } return dataItem.Value; } catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e)) { throw ExceptionUtilities.Unreachable; } } internal const DkmEvaluationFlags NotRoot = (DkmEvaluationFlags)0x20000; internal const DkmEvaluationFlags NoResults = (DkmEvaluationFlags)0x40000; void IDkmClrResultProvider.GetChildren(DkmEvaluationResult evaluationResult, DkmWorkList workList, int initialRequestSize, DkmInspectionContext inspectionContext, DkmCompletionRoutine<DkmGetChildrenAsyncResult> completionRoutine) { var dataItem = evaluationResult.GetDataItem<EvalResultDataItem>(); if (dataItem == null) { // We don't know about this result. Call next implementation evaluationResult.GetChildren(workList, initialRequestSize, inspectionContext, completionRoutine); return; } var expansion = dataItem.Expansion; if (expansion == null) { var enumContext = DkmEvaluationResultEnumContext.Create(0, evaluationResult.StackFrame, inspectionContext, new EnumContextDataItem(evaluationResult)); completionRoutine(new DkmGetChildrenAsyncResult(new DkmEvaluationResult[0], enumContext)); return; } // Evaluate children with InspectionContext that is not the root. inspectionContext = inspectionContext.With(NotRoot); var rows = ArrayBuilder<EvalResult>.GetInstance(); int index = 0; expansion.GetRows(this, rows, inspectionContext, dataItem, dataItem.Value, 0, initialRequestSize, visitAll: true, index: ref index); var numRows = rows.Count; Debug.Assert(index >= numRows); Debug.Assert(initialRequestSize >= numRows); var initialChildren = new DkmEvaluationResult[numRows]; CompletionRoutine<Exception> onException = e => completionRoutine(DkmGetChildrenAsyncResult.CreateErrorResult(e)); var wl = new WorkList(workList, onException); wl.ContinueWith(() => GetEvaluationResultsAndContinue(evaluationResult, rows, initialChildren, 0, numRows, wl, inspectionContext, () => wl.ContinueWith( () => { var enumContext = DkmEvaluationResultEnumContext.Create(index, evaluationResult.StackFrame, inspectionContext, new EnumContextDataItem(evaluationResult)); completionRoutine(new DkmGetChildrenAsyncResult(initialChildren, enumContext)); rows.Free(); }), onException)); } void IDkmClrResultProvider.GetItems(DkmEvaluationResultEnumContext enumContext, DkmWorkList workList, int startIndex, int count, DkmCompletionRoutine<DkmEvaluationEnumAsyncResult> completionRoutine) { var enumContextDataItem = enumContext.GetDataItem<EnumContextDataItem>(); if (enumContextDataItem == null) { // We don't know about this result. Call next implementation enumContext.GetItems(workList, startIndex, count, completionRoutine); return; } var evaluationResult = enumContextDataItem.Result; var dataItem = evaluationResult.GetDataItem<EvalResultDataItem>(); var expansion = dataItem.Expansion; if (expansion == null) { completionRoutine(new DkmEvaluationEnumAsyncResult(new DkmEvaluationResult[0])); return; } var inspectionContext = enumContext.InspectionContext; var rows = ArrayBuilder<EvalResult>.GetInstance(); int index = 0; expansion.GetRows(this, rows, inspectionContext, dataItem, dataItem.Value, startIndex, count, visitAll: false, index: ref index); var numRows = rows.Count; Debug.Assert(count >= numRows); var results = new DkmEvaluationResult[numRows]; CompletionRoutine<Exception> onException = e => completionRoutine(DkmEvaluationEnumAsyncResult.CreateErrorResult(e)); var wl = new WorkList(workList, onException); wl.ContinueWith(() => GetEvaluationResultsAndContinue(evaluationResult, rows, results, 0, numRows, wl, inspectionContext, () => wl.ContinueWith( () => { completionRoutine(new DkmEvaluationEnumAsyncResult(results)); rows.Free(); }), onException)); } string IDkmClrResultProvider.GetUnderlyingString(DkmEvaluationResult result) { try { var dataItem = result.GetDataItem<EvalResultDataItem>(); if (dataItem == null) { // We don't know about this result. Call next implementation return result.GetUnderlyingString(); } return dataItem.Value?.GetUnderlyingString(result.InspectionContext); } catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e)) { throw ExceptionUtilities.Unreachable; } } private void GetChild( DkmEvaluationResult parent, WorkList workList, EvalResult row, DkmCompletionRoutine<DkmEvaluationAsyncResult> completionRoutine) { var inspectionContext = row.InspectionContext; if ((row.Kind != ExpansionKind.Default) || (row.Value == null)) { CreateEvaluationResultAndContinue( row, workList, row.InspectionContext, parent.StackFrame, child => completionRoutine(new DkmEvaluationAsyncResult(child))); } else { var typeDeclaringMember = row.TypeDeclaringMemberAndInfo; var name = (typeDeclaringMember.Type == null) ? row.Name : GetQualifiedMemberName(row.InspectionContext, typeDeclaringMember, row.Name, FullNameProvider); row.Value.GetResult( workList.InnerWorkList, row.DeclaredTypeAndInfo.ClrType, row.DeclaredTypeAndInfo.Info, row.InspectionContext, Formatter.NoFormatSpecifiers, name, row.FullName, result => workList.ContinueWith(() => completionRoutine(result))); } } private void CreateEvaluationResultAndContinue(EvalResult result, WorkList workList, DkmInspectionContext inspectionContext, DkmStackWalkFrame stackFrame, CompletionRoutine<DkmEvaluationResult> completionRoutine) { switch (result.Kind) { case ExpansionKind.Explicit: completionRoutine(DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, Name: result.DisplayName, FullName: result.FullName, Flags: result.Flags, Value: result.DisplayValue, EditableValue: result.EditableValue, Type: result.DisplayType, Category: DkmEvaluationResultCategory.Data, Access: DkmEvaluationResultAccessType.None, StorageType: DkmEvaluationResultStorageType.None, TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None, Address: result.Value.Address, CustomUIVisualizers: null, ExternalModules: null, DataItem: result.ToDataItem())); break; case ExpansionKind.Error: completionRoutine(DkmFailedEvaluationResult.Create( inspectionContext, StackFrame: stackFrame, Name: result.Name, FullName: result.FullName, ErrorMessage: result.DisplayValue, Flags: DkmEvaluationResultFlags.None, Type: null, DataItem: null)); break; case ExpansionKind.NativeView: { var value = result.Value; var name = Resources.NativeView; var fullName = result.FullName; var display = result.Name; DkmEvaluationResult evalResult; if (value.IsError()) { evalResult = DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, Name: name, FullName: fullName, ErrorMessage: display, Flags: result.Flags, Type: null, DataItem: result.ToDataItem()); } else { // For Native View, create a DkmIntermediateEvaluationResult. // This will allow the C++ EE to take over expansion. var process = inspectionContext.RuntimeInstance.Process; var cpp = process.EngineSettings.GetLanguage(new DkmCompilerId(DkmVendorId.Microsoft, DkmLanguageId.Cpp)); evalResult = DkmIntermediateEvaluationResult.Create( inspectionContext, stackFrame, Name: name, FullName: fullName, Expression: display, IntermediateLanguage: cpp, TargetRuntime: process.GetNativeRuntimeInstance(), DataItem: result.ToDataItem()); } completionRoutine(evalResult); } break; case ExpansionKind.NonPublicMembers: completionRoutine(DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, Name: Resources.NonPublicMembers, FullName: result.FullName, Flags: result.Flags, Value: null, EditableValue: null, Type: string.Empty, Category: DkmEvaluationResultCategory.Data, Access: DkmEvaluationResultAccessType.None, StorageType: DkmEvaluationResultStorageType.None, TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None, Address: result.Value.Address, CustomUIVisualizers: null, ExternalModules: null, DataItem: result.ToDataItem())); break; case ExpansionKind.StaticMembers: completionRoutine(DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, Name: StaticMembersString, FullName: result.FullName, Flags: result.Flags, Value: null, EditableValue: null, Type: string.Empty, Category: DkmEvaluationResultCategory.Class, Access: DkmEvaluationResultAccessType.None, StorageType: DkmEvaluationResultStorageType.None, TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None, Address: result.Value.Address, CustomUIVisualizers: null, ExternalModules: null, DataItem: result.ToDataItem())); break; case ExpansionKind.RawView: completionRoutine(DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, Name: Resources.RawView, FullName: result.FullName, Flags: result.Flags, Value: null, EditableValue: result.EditableValue, Type: string.Empty, Category: DkmEvaluationResultCategory.Data, Access: DkmEvaluationResultAccessType.None, StorageType: DkmEvaluationResultStorageType.None, TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None, Address: result.Value.Address, CustomUIVisualizers: null, ExternalModules: null, DataItem: result.ToDataItem())); break; case ExpansionKind.DynamicView: case ExpansionKind.ResultsView: completionRoutine(DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, result.Name, result.FullName, result.Flags, result.DisplayValue, EditableValue: null, Type: string.Empty, Category: DkmEvaluationResultCategory.Method, Access: DkmEvaluationResultAccessType.None, StorageType: DkmEvaluationResultStorageType.None, TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None, Address: result.Value.Address, CustomUIVisualizers: null, ExternalModules: null, DataItem: result.ToDataItem())); break; case ExpansionKind.TypeVariable: completionRoutine(DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, result.Name, result.FullName, result.Flags, result.DisplayValue, EditableValue: null, Type: result.DisplayValue, Category: DkmEvaluationResultCategory.Data, Access: DkmEvaluationResultAccessType.None, StorageType: DkmEvaluationResultStorageType.None, TypeModifierFlags: DkmEvaluationResultTypeModifierFlags.None, Address: result.Value.Address, CustomUIVisualizers: null, ExternalModules: null, DataItem: result.ToDataItem())); break; case ExpansionKind.PointerDereference: case ExpansionKind.Default: // This call will evaluate DebuggerDisplayAttributes. GetResultAndContinue( result, workList, declaredType: result.DeclaredTypeAndInfo.ClrType, declaredTypeInfo: result.DeclaredTypeAndInfo.Info, inspectionContext: inspectionContext, useDebuggerDisplay: result.UseDebuggerDisplay, completionRoutine: completionRoutine); break; default: throw ExceptionUtilities.UnexpectedValue(result.Kind); } } private static DkmEvaluationResult CreateEvaluationResult( DkmInspectionContext inspectionContext, DkmClrValue value, string name, string typeName, string display, EvalResult result) { if (value.IsError()) { // Evaluation failed return DkmFailedEvaluationResult.Create( InspectionContext: inspectionContext, StackFrame: value.StackFrame, Name: name, FullName: result.FullName, ErrorMessage: display, Flags: result.Flags, Type: typeName, DataItem: result.ToDataItem()); } else { ReadOnlyCollection<DkmCustomUIVisualizerInfo> customUIVisualizers = null; if (!value.IsNull) { DkmCustomUIVisualizerInfo[] customUIVisualizerInfo = value.Type.GetDebuggerCustomUIVisualizerInfo(); if (customUIVisualizerInfo != null) { customUIVisualizers = new ReadOnlyCollection<DkmCustomUIVisualizerInfo>(customUIVisualizerInfo); } } // If the EvalResultDataItem doesn't specify a particular category, we'll just propagate DkmClrValue.Category, // which typically appears to be set to the default value ("Other"). var category = (result.Category != DkmEvaluationResultCategory.Other) ? result.Category : value.Category; // Valid value return DkmSuccessEvaluationResult.Create( InspectionContext: inspectionContext, StackFrame: value.StackFrame, Name: name, FullName: result.FullName, Flags: result.Flags, Value: display, EditableValue: result.EditableValue, Type: typeName, Category: category, Access: value.Access, StorageType: value.StorageType, TypeModifierFlags: value.TypeModifierFlags, Address: value.Address, CustomUIVisualizers: customUIVisualizers, ExternalModules: null, DataItem: result.ToDataItem()); } } /// <returns> /// The qualified name (i.e. including containing types and namespaces) of a named, pointer, /// or array type followed by the qualified name of the actual runtime type, if provided. /// </returns> internal static string GetTypeName( DkmInspectionContext inspectionContext, DkmClrValue value, DkmClrType declaredType, DkmClrCustomTypeInfo declaredTypeInfo, bool isPointerDereference) { var declaredLmrType = declaredType.GetLmrType(); var runtimeType = value.Type; var declaredTypeName = inspectionContext.GetTypeName(declaredType, declaredTypeInfo, Formatter.NoFormatSpecifiers); // Include the runtime type if distinct. if (!declaredLmrType.IsPointer && !isPointerDereference && (!declaredLmrType.IsNullable() || value.EvalFlags.Includes(DkmEvaluationResultFlags.ExceptionThrown))) { // Generate the declared type name without tuple element names. var declaredTypeInfoNoTupleElementNames = declaredTypeInfo.WithNoTupleElementNames(); var declaredTypeNameNoTupleElementNames = (declaredTypeInfo == declaredTypeInfoNoTupleElementNames) ? declaredTypeName : inspectionContext.GetTypeName(declaredType, declaredTypeInfoNoTupleElementNames, Formatter.NoFormatSpecifiers); // Generate the runtime type name with no tuple element names and no dynamic. var runtimeTypeName = inspectionContext.GetTypeName(runtimeType, null, FormatSpecifiers: Formatter.NoFormatSpecifiers); // If the two names are distinct, include both. if (!string.Equals(declaredTypeNameNoTupleElementNames, runtimeTypeName, StringComparison.Ordinal)) // Names will reflect "dynamic", types will not. { return string.Format("{0} {{{1}}}", declaredTypeName, runtimeTypeName); } } return declaredTypeName; } internal EvalResult CreateDataItem( DkmInspectionContext inspectionContext, string name, TypeAndCustomInfo typeDeclaringMemberAndInfo, TypeAndCustomInfo declaredTypeAndInfo, DkmClrValue value, bool useDebuggerDisplay, ExpansionFlags expansionFlags, bool childShouldParenthesize, string fullName, ReadOnlyCollection<string> formatSpecifiers, DkmEvaluationResultCategory category, DkmEvaluationResultFlags flags, DkmEvaluationFlags evalFlags) { if ((evalFlags & DkmEvaluationFlags.ShowValueRaw) != 0) { formatSpecifiers = Formatter.AddFormatSpecifier(formatSpecifiers, "raw"); } Expansion expansion; // If the declared type is Nullable<T>, the value should // have no expansion if null, or be expanded as a T. var declaredType = declaredTypeAndInfo.Type; var lmrNullableTypeArg = declaredType.GetNullableTypeArgument(); if (lmrNullableTypeArg != null && !value.HasExceptionThrown()) { Debug.Assert(value.Type.GetProxyType() == null); DkmClrValue nullableValue; if (value.IsError()) { expansion = null; } else if ((nullableValue = value.GetNullableValue(lmrNullableTypeArg, inspectionContext)) == null) { Debug.Assert(declaredType.Equals(value.Type.GetLmrType())); // No expansion of "null". expansion = null; } else { value = nullableValue; Debug.Assert(lmrNullableTypeArg.Equals(value.Type.GetLmrType())); // If this is not the case, add a test for includeRuntimeTypeIfNecessary. // CONSIDER: The DynamicAttribute for the type argument should just be Skip(1) of the original flag array. expansion = this.GetTypeExpansion(inspectionContext, new TypeAndCustomInfo(DkmClrType.Create(declaredTypeAndInfo.ClrType.AppDomain, lmrNullableTypeArg)), value, ExpansionFlags.IncludeResultsView); } } else if (value.IsError() || (inspectionContext.EvaluationFlags & DkmEvaluationFlags.NoExpansion) != 0) { expansion = null; } else { expansion = DebuggerTypeProxyExpansion.CreateExpansion( this, inspectionContext, name, typeDeclaringMemberAndInfo, declaredTypeAndInfo, value, childShouldParenthesize, fullName, flags.Includes(DkmEvaluationResultFlags.ExceptionThrown) ? null : fullName, formatSpecifiers, flags, Formatter2.GetEditableValueString(value, inspectionContext, declaredTypeAndInfo.Info)); if (expansion == null) { expansion = value.HasExceptionThrown() ? this.GetTypeExpansion(inspectionContext, new TypeAndCustomInfo(value.Type), value, expansionFlags) : this.GetTypeExpansion(inspectionContext, declaredTypeAndInfo, value, expansionFlags); } } return new EvalResult( ExpansionKind.Default, name, typeDeclaringMemberAndInfo, declaredTypeAndInfo, useDebuggerDisplay: useDebuggerDisplay, value: value, displayValue: null, expansion: expansion, childShouldParenthesize: childShouldParenthesize, fullName: fullName, childFullNamePrefixOpt: flags.Includes(DkmEvaluationResultFlags.ExceptionThrown) ? null : fullName, formatSpecifiers: formatSpecifiers, category: category, flags: flags, editableValue: Formatter2.GetEditableValueString(value, inspectionContext, declaredTypeAndInfo.Info), inspectionContext: inspectionContext); } private void GetRootResultAndContinue( DkmClrValue value, WorkList workList, DkmClrType declaredType, DkmClrCustomTypeInfo declaredTypeInfo, DkmInspectionContext inspectionContext, string name, string fullName, ReadOnlyCollection<string> formatSpecifiers, CompletionRoutine<DkmEvaluationResult> completionRoutine) { Debug.Assert(formatSpecifiers != null); var type = value.Type.GetLmrType(); if (type.IsTypeVariables()) { Debug.Assert(type.Equals(declaredType.GetLmrType())); var declaredTypeAndInfo = new TypeAndCustomInfo(declaredType, declaredTypeInfo); var expansion = new TypeVariablesExpansion(declaredTypeAndInfo); var dataItem = new EvalResult( ExpansionKind.Default, name, typeDeclaringMemberAndInfo: default(TypeAndCustomInfo), declaredTypeAndInfo: declaredTypeAndInfo, useDebuggerDisplay: false, value: value, displayValue: null, expansion: expansion, childShouldParenthesize: false, fullName: null, childFullNamePrefixOpt: null, formatSpecifiers: Formatter.NoFormatSpecifiers, category: DkmEvaluationResultCategory.Data, flags: DkmEvaluationResultFlags.ReadOnly, editableValue: null, inspectionContext: inspectionContext); Debug.Assert(dataItem.Flags == (DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.Expandable)); // Note: We're not including value.EvalFlags in Flags parameter // below (there shouldn't be a reason to do so). completionRoutine(DkmSuccessEvaluationResult.Create( InspectionContext: inspectionContext, StackFrame: value.StackFrame, Name: Resources.TypeVariablesName, FullName: dataItem.FullName, Flags: dataItem.Flags, Value: "", EditableValue: null, Type: "", Category: dataItem.Category, Access: value.Access, StorageType: value.StorageType, TypeModifierFlags: value.TypeModifierFlags, Address: value.Address, CustomUIVisualizers: null, ExternalModules: null, DataItem: dataItem.ToDataItem())); } else if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.ResultsOnly) != 0) { var dataItem = ResultsViewExpansion.CreateResultsOnlyRow( inspectionContext, name, fullName, formatSpecifiers, declaredType, declaredTypeInfo, value, this); CreateEvaluationResultAndContinue( dataItem, workList, inspectionContext, value.StackFrame, completionRoutine); } else if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.DynamicView) != 0) { var dataItem = DynamicViewExpansion.CreateMembersOnlyRow( inspectionContext, name, value, this); CreateEvaluationResultAndContinue( dataItem, workList, inspectionContext, value.StackFrame, completionRoutine); } else { var dataItem = ResultsViewExpansion.CreateResultsOnlyRowIfSynthesizedEnumerable( inspectionContext, name, fullName, formatSpecifiers, declaredType, declaredTypeInfo, value, this); if (dataItem != null) { CreateEvaluationResultAndContinue( dataItem, workList, inspectionContext, value.StackFrame, completionRoutine); } else { var useDebuggerDisplay = (inspectionContext.EvaluationFlags & NotRoot) != 0; var expansionFlags = (inspectionContext.EvaluationFlags & NoResults) != 0 ? ExpansionFlags.IncludeBaseMembers : ExpansionFlags.All; dataItem = CreateDataItem( inspectionContext, name, typeDeclaringMemberAndInfo: default(TypeAndCustomInfo), declaredTypeAndInfo: new TypeAndCustomInfo(declaredType, declaredTypeInfo), value: value, useDebuggerDisplay: useDebuggerDisplay, expansionFlags: expansionFlags, childShouldParenthesize: (fullName == null) ? false : FullNameProvider.ClrExpressionMayRequireParentheses(inspectionContext, fullName), fullName: fullName, formatSpecifiers: formatSpecifiers, category: DkmEvaluationResultCategory.Other, flags: value.EvalFlags, evalFlags: inspectionContext.EvaluationFlags); GetResultAndContinue(dataItem, workList, declaredType, declaredTypeInfo, inspectionContext, useDebuggerDisplay, completionRoutine); } } } private void GetResultAndContinue( EvalResult result, WorkList workList, DkmClrType declaredType, DkmClrCustomTypeInfo declaredTypeInfo, DkmInspectionContext inspectionContext, bool useDebuggerDisplay, CompletionRoutine<DkmEvaluationResult> completionRoutine) { var value = result.Value; // Value may have been replaced (specifically, for Nullable<T>). DebuggerDisplayInfo displayInfo; if (value.TryGetDebuggerDisplayInfo(out displayInfo)) { var targetType = displayInfo.TargetType; var attribute = displayInfo.Attribute; CompletionRoutine<Exception> onException = e => completionRoutine(CreateEvaluationResultFromException(e, result, inspectionContext)); var innerWorkList = workList.InnerWorkList; EvaluateDebuggerDisplayStringAndContinue(value, innerWorkList, inspectionContext, targetType, attribute.Name, displayName => EvaluateDebuggerDisplayStringAndContinue(value, innerWorkList, inspectionContext, targetType, attribute.Value, displayValue => EvaluateDebuggerDisplayStringAndContinue(value, innerWorkList, inspectionContext, targetType, attribute.TypeName, displayType => workList.ContinueWith(() => completionRoutine(GetResult(inspectionContext, result, declaredType, declaredTypeInfo, displayName.Result, displayValue.Result, displayType.Result, useDebuggerDisplay))), onException), onException), onException); } else { completionRoutine(GetResult(inspectionContext, result, declaredType, declaredTypeInfo, displayName: null, displayValue: null, displayType: null, useDebuggerDisplay: false)); } } private static void EvaluateDebuggerDisplayStringAndContinue( DkmClrValue value, DkmWorkList workList, DkmInspectionContext inspectionContext, DkmClrType targetType, string str, CompletionRoutine<DkmEvaluateDebuggerDisplayStringAsyncResult> onCompleted, CompletionRoutine<Exception> onException) { DkmCompletionRoutine<DkmEvaluateDebuggerDisplayStringAsyncResult> completionRoutine = result => { try { onCompleted(result); } catch (Exception e) { onException(e); } }; if (str == null) { completionRoutine(default(DkmEvaluateDebuggerDisplayStringAsyncResult)); } else { value.EvaluateDebuggerDisplayString(workList, inspectionContext, targetType, str, completionRoutine); } } private DkmEvaluationResult GetResult( DkmInspectionContext inspectionContext, EvalResult result, DkmClrType declaredType, DkmClrCustomTypeInfo declaredTypeInfo, string displayName, string displayValue, string displayType, bool useDebuggerDisplay) { var name = result.Name; Debug.Assert(name != null); var typeDeclaringMemberAndInfo = result.TypeDeclaringMemberAndInfo; // Note: Don't respect the debugger display name on the root element: // 1) In the Watch window, that's where the user's text goes. // 2) In the Locals window, that's where the local name goes. // Note: Dev12 respects the debugger display name in the Locals window, // but not in the Watch window, but we can't distinguish and this // behavior seems reasonable. if (displayName != null && useDebuggerDisplay) { name = displayName; } else if (typeDeclaringMemberAndInfo.Type != null) { name = GetQualifiedMemberName(inspectionContext, typeDeclaringMemberAndInfo, name, FullNameProvider); } var value = result.Value; string display; if (value.HasExceptionThrown()) { display = result.DisplayValue ?? value.GetExceptionMessage(inspectionContext, result.FullNameWithoutFormatSpecifiers ?? result.Name); } else if (displayValue != null) { display = value.IncludeObjectId(displayValue); } else { display = value.GetValueString(inspectionContext, Formatter.NoFormatSpecifiers); } var typeName = displayType ?? GetTypeName(inspectionContext, value, declaredType, declaredTypeInfo, result.Kind == ExpansionKind.PointerDereference); return CreateEvaluationResult(inspectionContext, value, name, typeName, display, result); } private void GetEvaluationResultsAndContinue( DkmEvaluationResult parent, ArrayBuilder<EvalResult> rows, DkmEvaluationResult[] results, int index, int numRows, WorkList workList, DkmInspectionContext inspectionContext, CompletionRoutine onCompleted, CompletionRoutine<Exception> onException) { DkmCompletionRoutine<DkmEvaluationAsyncResult> completionRoutine = result => { try { results[index] = result.Result; GetEvaluationResultsAndContinue(parent, rows, results, index + 1, numRows, workList, inspectionContext, onCompleted, onException); } catch (Exception e) { onException(e); } }; if (index < numRows) { GetChild( parent, workList, rows[index], child => workList.ContinueWith(() => completionRoutine(child))); } else { onCompleted(); } } internal Expansion GetTypeExpansion( DkmInspectionContext inspectionContext, TypeAndCustomInfo declaredTypeAndInfo, DkmClrValue value, ExpansionFlags flags) { var declaredType = declaredTypeAndInfo.Type; Debug.Assert(!declaredType.IsTypeVariables()); if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.NoExpansion) != 0) { return null; } var runtimeType = value.Type.GetLmrType(); // If the value is an array, expand the array elements. if (runtimeType.IsArray) { var sizes = value.ArrayDimensions; if (sizes == null) { // Null array. No expansion. return null; } var lowerBounds = value.ArrayLowerBounds; Type elementType; DkmClrCustomTypeInfo elementTypeInfo; if (declaredType.IsArray) { elementType = declaredType.GetElementType(); elementTypeInfo = CustomTypeInfo.SkipOne(declaredTypeAndInfo.Info); } else { elementType = runtimeType.GetElementType(); elementTypeInfo = null; } return ArrayExpansion.CreateExpansion(new TypeAndCustomInfo(DkmClrType.Create(declaredTypeAndInfo.ClrType.AppDomain, elementType), elementTypeInfo), sizes, lowerBounds); } if (this.IsPrimitiveType(runtimeType)) { return null; } if (declaredType.IsFunctionPointer()) { // Function pointers have no expansion return null; } if (declaredType.IsPointer) { // If this assert fails, the element type info is just .SkipOne(). Debug.Assert(declaredTypeAndInfo.Info?.PayloadTypeId != CustomTypeInfo.PayloadTypeId); var elementType = declaredType.GetElementType(); return value.IsNull || elementType.IsVoid() ? null : new PointerDereferenceExpansion(new TypeAndCustomInfo(DkmClrType.Create(declaredTypeAndInfo.ClrType.AppDomain, elementType))); } if (value.EvalFlags.Includes(DkmEvaluationResultFlags.ExceptionThrown) && runtimeType.IsEmptyResultsViewException()) { // The value is an exception thrown expanding an empty // IEnumerable. Use the runtime type of the exception and // skip base types. (This matches the native EE behavior // to expose a single property from the exception.) flags &= ~ExpansionFlags.IncludeBaseMembers; } int cardinality; if (runtimeType.IsTupleCompatible(out cardinality)) { return TupleExpansion.CreateExpansion(inspectionContext, declaredTypeAndInfo, value, cardinality); } return MemberExpansion.CreateExpansion(inspectionContext, declaredTypeAndInfo, value, flags, TypeHelpers.IsVisibleMember, this); } private static DkmEvaluationResult CreateEvaluationResultFromException(Exception e, EvalResult result, DkmInspectionContext inspectionContext) { return DkmFailedEvaluationResult.Create( inspectionContext, result.Value.StackFrame, Name: result.Name, FullName: null, ErrorMessage: e.Message, Flags: DkmEvaluationResultFlags.None, Type: null, DataItem: null); } private static string GetQualifiedMemberName( DkmInspectionContext inspectionContext, TypeAndCustomInfo typeDeclaringMember, string memberName, IDkmClrFullNameProvider fullNameProvider) { var typeName = fullNameProvider.GetClrTypeName(inspectionContext, typeDeclaringMember.ClrType, typeDeclaringMember.Info) ?? inspectionContext.GetTypeName(typeDeclaringMember.ClrType, typeDeclaringMember.Info, Formatter.NoFormatSpecifiers); return typeDeclaringMember.Type.IsInterface ? $"{typeName}.{memberName}" : $"{memberName} ({typeName})"; } // Track remaining evaluations so that each subsequent evaluation // is executed at the entry point from the host rather than on the // callstack of the previous evaluation. private sealed class WorkList { private enum State { Initialized, Executing, Executed } internal readonly DkmWorkList InnerWorkList; private readonly CompletionRoutine<Exception> _onException; private CompletionRoutine _completionRoutine; private State _state; internal WorkList(DkmWorkList workList, CompletionRoutine<Exception> onException) { InnerWorkList = workList; _onException = onException; _state = State.Initialized; } /// <summary> /// Run the continuation synchronously if there is no current /// continuation. Otherwise hold on to the continuation for /// the current execution to complete. /// </summary> internal void ContinueWith(CompletionRoutine completionRoutine) { Debug.Assert(_completionRoutine == null); _completionRoutine = completionRoutine; if (_state != State.Executing) { Execute(); } } private void Execute() { Debug.Assert(_state != State.Executing); _state = State.Executing; while (_completionRoutine != null) { var completionRoutine = _completionRoutine; _completionRoutine = null; try { completionRoutine(); } catch (Exception e) { _onException(e); } } _state = State.Executed; } } } }
// Copyright 2009 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; using System.Globalization; using Minibench.Framework; namespace NodaTime.Benchmarks.NodaTimeTests { internal class LocalDateTimeBenchmarks { private static readonly DateTime SampleDateTime = new DateTime(2009, 12, 26, 10, 8, 30); private static readonly LocalDateTime Sample = new LocalDateTime(2009, 12, 26, 10, 8, 30); private static readonly CultureInfo MutableCulture = (CultureInfo) CultureInfo.InvariantCulture.Clone(); private static readonly Period SampleTimePeriod = new PeriodBuilder { Hours = 10, Minutes = 4, Seconds = 5, Milliseconds = 20, Ticks = 30 }.Build(); private static readonly Period SampleDatePeriod = new PeriodBuilder { Years = 1, Months = 2, Weeks = 3, Days = 4 }.Build(); private static readonly Period SampleMixedPeriod = SampleDatePeriod + SampleTimePeriod; [Benchmark] public void ConstructionToMinute() { new LocalDateTime(2009, 12, 26, 10, 8).Consume(); } [Benchmark] public void ConstructionToSecond() { new LocalDateTime(2009, 12, 26, 10, 8, 30).Consume(); } [Benchmark] public void ConstructionToTick() { new LocalDateTime(2009, 12, 26, 10, 8, 30, 0, 0).Consume(); } [Benchmark] public void FromDateTime() { LocalDateTime.FromDateTime(SampleDateTime); } [Benchmark] public void ToDateTimeUnspecified() { Sample.ToDateTimeUnspecified(); } [Benchmark] public void Year() { Sample.Year.Consume(); } [Benchmark] public void Month() { Sample.Month.Consume(); } [Benchmark] public void DayOfMonth() { Sample.Day.Consume(); } [Benchmark] public void IsoDayOfWeek() { Sample.IsoDayOfWeek.Consume(); } [Benchmark] public void DayOfYear() { Sample.DayOfYear.Consume(); } [Benchmark] public void Hour() { Sample.Hour.Consume(); } [Benchmark] public void Minute() { Sample.Minute.Consume(); } [Benchmark] public void Second() { Sample.Second.Consume(); } [Benchmark] public void Millisecond() { Sample.Millisecond.Consume(); } [Benchmark] public void Date() { Sample.Date.Consume(); } [Benchmark] public void TimeOfDay() { Sample.TimeOfDay.Consume(); } [Benchmark] public void TickOfDay() { Sample.TickOfDay.Consume(); } [Benchmark] public void TickOfSecond() { Sample.TickOfSecond.Consume(); } [Benchmark] public void WeekOfWeekYear() { Sample.WeekOfWeekYear.Consume(); } [Benchmark] public void WeekYear() { Sample.WeekYear.Consume(); } [Benchmark] public void ClockHourOfHalfDay() { Sample.ClockHourOfHalfDay.Consume(); } [Benchmark] public void Era() { Sample.Era.Consume(); } [Benchmark] public void YearOfEra() { Sample.YearOfEra.Consume(); } [Benchmark] public void ToString_Parameterless() { Sample.ToString(); } [Benchmark] public void ToString_ExplicitPattern_Invariant() { Sample.ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture); } /// <summary> /// This test will involve creating a new NodaFormatInfo for each iteration. /// </summary> [Benchmark] public void ToString_ExplicitPattern_MutableCulture() { Sample.ToString("dd/MM/yyyy HH:mm:ss", MutableCulture); } [Benchmark] public void PlusYears() { Sample.PlusYears(3).Consume(); } [Benchmark] public void PlusMonths() { Sample.PlusMonths(3).Consume(); } [Benchmark] public void PlusWeeks() { Sample.PlusWeeks(3).Consume(); } [Benchmark] public void PlusDays() { Sample.PlusDays(3).Consume(); } [Benchmark] public void PlusHours() { Sample.PlusHours(3).Consume(); } public void PlusHours_OverflowDay() { Sample.PlusHours(33).Consume(); } [Benchmark] public void PlusHours_Negative() { Sample.PlusHours(-3).Consume(); } [Benchmark] public void PlusHours_UnderflowDay() { Sample.PlusHours(-33).Consume(); } [Benchmark] public void PlusMinutes() { Sample.PlusMinutes(3).Consume(); } [Benchmark] public void PlusSeconds() { Sample.PlusSeconds(3).Consume(); } [Benchmark] public void PlusMilliseconds() { Sample.PlusMilliseconds(3).Consume(); } [Benchmark] public void PlusTicks() { Sample.PlusTicks(3).Consume(); } [Benchmark] public void PlusDatePeriod() { (Sample + SampleDatePeriod).Consume(); } [Benchmark] public void MinusDatePeriod() { (Sample - SampleDatePeriod).Consume(); } [Benchmark] public void PlusTimePeriod() { (Sample + SampleTimePeriod).Consume(); } [Benchmark] public void MinusTimePeriod() { (Sample - SampleTimePeriod).Consume(); } [Benchmark] public void PlusMixedPeriod() { (Sample + SampleMixedPeriod).Consume(); } [Benchmark] public void MinusMixedPeriod() { (Sample - SampleMixedPeriod).Consume(); } #if !NO_INTERNALS [Benchmark] public void ToLocalInstant() { Sample.ToLocalInstant().Consume(); } #endif } }
using System; namespace DoFactory.GangOfFour.State.NETOptimized { /// <summary> /// MainApp startup class for .NET optimized /// State Design Pattern. /// </summary> class MainApp { /// <summary> /// Entry point into console application. /// </summary> static void Main() { // Open a new account var account = new Account("Jim Johnson"); // Apply financial transactions account.Deposit(500.0); account.Deposit(300.0); account.Deposit(550.0); account.PayInterest(); account.Withdraw(2000.00); account.Withdraw(1100.00); // Wait for user Console.ReadKey(); } } /// <summary> /// The 'State' abstract class /// </summary> abstract class State { protected double interest; protected double lowerLimit; protected double upperLimit; // Gets or sets the account public Account Account { get; set; } // Gets or sets the balance public double Balance { get; set; } public abstract void Deposit(double amount); public abstract void Withdraw(double amount); public abstract void PayInterest(); } /// <summary> /// A 'ConcreteState' class /// <remarks> /// Red state indicates account is overdrawn /// </remarks> /// </summary> class RedState : State { double serviceFee; // Constructor public RedState(State state) { Balance = state.Balance; Account = state.Account; Initialize(); } private void Initialize() { // Should come from a datasource interest = 0.0; lowerLimit = -100.0; upperLimit = 0.0; serviceFee = 15.00; } public override void Deposit(double amount) { Balance += amount; StateChangeCheck(); } public override void Withdraw(double amount) { amount = amount - serviceFee; Console.WriteLine("No funds available for withdrawal!"); } public override void PayInterest() { // No interest is paid } private void StateChangeCheck() { if (Balance > upperLimit) { Account.State = new SilverState(this); } } } /// <summary> /// A 'ConcreteState' class /// <remarks> /// Silver state is non-interest bearing state /// </remarks> /// </summary> class SilverState : State { // Overloaded constructors public SilverState(State state) : this(state.Balance, state.Account) { } public SilverState(double balance, Account account) { Balance = balance; Account = account; Initialize(); } private void Initialize() { // Should come from a datasource interest = 0.0; lowerLimit = 0.0; upperLimit = 1000.0; } public override void Deposit(double amount) { Balance += amount; StateChangeCheck(); } public override void Withdraw(double amount) { Balance -= amount; StateChangeCheck(); } public override void PayInterest() { Balance += interest * Balance; StateChangeCheck(); } private void StateChangeCheck() { if (Balance < lowerLimit) { Account.State = new RedState(this); } else if (Balance > upperLimit) { Account.State = new GoldState(this); } } } /// <summary> /// A 'ConcreteState' class /// <remarks> /// Gold incidates interest bearing state /// </remarks> /// </summary> class GoldState : State { // Overloaded constructors public GoldState(State state) : this(state.Balance, state.Account) { } public GoldState(double balance, Account account) { Balance = balance; Account = account; Initialize(); } private void Initialize() { // Should come from a database interest = 0.05; lowerLimit = 1000.0; upperLimit = 10000000.0; } public override void Deposit(double amount) { Balance += amount; StateChangeCheck(); } public override void Withdraw(double amount) { Balance -= amount; StateChangeCheck(); } public override void PayInterest() { Balance += interest * Balance; StateChangeCheck(); } private void StateChangeCheck() { if (Balance < 0.0) { Account.State = new RedState(this); } else if (Balance < lowerLimit) { Account.State = new SilverState(this); } } } /// <summary> /// The 'Context' class /// </summary> class Account { string owner; // Constructor public Account(string owner) { // New accounts are 'Silver' by default this.owner = owner; this.State = new SilverState(0.0, this); } // Gets the balance public double Balance { get { return State.Balance; } } // Gets or sets state public State State { get; set; } public void Deposit(double amount) { State.Deposit(amount); Console.WriteLine("Deposited {0:C} --- ", amount); Console.WriteLine(" Balance = {0:C}", this.Balance); Console.WriteLine(" Status = {0}", this.State.GetType().Name); Console.WriteLine(""); } public void Withdraw(double amount) { State.Withdraw(amount); Console.WriteLine("Withdrew {0:C} --- ", amount); Console.WriteLine(" Balance = {0:C}", this.Balance); Console.WriteLine(" Status = {0}\n", this.State.GetType().Name); } public void PayInterest() { State.PayInterest(); Console.WriteLine("Interest Paid --- "); Console.WriteLine(" Balance = {0:C}", this.Balance); Console.WriteLine(" Status = {0}\n", this.State.GetType().Name); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Globalization; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNetCore.Testing; using Xunit; namespace Microsoft.AspNetCore.Mvc.FunctionalTests { public class TagHelpersTest : IClassFixture<MvcTestFixture<TagHelpersWebSite.Startup>>, IClassFixture<MvcEncodedTestFixture<TagHelpersWebSite.Startup>> { // Some tests require comparing the actual response body against an expected response baseline // so they require a reference to the assembly on which the resources are located, in order to // make the tests less verbose, we get a reference to the assembly with the resources and we // use it on all the rest of the tests. private static readonly Assembly _resourcesAssembly = typeof(TagHelpersTest).GetTypeInfo().Assembly; public TagHelpersTest( MvcTestFixture<TagHelpersWebSite.Startup> fixture, MvcEncodedTestFixture<TagHelpersWebSite.Startup> encodedFixture) { Client = fixture.CreateDefaultClient(); EncodedClient = encodedFixture.CreateDefaultClient(); } public HttpClient Client { get; } public HttpClient EncodedClient { get; } [Theory] [InlineData("Index")] [InlineData("About")] [InlineData("Help")] [InlineData("UnboundDynamicAttributes")] public async Task CanRenderViewsWithTagHelpers(string action) { // Arrange var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8"); var outputFile = "compiler/resources/TagHelpersWebSite.Home." + action + ".html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); // Act // The host is not important as everything runs in memory and tests are isolated from each other. var response = await Client.GetAsync("http://localhost/Home/" + action); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedMediaType, response.Content.Headers.ContentType); var responseContent = await response.Content.ReadAsStringAsync(); ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile, expectedContent, responseContent); } [ConditionalTheory(Skip = "https://github.com/dotnet/aspnetcore/issues/10423")] [InlineData("GlobbingTagHelpers")] [InlineData("ViewComponentTagHelpers")] public Task CanRenderViewsWithTagHelpersNotReadyForHelix(string action) => CanRenderViewsWithTagHelpers(action); [Fact] public async Task GivesCorrectCallstackForSyncronousCalls() { // Regression test for https://github.com/dotnet/aspnetcore/issues/15367 // Arrange var exception = await Assert.ThrowsAsync<HttpRequestException>(async () => await Client.GetAsync("http://localhost/Home/MyHtml")); // Assert Assert.Equal("Should be visible", exception.InnerException.InnerException.Message); } [Fact] public async Task CanRenderViewsWithTagHelpersAndUnboundDynamicAttributes_Encoded() { // Arrange var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8"); var outputFile = "compiler/resources/TagHelpersWebSite.Home.UnboundDynamicAttributes.Encoded.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); // Act // The host is not important as everything runs in memory and tests are isolated from each other. var response = await EncodedClient.GetAsync("http://localhost/Home/UnboundDynamicAttributes"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedMediaType, response.Content.Headers.ContentType); var responseContent = await response.Content.ReadAsStringAsync(); ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile, expectedContent, responseContent); } [Fact] public async Task ReRegisteringAntiforgeryTokenInsideFormTagHelper_DoesNotAddDuplicateAntiforgeryTokenFields() { // Arrange var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8"); var outputFile = "compiler/resources/TagHelpersWebSite.Employee.DuplicateAntiforgeryTokenRegistration.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); // Act var response = await Client.GetAsync("http://localhost/Employee/DuplicateAntiforgeryTokenRegistration"); var responseContent = await response.Content.ReadAsStringAsync(); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedMediaType, response.Content.Headers.ContentType); responseContent = responseContent.Trim(); var forgeryToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken( responseContent, "/Employee/DuplicateAntiforgeryTokenRegistration"); ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile, expectedContent, responseContent, forgeryToken); } public static TheoryData TagHelpersAreInheritedFromViewImportsPagesData { get { // action, expected return new TheoryData<string, string> { { "NestedViewImportsTagHelper", @"<root>root-content</root> <nested>nested-content</nested>" }, { "ViewWithLayoutAndNestedTagHelper", @"layout:<root>root-content</root> <nested>nested-content</nested>" }, { "ViewWithInheritedRemoveTagHelper", @"layout:<root>root-content</root> page:<root/> <nested>nested-content</nested>" }, { "ViewWithInheritedTagHelperPrefix", @"layout:<root>root-content</root> page:<root>root-content</root>" }, { "ViewWithOverriddenTagHelperPrefix", @"layout:<root>root-content</root> page:<root>root-content</root>" }, { "ViewWithNestedInheritedTagHelperPrefix", @"layout:<root>root-content</root> page:<root>root-content</root>" }, { "ViewWithNestedOverriddenTagHelperPrefix", @"layout:<root>root-content</root> page:<root>root-content</root>" }, }; } } [Theory] [MemberData(nameof(TagHelpersAreInheritedFromViewImportsPagesData))] public async Task TagHelpersAreInheritedFromViewImportsPages(string action, string expected) { // Arrange & Act var result = await Client.GetStringAsync("http://localhost/Home/" + action); // Assert Assert.Equal(expected, result.Trim(), ignoreLineEndingDifferences: true); } [Fact] public async Task DefaultInheritedTagsCanBeRemoved() { // Arrange var expected = @"<a href=""~/VirtualPath"">Virtual path</a>"; var result = await Client.GetStringAsync("RemoveDefaultInheritedTagHelpers"); // Assert Assert.Equal(expected, result.Trim(), ignoreLineEndingDifferences: true); } [Fact] public async Task ViewsWithModelMetadataAttributes_CanRenderForm() { // Arrange var outputFile = "compiler/resources/TagHelpersWebSite.Employee.Create.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); // Act var response = await Client.GetAsync("http://localhost/Employee/Create"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var responseContent = await response.Content.ReadAsStringAsync(); ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile, expectedContent, responseContent); } [Fact] public async Task ViewsWithModelMetadataAttributes_CanRenderPostedValue() { // Arrange var outputFile = "compiler/resources/TagHelpersWebSite.Employee.Details.AfterCreate.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); var validPostValues = new Dictionary<string, string> { { "FullName", "Boo" }, { "Gender", "M" }, { "Age", "22" }, { "EmployeeId", "0" }, { "JoinDate", "2014-12-01" }, { "Email", "a@b.com" }, }; var postContent = new FormUrlEncodedContent(validPostValues); // Act var response = await Client.PostAsync("http://localhost/Employee/Create", postContent); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var responseContent = await response.Content.ReadAsStringAsync(); ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile, expectedContent, responseContent); } [Fact] public async Task ViewsWithModelMetadataAttributes_CanHandleInvalidData() { // Arrange var outputFile = "compiler/resources/TagHelpersWebSite.Employee.Create.Invalid.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); var validPostValues = new Dictionary<string, string> { { "FullName", "Boo" }, { "Gender", "M" }, { "Age", "1000" }, { "EmployeeId", "0" }, { "Email", "a@b.com" }, { "Salary", "z" }, }; var postContent = new FormUrlEncodedContent(validPostValues); // Act var response = await Client.PostAsync("http://localhost/Employee/Create", postContent); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var responseContent = await response.Content.ReadAsStringAsync(); ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile, expectedContent, responseContent); } [Theory] [InlineData("Index")] [InlineData("CustomEncoder")] [InlineData("NullEncoder")] [InlineData("TwoEncoders")] [InlineData("ThreeEncoders")] public async Task EncodersPages_ReturnExpectedContent(string actionName) { // Arrange var outputFile = $"compiler/resources/TagHelpersWebSite.Encoders.{ actionName }.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); // Act var response = await Client.GetAsync($"/Encoders/{ actionName }"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var responseContent = await response.Content.ReadAsStringAsync(); ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile, expectedContent, responseContent); } } }
// // TextEntryBackend.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Backends; using Xwt.Drawing; namespace Xwt.GtkBackend { public partial class TextEntryBackend : WidgetBackend, ITextEntryBackend { public override void Initialize () { Widget = new Gtk.Entry (); Widget.Show (); } protected virtual Gtk.Entry TextEntry { get { return (Gtk.Entry)base.Widget; } } protected new Gtk.Entry Widget { get { return TextEntry; } set { base.Widget = value; } } protected new ITextBoxEventSink EventSink { get { return (ITextBoxEventSink)base.EventSink; } } public string Text { get { return Widget.Text; } set { Widget.Text = value ?? ""; } // null value causes GTK error } public Alignment TextAlignment { get { if (Widget.Xalign == 0) return Alignment.Start; else if (Widget.Xalign == 1) return Alignment.End; else return Alignment.Center; } set { switch (value) { case Alignment.Start: Widget.Xalign = 0; break; case Alignment.End: Widget.Xalign = 1; break; case Alignment.Center: Widget.Xalign = 0.5f; break; } } } public override Color BackgroundColor { get { return base.BackgroundColor; } set { base.BackgroundColor = value; Widget.ModifyBase (Gtk.StateType.Normal, value.ToGtkValue ()); } } public bool ReadOnly { get { return !Widget.IsEditable; } set { Widget.IsEditable = !value; } } public bool ShowFrame { get { return Widget.HasFrame; } set { Widget.HasFrame = value; } } public int CursorPosition { get { return Widget.Position; } set { Widget.Position = value; } } public int SelectionStart { get { int start, end; Widget.GetSelectionBounds (out start, out end); return start; } set { int cacheStart = SelectionStart; int cacheLength = SelectionLength; Widget.GrabFocus (); if (String.IsNullOrEmpty (Text)) return; Widget.SelectRegion (value, value + cacheLength); if (cacheStart != value) HandleSelectionChanged (); } } public int SelectionLength { get { int start, end; Widget.GetSelectionBounds (out start, out end); return end - start; } set { int cacheStart = SelectionStart; int cacheLength = SelectionLength; Widget.GrabFocus (); if (String.IsNullOrEmpty (Text)) return; Widget.SelectRegion (cacheStart, cacheStart + value); if (cacheLength != value) HandleSelectionChanged (); } } public string SelectedText { get { int start = SelectionStart; int end = start + SelectionLength; if (start == end) return String.Empty; try { return Text.Substring (start, end - start); } catch { return String.Empty; } } set { int cacheSelStart = SelectionStart; int pos = cacheSelStart; if (SelectionLength > 0) { Widget.DeleteSelection (); } Widget.InsertText (value, ref pos); Widget.GrabFocus (); Widget.SelectRegion (cacheSelStart, pos); HandleSelectionChanged (); } } public bool MultiLine { get; set; } public override void EnableEvent (object eventId) { base.EnableEvent (eventId); if (eventId is TextBoxEvent) { switch ((TextBoxEvent)eventId) { case TextBoxEvent.Changed: Widget.Changed += HandleChanged; break; case TextBoxEvent.Activated: Widget.Activated += HandleActivated; break; case TextBoxEvent.SelectionChanged: enableSelectionChangedEvent = true; Widget.MoveCursor += HandleMoveCursor; Widget.ButtonPressEvent += HandleButtonPressEvent; Widget.ButtonReleaseEvent += HandleButtonReleaseEvent; Widget.MotionNotifyEvent += HandleMotionNotifyEvent; break; } } } public override void DisableEvent (object eventId) { base.DisableEvent (eventId); if (eventId is TextBoxEvent) { switch ((TextBoxEvent)eventId) { case TextBoxEvent.Changed: Widget.Changed -= HandleChanged; break; case TextBoxEvent.Activated: Widget.Activated -= HandleActivated; break; case TextBoxEvent.SelectionChanged: enableSelectionChangedEvent = false; Widget.MoveCursor -= HandleMoveCursor; Widget.ButtonPressEvent -= HandleButtonPressEvent; Widget.ButtonReleaseEvent -= HandleButtonReleaseEvent; Widget.MotionNotifyEvent -= HandleMotionNotifyEvent; break; } } } void HandleChanged (object sender, EventArgs e) { ApplicationContext.InvokeUserCode (delegate { EventSink.OnChanged (); EventSink.OnSelectionChanged (); }); } void HandleActivated (object sender, EventArgs e) { ApplicationContext.InvokeUserCode (delegate { EventSink.OnActivated (); }); } bool enableSelectionChangedEvent; void HandleSelectionChanged () { if (enableSelectionChangedEvent) ApplicationContext.InvokeUserCode (delegate { EventSink.OnSelectionChanged (); }); } void HandleMoveCursor (object sender, EventArgs e) { HandleSelectionChanged (); } int cacheSelectionStart, cacheSelectionLength; bool isMouseSelection; [GLib.ConnectBefore] void HandleButtonPressEvent (object o, Gtk.ButtonPressEventArgs args) { if (args.Event.Button == 1) { HandleSelectionChanged (); cacheSelectionStart = SelectionStart; cacheSelectionLength = SelectionLength; isMouseSelection = true; } } [GLib.ConnectBefore] void HandleMotionNotifyEvent (object o, Gtk.MotionNotifyEventArgs args) { if (isMouseSelection) if (cacheSelectionStart != SelectionStart || cacheSelectionLength != SelectionLength) HandleSelectionChanged (); cacheSelectionStart = SelectionStart; cacheSelectionLength = SelectionLength; } [GLib.ConnectBefore] void HandleButtonReleaseEvent (object o, Gtk.ButtonReleaseEventArgs args) { if (args.Event.Button == 1) { isMouseSelection = false; HandleSelectionChanged (); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace BugLogger.Services.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Xml; using System.Diagnostics; using System.Collections; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Globalization; using Microsoft.Build.Framework; using Microsoft.Build.BuildEngine.Shared; using error = Microsoft.Build.BuildEngine.Shared.ErrorUtilities; namespace Microsoft.Build.BuildEngine { /// <summary> /// This class represents a single task. /// </summary> /// <owner>rgoel</owner> public class BuildTask { #region Member Data // The task XML element, if this is a persisted target. private XmlElement taskElement = null; // This is the "Condition" attribute on the task element. private XmlAttribute conditionAttribute = null; // This is the "ContinueOnError" attribute on the task element. private XmlAttribute continueOnErrorAttribute = null; // The target to which this task belongs. private Target parentTarget= null; // The name of the task. private string taskName = String.Empty; // If this is a persisted task element, this boolean tells us whether // it came from the main project file or an imported project file. private bool importedFromAnotherProject = false; // This is the optional host object for this particular task. The actual task // object will get passed this host object, and can communicate with it as it // wishes. Although it is declared generically as an "Object" here, the actual // task will cast it to whatever it expects. private ITaskHost hostObject = null; #endregion #region Constructors /// <summary> /// This constructor initializes a persisted task from an existing task /// element which exists either in the main project file or one of the /// imported files. /// </summary> /// <param name="taskElement"></param> /// <param name="parentTarget"></param> /// <param name="importedFromAnotherProject"></param> /// <owner>rgoel</owner> internal BuildTask ( XmlElement taskElement, Target parentTarget, bool importedFromAnotherProject ) { // Make sure a valid node has been given to us. error.VerifyThrow(taskElement != null, "Need a valid XML node."); // Make sure a valid target has been given to us. error.VerifyThrow(parentTarget != null, "Need a valid target parent."); this.taskElement = taskElement; this.parentTarget = parentTarget; this.conditionAttribute = null; this.continueOnErrorAttribute = null; this.importedFromAnotherProject = importedFromAnotherProject; // Loop through all the attributes on the task element. foreach (XmlAttribute taskAttribute in taskElement.Attributes) { switch (taskAttribute.Name) { case XMakeAttributes.condition: this.conditionAttribute = taskAttribute; break; case XMakeAttributes.continueOnError: this.continueOnErrorAttribute = taskAttribute; break; // this only makes sense in the context of the new OM, // so just ignore it. case XMakeAttributes.msbuildRuntime: // do nothing break; // this only makes sense in the context of the new OM, // so just ignore it. case XMakeAttributes.msbuildArchitecture: // do nothing break; } } this.taskName = taskElement.Name; } /// <summary> /// Default constructor. This is not allowed, because it leaves the /// BuildTask in a bad state. But we have to have it, otherwise FXCop /// complains. /// </summary> /// <owner>rgoel</owner> private BuildTask ( ) { // Not allowed. } #endregion #region Properties /// <summary> /// Read-only accessor for XML element representing this task. /// </summary> /// <value></value> /// <owner>RGoel</owner> internal XmlElement TaskXmlElement { get { return this.taskElement; } } /// <summary> /// Accessor for the task's "name" element. /// </summary> /// <owner>RGoel</owner> public string Name { get { return this.taskName; } } /// <summary> /// Accessor for the task's "condition". /// </summary> /// <owner>RGoel</owner> public string Condition { get { return (this.conditionAttribute == null) ? String.Empty : this.conditionAttribute.Value; } set { // If this Task object is not actually represented by a // task element in the project file, then do not allow // the caller to set the condition. error.VerifyThrowInvalidOperation(this.taskElement != null, "CannotSetCondition"); // If this task was imported from another project, we don't allow modifying it. error.VerifyThrowInvalidOperation(!this.importedFromAnotherProject, "CannotModifyImportedProjects"); this.conditionAttribute = ProjectXmlUtilities.SetOrRemoveAttribute(taskElement, XMakeAttributes.condition, value); this.MarkTaskAsDirty(); } } /// <summary> /// Accessor for the task's "ContinueOnError". /// </summary> /// <owner>RGoel</owner> public bool ContinueOnError { get { Expander expander = new Expander(parentTarget.ParentProject.evaluatedProperties, parentTarget.ParentProject.evaluatedItemsByName); // NOTE: if the ContinueOnError attribute contains an item metadata reference, this property is meaningless // because we are unable to batch -- this property will always be 'false' in that case if ((continueOnErrorAttribute != null) && ConversionUtilities.ConvertStringToBool ( expander.ExpandAllIntoString(continueOnErrorAttribute.Value, continueOnErrorAttribute) )) { return true; } else { return false; } } set { // If this Task object is not actually represented by a // task element in the project file, then do not allow // the caller to set the attribute. error.VerifyThrowInvalidOperation(this.taskElement != null, "CannotSetContinueOnError"); // If this task was imported from another project, we don't allow modifying it. error.VerifyThrowInvalidOperation(!this.importedFromAnotherProject, "CannotModifyImportedProjects"); if (value) { this.taskElement.SetAttribute(XMakeAttributes.continueOnError, "true"); } else { // Set the new "ContinueOnError" attribute on the task element. this.taskElement.SetAttribute(XMakeAttributes.continueOnError, "false"); } this.continueOnErrorAttribute = this.taskElement.Attributes[XMakeAttributes.continueOnError]; this.MarkTaskAsDirty(); } } /// <summary> /// System.Type object corresponding to the task class that implements /// the functionality that runs this task object. /// </summary> /// <owner>RGoel</owner> public Type Type { get { // put verify throw for target name ErrorUtilities.VerifyThrow(this.ParentTarget != null, "ParentTarget should not be null"); Engine parentEngine = this.ParentTarget.ParentProject.ParentEngine; Project parentProject = this.ParentTarget.ParentProject; string projectFileOfTaskNode = XmlUtilities.GetXmlNodeFile(taskElement, parentProject.FullFileName); BuildEventContext taskContext = new BuildEventContext ( parentProject.ProjectBuildEventContext.NodeId, this.ParentTarget.Id, parentProject.ProjectBuildEventContext.ProjectContextId, parentProject.ProjectBuildEventContext.TaskId ); int handleId = parentEngine.EngineCallback.CreateTaskContext(parentProject, ParentTarget, null, taskElement, EngineCallback.inProcNode, taskContext); EngineLoggingServices loggingServices = parentEngine.LoggingServices; TaskExecutionModule taskExecutionModule = parentEngine.NodeManager.TaskExecutionModule; TaskEngine taskEngine = new TaskEngine(taskElement, null, projectFileOfTaskNode, parentProject.FullFileName, loggingServices, handleId, taskExecutionModule, taskContext); ErrorUtilities.VerifyThrowInvalidOperation(taskEngine.FindTask(), "MissingTaskError", taskName, parentEngine.ToolsetStateMap[ParentTarget.ParentProject.ToolsVersion].ToolsPath); return taskEngine.TaskClass.Type; } } /// <summary> /// Accessor for the "host object" for this task. /// </summary> /// <owner>RGoel</owner> public ITaskHost HostObject { get { return this.hostObject; } set { this.hostObject = value; } } /// <summary> /// Accessor for parent Target object. /// </summary> /// <value></value> /// <owner>RGoel</owner> internal Target ParentTarget { get { return this.parentTarget; } set { this.parentTarget = value; } } #endregion #region Methods /// <summary> /// This retrieves the list of all parameter names from the element /// node of this task. Note that it excludes anything that a specific /// property is exposed for or that isn't valid here (Name, Condition, /// ContinueOnError). /// /// Note that if there are none, it returns string[0], rather than null, /// as it makes writing foreach statements over the return value so /// much simpler. /// </summary> /// <returns></returns> /// <owner>rgoel</owner> public string[] GetParameterNames() { if (this.taskElement == null) { return new string[0]; } ArrayList list = new ArrayList(); foreach (XmlAttribute attrib in this.taskElement.Attributes) { string attributeValue = attrib.Name; if (!XMakeAttributes.IsSpecialTaskAttribute(attributeValue)) { list.Add(attributeValue); } } return (string[])list.ToArray(typeof(string)); } /// <summary> /// This retrieves an arbitrary attribute from the task element. These /// are attributes that the project author has placed on the task element /// that have no meaning to MSBuild other than that they get passed to the /// task itself as arguments. /// </summary> /// <owner>RGoel</owner> public string GetParameterValue ( string attributeName ) { // You can only request the value of user-defined attributes. The well-known // ones, like "ContinueOnError" for example, are accessed through other means. error.VerifyThrowArgument(!XMakeAttributes.IsSpecialTaskAttribute(attributeName), "CannotAccessKnownAttributes", attributeName); error.VerifyThrowInvalidOperation(this.taskElement != null, "CannotUseParameters"); string attributeValue; // If this is a persisted Task, grab the attribute directly from the // task element. attributeValue = taskElement.GetAttribute(attributeName); return (attributeValue == null) ? String.Empty : attributeValue; } /// <summary> /// This sets an arbitrary attribute on the task element. These /// are attributes that the project author has placed on the task element /// that get passed in to the task. /// /// This optionally escapes the parameter value so it will be treated as a literal. /// </summary> /// <param name="parameterName"></param> /// <param name="parameterValue"></param> /// <param name="treatParameterValueAsLiteral"></param> /// <owner>RGoel</owner> public void SetParameterValue ( string parameterName, string parameterValue, bool treatParameterValueAsLiteral ) { this.SetParameterValue(parameterName, treatParameterValueAsLiteral ? EscapingUtilities.Escape(parameterValue) : parameterValue); } /// <summary> /// This sets an arbitrary attribute on the task element. These /// are attributes that the project author has placed on the task element /// that get passed in to the task. /// </summary> /// <owner>RGoel</owner> public void SetParameterValue ( string parameterName, string parameterValue ) { // You can only set the value of user-defined attributes. The well-known // ones, like "ContinueOnError" for example, are accessed through other means. error.VerifyThrowArgument(!XMakeAttributes.IsSpecialTaskAttribute(parameterName), "CannotAccessKnownAttributes", parameterName); // If this task was imported from another project, we don't allow modifying it. error.VerifyThrowInvalidOperation(!this.importedFromAnotherProject, "CannotModifyImportedProjects"); error.VerifyThrowInvalidOperation(this.taskElement != null, "CannotUseParameters"); // If this is a persisted Task, set the attribute directly on the // task element. taskElement.SetAttribute(parameterName, parameterValue); this.MarkTaskAsDirty(); } /// <summary> /// Adds an Output tag to this task element /// </summary> /// <param name="taskParameter"></param> /// <param name="itemName"></param> /// <owner>LukaszG</owner> public void AddOutputItem(string taskParameter, string itemName) { AddOutputItem(taskParameter, itemName, null); } /// <summary> /// Adds an Output tag to this task element, with a condition /// </summary> /// <param name="taskParameter"></param> /// <param name="itemName"></param> /// <param name="condition">May be null</param> internal void AddOutputItem(string taskParameter, string itemName, string condition) { // If this task was imported from another project, we don't allow modifying it. error.VerifyThrowInvalidOperation(!this.importedFromAnotherProject, "CannotModifyImportedProjects"); error.VerifyThrowInvalidOperation(this.taskElement != null, "CannotUseParameters"); XmlElement newOutputElement = this.taskElement.OwnerDocument.CreateElement(XMakeElements.output, XMakeAttributes.defaultXmlNamespace); newOutputElement.SetAttribute(XMakeAttributes.taskParameter, taskParameter); newOutputElement.SetAttribute(XMakeAttributes.itemName, itemName); if (condition != null) { newOutputElement.SetAttribute(XMakeAttributes.condition, condition); } this.taskElement.AppendChild(newOutputElement); this.MarkTaskAsDirty(); } /// <summary> /// Adds an Output tag to this task element /// </summary> /// <param name="taskParameter"></param> /// <param name="propertyName"></param> /// <owner>LukaszG</owner> public void AddOutputProperty(string taskParameter, string propertyName) { // If this task was imported from another project, we don't allow modifying it. error.VerifyThrowInvalidOperation(!this.importedFromAnotherProject, "CannotModifyImportedProjects"); error.VerifyThrowInvalidOperation(this.taskElement != null, "CannotUseParameters"); XmlElement newOutputElement = this.taskElement.OwnerDocument.CreateElement(XMakeElements.output, XMakeAttributes.defaultXmlNamespace); newOutputElement.SetAttribute(XMakeAttributes.taskParameter, taskParameter); newOutputElement.SetAttribute(XMakeAttributes.propertyName, propertyName); this.taskElement.AppendChild(newOutputElement); this.MarkTaskAsDirty(); } /// <summary> /// Runs the task associated with this object. /// </summary> /// <owner>RGoel</owner> public bool Execute ( ) { error.VerifyThrowInvalidOperation(this.taskElement != null, "CannotExecuteUnassociatedTask"); error.VerifyThrowInvalidOperation(this.parentTarget != null, "CannotExecuteUnassociatedTask"); return this.parentTarget.ExecuteOneTask(this.taskElement, this.HostObject); } /// <summary> /// Indicates that something has changed within the task element, so the project /// needs to be saved and re-evaluated at next build. Send the "dirtiness" /// notification up the chain. /// </summary> /// <owner>RGoel</owner> private void MarkTaskAsDirty ( ) { if (this.ParentTarget != null) { // This is a change to the contents of the target. this.ParentTarget.MarkTargetAsDirty(); } } #endregion } }
// This source code is dual-licensed under the Apache License, version // 2.0, and the Mozilla Public License, version 1.1. // // The APL v2.0: // //--------------------------------------------------------------------------- // Copyright (C) 2007-2014 GoPivotal, 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. //--------------------------------------------------------------------------- // // The MPL v1.1: // //--------------------------------------------------------------------------- // 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. // // The Original Code is RabbitMQ. // // The Initial Developer of the Original Code is GoPivotal, Inc. // Copyright (c) 2007-2014 GoPivotal, Inc. All rights reserved. //--------------------------------------------------------------------------- using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Xml; using RabbitMQ.Client.Apigen.Attributes; namespace RabbitMQ.Client.Apigen { public class Apigen { /////////////////////////////////////////////////////////////////////////// // Entry point public static void Main(string[] args) { Apigen instance = new Apigen(new List<string>(args)); instance.Generate(); } /////////////////////////////////////////////////////////////////////////// // XML utilities public static XmlNodeList GetNodes(XmlNode n0, string path) { return n0.SelectNodes(path); } public static string GetString(XmlNode n0, string path, string d) { XmlNode n = n0.SelectSingleNode(path); string pathOrDefault = (n == null) ? d : n.InnerText; return xmlStringMapper(pathOrDefault); } public static string GetString(XmlNode n0, string path) { string s = GetString(n0, path, null); if (s == null) { throw new Exception("Missing spec XML node: " + path); } return s; } public static int GetInt(XmlNode n0, string path, int d) { string s = GetString(n0, path, null); return (s == null) ? d : int.Parse(s); } public static int GetInt(XmlNode n0, string path) { return int.Parse(GetString(n0, path)); } /// <summary> /// Rename all instances of an entire string from the XML spec /// </summary> /// <param name="xmlString">input string from XML spec</param> /// <returns>renamed string</returns> private static string xmlStringMapper(string xmlString) { switch (xmlString) { case "no-wait": return "nowait"; default: return xmlString; } } /////////////////////////////////////////////////////////////////////////// // Name manipulation and mangling for C# public static string MangleConstant(string name) { // Previously, we used C_STYLE_CONSTANT_NAMES: /* return name .Replace(" ", "_") .Replace("-", "_"). ToUpper(); */ // ... but TheseKindsOfNames are more in line with .NET style guidelines. return MangleClass(name); } public static IList<string> IdentifierParts(string name) { IList<string> result = new List<string>(); foreach (String s1 in name.Split(new Char[] { '-' })) { foreach (String s2 in s1.Split(new Char[] { ' ' })) { result.Add(s2); } } return result; } public static string MangleClass(string name) { StringBuilder sb = new StringBuilder(); foreach (String s in IdentifierParts(name)) { sb.Append(Char.ToUpper(s[0]) + s.Substring(1).ToLower()); } return sb.ToString(); } public static string MangleMethod(string name) { StringBuilder sb = new StringBuilder(); bool useUpper = false; foreach (String s in IdentifierParts(name)) { if (useUpper) { sb.Append(Char.ToUpper(s[0]) + s.Substring(1).ToLower()); } else { sb.Append(s.ToLower()); useUpper = true; } } return sb.ToString(); } public static string MangleMethodClass(AmqpClass c, AmqpMethod m) { return MangleClass(c.Name) + MangleClass(m.Name); } /////////////////////////////////////////////////////////////////////////// public string m_inputXmlFilename; public string m_outputFilename; public XmlDocument m_spec = null; public TextWriter m_outputFile = null; public int m_majorVersion; public int m_minorVersion; public int m_revision = 0; public string m_apiName; public bool m_emitComments = false; public Type m_modelType = typeof(RabbitMQ.Client.Impl.IFullModel); public IList<Type> m_modelTypes = new List<Type>(); public IList<KeyValuePair<string, int>> m_constants = new List<KeyValuePair<string, int>>(); public IList<AmqpClass> m_classes = new List<AmqpClass>(); public IDictionary<string, string> m_domains = new Dictionary<string, string>(); public static IDictionary<string, string> m_primitiveTypeMap; public static IDictionary<string, bool> m_primitiveTypeFlagMap; private CodeDomProvider m_csharpProvider; static Apigen() { m_primitiveTypeMap = new Dictionary<string, string>(); m_primitiveTypeFlagMap = new Dictionary<string, bool>(); InitPrimitiveType("octet", "byte", false); InitPrimitiveType("shortstr", "string", true); InitPrimitiveType("longstr", "byte[]", true); InitPrimitiveType("short", "ushort", false); InitPrimitiveType("long", "uint", false); InitPrimitiveType("longlong", "ulong", false); InitPrimitiveType("bit", "bool", false); InitPrimitiveType("table", "System.Collections.Generic.IDictionary<string, object>", true); InitPrimitiveType("timestamp", "AmqpTimestamp", false); InitPrimitiveType("content", "byte[]", true); } public static void InitPrimitiveType(string amqpType, string dotnetType, bool isReference) { m_primitiveTypeMap[amqpType] = dotnetType; m_primitiveTypeFlagMap[amqpType] = isReference; } public void HandleOption(string opt) { if (opt.StartsWith("/apiName:")) { m_apiName = opt.Substring(9); } else if (opt == "/c") { m_emitComments = true; } else { Console.Error.WriteLine("Unsupported command-line option: " + opt); Usage(); } } public void Usage() { Console.Error.WriteLine("Usage: Apigen.exe [options ...] <input-spec-xml> <output-csharp-file>"); Console.Error.WriteLine(" Options include:"); Console.Error.WriteLine(" /apiName:<identifier>"); Console.Error.WriteLine(" The apiName option is required."); Environment.Exit(1); } public Apigen(IList<string> args) { while (args.Count > 0 && ((string) args[0]).StartsWith("/")) { HandleOption((string) args[0]); args.RemoveAt(0); } if ((args.Count < 2) || (m_apiName == null)) { Usage(); } m_inputXmlFilename = (string) args[0]; m_outputFilename = (string) args[1]; this.m_csharpProvider = CodeDomProvider.CreateProvider("C#"); } /////////////////////////////////////////////////////////////////////////// public string ApiNamespaceBase { get { return "RabbitMQ.Client.Framing"; } } public string ImplNamespaceBase { get { return "RabbitMQ.Client.Framing.Impl"; } } public void Generate() { LoadSpec(); ParseSpec(); ReflectModel(); GenerateOutput(); } public void LoadSpec() { Console.WriteLine("* Loading spec from '" + m_inputXmlFilename + "'"); m_spec = new XmlDocument(); m_spec.Load(m_inputXmlFilename); } public void ParseSpec() { m_majorVersion = GetInt(m_spec, "/amqp/@major"); m_minorVersion = GetInt(m_spec, "/amqp/@minor"); m_revision = GetInt(m_spec, "/amqp/@revision"); Console.WriteLine("* Parsing spec for version {0}.{1}.{2}", m_majorVersion, m_minorVersion, m_revision); foreach (XmlNode n in m_spec.SelectNodes("/amqp/constant")) { m_constants.Add(new KeyValuePair<string, int>(GetString(n, "@name"), GetInt(n, "@value"))); } foreach (XmlNode n in m_spec.SelectNodes("/amqp/class")) { m_classes.Add(new AmqpClass(n)); } foreach (XmlNode n in m_spec.SelectNodes("/amqp/domain")) { m_domains[GetString(n, "@name")] = GetString(n, "@type"); } } public void ReflectModel() { m_modelTypes.Add(m_modelType); for (int i = 0; i < m_modelTypes.Count; i++) { foreach (Type intf in ((Type) m_modelTypes[i]).GetInterfaces()) { m_modelTypes.Add(intf); } } } public string ResolveDomain(string d) { while (m_domains.ContainsKey(d)) { string newD = (string) m_domains[d]; if (d.Equals(newD)) break; d = newD; } return d; } public string MapDomain(string d) { return (string) m_primitiveTypeMap[ResolveDomain(d)]; } public string VersionToken() { return "v" + m_majorVersion + "_" + m_minorVersion; } public void GenerateOutput() { Console.WriteLine("* Generating code into '" + m_outputFilename + "'"); m_outputFile = new StreamWriter(m_outputFilename); EmitPrelude(); EmitPublic(); EmitPrivate(); m_outputFile.Close(); } public void Emit(object o) { m_outputFile.Write(o); } public void EmitLine(object o) { m_outputFile.WriteLine(o); } public void EmitSpecComment(object o) { if (m_emitComments) EmitLine(o); } public void EmitPrelude() { EmitLine("// Autogenerated code. Do not edit."); EmitLine(""); EmitLine("// This source code is dual-licensed under the Apache License, version"); EmitLine("// 2.0, and the Mozilla Public License, version 1.1."); EmitLine("//"); EmitLine("// The APL v2.0:"); EmitLine("//"); EmitLine("//---------------------------------------------------------------------------"); EmitLine("// Copyright (C) 2007-2014 GoPivotal, Inc."); EmitLine("//"); EmitLine("// Licensed under the Apache License, Version 2.0 (the \"License\");"); EmitLine("// you may not use this file except in compliance with the License."); EmitLine("// You may obtain a copy of the License at"); EmitLine("//"); EmitLine("// http://www.apache.org/licenses/LICENSE-2.0"); EmitLine("//"); EmitLine("// Unless required by applicable law or agreed to in writing, software"); EmitLine("// distributed under the License is distributed on an \"AS IS\" BASIS,"); EmitLine("// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied."); EmitLine("// See the License for the specific language governing permissions and"); EmitLine("// limitations under the License."); EmitLine("//---------------------------------------------------------------------------"); EmitLine("//"); EmitLine("// The MPL v1.1:"); EmitLine("//"); EmitLine("//---------------------------------------------------------------------------"); EmitLine("// The contents of this file are subject to the Mozilla Public License"); EmitLine("// Version 1.1 (the \"License\"); you may not use this file except in"); EmitLine("// compliance with the License. You may obtain a copy of the License at"); EmitLine("// http://www.rabbitmq.com/mpl.html"); EmitLine("//"); EmitLine("// Software distributed under the License is distributed on an \"AS IS\""); EmitLine("// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the"); EmitLine("// License for the specific language governing rights and limitations"); EmitLine("// under the License."); EmitLine("//"); EmitLine("// The Original Code is RabbitMQ."); EmitLine("//"); EmitLine("// The Initial Developer of the Original Code is GoPivotal, Inc."); EmitLine("// Copyright (c) 2007-2014 GoPivotal, Inc. All rights reserved."); EmitLine("//---------------------------------------------------------------------------"); EmitLine(""); EmitLine("using RabbitMQ.Client;"); EmitLine("using RabbitMQ.Client.Exceptions;"); EmitLine(""); } public void EmitPublic() { EmitLine("namespace "+ApiNamespaceBase+" {"); EmitLine(" public class Protocol: "+ImplNamespaceBase+".ProtocolBase {"); EmitLine(" ///<summary>Protocol major version (= "+m_majorVersion+")</summary>"); EmitLine(" public override int MajorVersion { get { return " + m_majorVersion + "; } }"); EmitLine(" ///<summary>Protocol minor version (= "+m_minorVersion+")</summary>"); EmitLine(" public override int MinorVersion { get { return " + m_minorVersion + "; } }"); EmitLine(" ///<summary>Protocol revision (= " + m_revision + ")</summary>"); EmitLine(" public override int Revision { get { return " + m_revision + "; } }"); EmitLine(" ///<summary>Protocol API name (= "+m_apiName+")</summary>"); EmitLine(" public override string ApiName { get { return \"" + m_apiName + "\"; } }"); int port = GetInt(m_spec, "/amqp/@port"); EmitLine(" ///<summary>Default TCP port (= "+port+")</summary>"); EmitLine(" public override int DefaultPort { get { return " + port + "; } }"); EmitLine(""); EmitMethodArgumentReader(); EmitLine(""); EmitContentHeaderReader(); EmitLine(" }"); EmitLine(" public class Constants {"); foreach (KeyValuePair<string, int> de in m_constants) { EmitLine(" ///<summary>(= "+de.Value+")</summary>"); EmitLine(" public const int "+MangleConstant((string) de.Key)+" = "+de.Value+";"); } EmitLine(" }"); foreach (AmqpClass c in m_classes) { EmitClassMethods(c); } foreach (AmqpClass c in m_classes) { if (c.NeedsProperties) { EmitClassProperties(c); } } EmitLine("}"); } public void EmitAutogeneratedSummary(string prefixSpaces, string extra) { EmitLine(prefixSpaces+"/// <summary>Autogenerated type. "+extra+"</summary>"); } public void EmitClassMethods(AmqpClass c) { foreach (AmqpMethod m in c.m_Methods) { EmitAutogeneratedSummary(" ", "AMQP specification method \""+c.Name+"."+m.Name+"\"."); EmitSpecComment(m.DocumentationCommentVariant(" ", "remarks")); EmitLine(" public interface I"+MangleMethodClass(c, m)+": IMethod {"); foreach (AmqpField f in m.m_Fields) { EmitSpecComment(f.DocumentationComment(" ")); EmitLine(" "+MapDomain(f.Domain)+" "+MangleClass(f.Name)+" { get; }"); } EmitLine(" }"); } } public bool HasFactoryMethod(AmqpClass c) { foreach (Type t in m_modelTypes) { foreach (MethodInfo method in t.GetMethods()) { AmqpContentHeaderFactoryAttribute f = (AmqpContentHeaderFactoryAttribute) Attribute(method, typeof(AmqpContentHeaderFactoryAttribute)); if (f != null && MangleClass(f.m_contentClass) == MangleClass(c.Name)) { return true; } } } return false; } public bool IsBoolean(AmqpField f) { return ResolveDomain(f.Domain) == "bit"; } public bool IsReferenceType(AmqpField f) { return (bool) m_primitiveTypeFlagMap[ResolveDomain(f.Domain)]; } public bool IsAmqpClass(Type t) { foreach (AmqpClass c in m_classes) { if (c.Name == t.Name) return true; } return false; } public void EmitClassProperties(AmqpClass c) { bool hasCommonApi = HasFactoryMethod(c); string propertiesBaseClass = hasCommonApi ? "RabbitMQ.Client.Impl."+MangleClass(c.Name)+"Properties" : "RabbitMQ.Client.Impl.ContentHeaderBase"; string maybeOverride = hasCommonApi ? "override " : ""; EmitAutogeneratedSummary(" ", "AMQP specification content header properties for "+ "content class \""+c.Name+"\""); EmitSpecComment(c.DocumentationCommentVariant(" ", "remarks")); EmitLine(" public class "+MangleClass(c.Name) +"Properties: "+propertiesBaseClass+" {"); foreach (AmqpField f in c.m_Fields) { EmitLine(" private "+MapDomain(f.Domain)+" m_"+MangleMethod(f.Name)+";"); } EmitLine(""); foreach (AmqpField f in c.m_Fields) { if (!IsBoolean(f)) { EmitLine(" private bool m_"+MangleMethod(f.Name)+"_present = false;"); } } EmitLine(""); foreach (AmqpField f in c.m_Fields) { EmitSpecComment(f.DocumentationComment(" ", "@label")); EmitLine(" public "+maybeOverride+MapDomain(f.Domain)+" "+MangleClass(f.Name)+" {"); EmitLine(" get {"); EmitLine(" return m_"+MangleMethod(f.Name)+";"); EmitLine(" }"); EmitLine(" set {"); if (!IsBoolean(f)) { EmitLine(" m_"+MangleMethod(f.Name)+"_present = true;"); } EmitLine(" m_"+MangleMethod(f.Name)+" = value;"); EmitLine(" }"); EmitLine(" }"); } EmitLine(""); foreach (AmqpField f in c.m_Fields) { if (!IsBoolean(f)) { EmitLine(" public "+maybeOverride+"void Clear"+MangleClass(f.Name)+"() { m_"+MangleMethod(f.Name)+"_present = false; }"); } } EmitLine(""); foreach (AmqpField f in c.m_Fields) { if (!IsBoolean(f)) EmitLine(" public " + maybeOverride + "bool Is" + MangleClass(f.Name) + "Present() { return m_" + MangleMethod(f.Name) + "_present; }"); } EmitLine(""); EmitLine(" public "+MangleClass(c.Name)+"Properties() {}"); EmitLine(" public override int ProtocolClassId { get { return "+c.Index+"; } }"); EmitLine(" public override string ProtocolClassName { get { return \""+c.Name+"\"; } }"); EmitLine(""); EmitLine(" public override void ReadPropertiesFrom(RabbitMQ.Client.Impl.ContentHeaderPropertyReader reader) {"); foreach (AmqpField f in c.m_Fields) { if (IsBoolean(f)) { EmitLine(" m_"+MangleMethod(f.Name)+" = reader.ReadBit();"); } else { EmitLine(" m_"+MangleMethod(f.Name)+"_present = reader.ReadPresence();"); } } EmitLine(" reader.FinishPresence();"); foreach (AmqpField f in c.m_Fields) { if (!IsBoolean(f)) { EmitLine(" if (m_"+MangleMethod(f.Name)+"_present) { m_"+MangleMethod(f.Name)+" = reader.Read"+MangleClass(ResolveDomain(f.Domain))+"(); }"); } } EmitLine(" }"); EmitLine(""); EmitLine(" public override void WritePropertiesTo(RabbitMQ.Client.Impl.ContentHeaderPropertyWriter writer) {"); foreach (AmqpField f in c.m_Fields) { if (IsBoolean(f)) { EmitLine(" writer.WriteBit(m_"+MangleMethod(f.Name)+");"); } else { EmitLine(" writer.WritePresence(m_"+MangleMethod(f.Name)+"_present);"); } } EmitLine(" writer.FinishPresence();"); foreach (AmqpField f in c.m_Fields) { if (!IsBoolean(f)) { EmitLine(" if (m_"+MangleMethod(f.Name)+"_present) { writer.Write"+MangleClass(ResolveDomain(f.Domain))+"(m_"+MangleMethod(f.Name)+"); }"); } } EmitLine(" }"); EmitLine(""); EmitLine(" public override void AppendPropertyDebugStringTo(System.Text.StringBuilder sb) {"); EmitLine(" sb.Append(\"(\");"); { int remaining = c.m_Fields.Count; foreach (AmqpField f in c.m_Fields) { Emit(" sb.Append(\""+f.Name+"=\");"); if (IsBoolean(f)) { Emit(" sb.Append(m_"+MangleMethod(f.Name)+");"); } else { string x = MangleMethod(f.Name); if (IsReferenceType(f)) { Emit(" sb.Append(m_"+x+"_present ? (m_"+x+" == null ? \"(null)\" : m_"+x+".ToString()) : \"_\");"); } else { Emit(" sb.Append(m_"+x+"_present ? m_"+x+".ToString() : \"_\");"); } } remaining--; if (remaining > 0) { EmitLine(" sb.Append(\", \");"); } else { EmitLine(""); } } } EmitLine(" sb.Append(\")\");"); EmitLine(" }"); EmitLine(" }"); } public void EmitPrivate() { EmitLine("namespace "+ImplNamespaceBase+" {"); EmitLine(" using "+ApiNamespaceBase+";"); EmitLine(" public enum ClassId {"); foreach (AmqpClass c in m_classes) { EmitLine(" "+MangleConstant(c.Name)+" = "+c.Index+","); } EmitLine(" Invalid = -1"); EmitLine(" }"); foreach (AmqpClass c in m_classes) { EmitClassMethodImplementations(c); } EmitLine(""); EmitModelImplementation(); EmitLine("}"); } public void EmitClassMethodImplementations(AmqpClass c) { foreach (AmqpMethod m in c.m_Methods) { EmitAutogeneratedSummary(" ", "Private implementation class - do not use directly."); EmitLine(" public class "+MangleMethodClass(c,m) +": RabbitMQ.Client.Impl.MethodBase, I"+MangleMethodClass(c,m)+" {"); EmitLine(" public const int ClassId = "+c.Index+";"); EmitLine(" public const int MethodId = "+m.Index+";"); EmitLine(""); foreach (AmqpField f in m.m_Fields) { EmitLine(" public "+MapDomain(f.Domain)+" m_"+MangleMethod(f.Name)+";"); } EmitLine(""); foreach (AmqpField f in m.m_Fields) { EmitLine(" "+MapDomain(f.Domain)+" I"+MangleMethodClass(c,m)+ "."+MangleClass(f.Name)+" { get {" + " return m_" + MangleMethod(f.Name) + "; } }"); } EmitLine(""); if (m.m_Fields.Count > 0) { EmitLine(" public "+MangleMethodClass(c,m)+"() {}"); } EmitLine(" public "+MangleMethodClass(c,m)+"("); { int remaining = m.m_Fields.Count; foreach (AmqpField f in m.m_Fields) { Emit(" "+MapDomain(f.Domain)+" init"+MangleClass(f.Name)); remaining--; if (remaining > 0) { EmitLine(","); } } } EmitLine(")"); EmitLine(" {"); foreach (AmqpField f in m.m_Fields) { EmitLine(" m_" + MangleMethod(f.Name) + " = init" + MangleClass(f.Name) + ";"); } EmitLine(" }"); EmitLine(""); EmitLine(" public override int ProtocolClassId { get { return "+c.Index+"; } }"); EmitLine(" public override int ProtocolMethodId { get { return "+m.Index+"; } }"); EmitLine(" public override string ProtocolMethodName { get { return \""+c.Name+"."+m.Name+"\"; } }"); EmitLine(" public override bool HasContent { get { return " +(m.HasContent ? "true" : "false")+"; } }"); EmitLine(""); EmitLine(" public override void ReadArgumentsFrom(RabbitMQ.Client.Impl.MethodArgumentReader reader) {"); foreach (AmqpField f in m.m_Fields) { EmitLine(" m_" + MangleMethod(f.Name) + " = reader.Read" + MangleClass(ResolveDomain(f.Domain)) + "();"); } EmitLine(" }"); EmitLine(""); EmitLine(" public override void WriteArgumentsTo(RabbitMQ.Client.Impl.MethodArgumentWriter writer) {"); foreach (AmqpField f in m.m_Fields) { EmitLine(" writer.Write"+MangleClass(ResolveDomain(f.Domain)) + "(m_" + MangleMethod(f.Name) + ");"); } EmitLine(" }"); EmitLine(""); EmitLine(" public override void AppendArgumentDebugStringTo(System.Text.StringBuilder sb) {"); EmitLine(" sb.Append(\"(\");"); { int remaining = m.m_Fields.Count; foreach (AmqpField f in m.m_Fields) { Emit(" sb.Append(m_" + MangleMethod(f.Name) + ");"); remaining--; if (remaining > 0) { EmitLine(" sb.Append(\",\");"); } else { EmitLine(""); } } } EmitLine(" sb.Append(\")\");"); EmitLine(" }"); EmitLine(" }"); } } public void EmitMethodArgumentReader() { EmitLine(" public override RabbitMQ.Client.Impl.MethodBase DecodeMethodFrom(RabbitMQ.Util.NetworkBinaryReader reader) {"); EmitLine(" ushort classId = reader.ReadUInt16();"); EmitLine(" ushort methodId = reader.ReadUInt16();"); EmitLine(""); EmitLine(" switch (classId) {"); foreach (AmqpClass c in m_classes) { EmitLine(" case "+c.Index+": {"); EmitLine(" switch (methodId) {"); foreach (AmqpMethod m in c.m_Methods) { EmitLine(" case "+m.Index+": {"); EmitLine(" "+ImplNamespaceBase+"."+MangleMethodClass(c,m)+" result = new "+ImplNamespaceBase+"."+MangleMethodClass(c,m)+"();"); EmitLine(" result.ReadArgumentsFrom(new RabbitMQ.Client.Impl.MethodArgumentReader(reader));"); EmitLine(" return result;"); EmitLine(" }"); } EmitLine(" default: break;"); EmitLine(" }"); EmitLine(" break;"); EmitLine(" }"); } EmitLine(" default: break;"); EmitLine(" }"); EmitLine(" throw new RabbitMQ.Client.Impl.UnknownClassOrMethodException(classId, methodId);"); EmitLine(" }"); } public void EmitContentHeaderReader() { EmitLine(" public override RabbitMQ.Client.Impl.ContentHeaderBase DecodeContentHeaderFrom(RabbitMQ.Util.NetworkBinaryReader reader) {"); EmitLine(" ushort classId = reader.ReadUInt16();"); EmitLine(""); EmitLine(" switch (classId) {"); foreach (AmqpClass c in m_classes) { if (c.NeedsProperties) { EmitLine(" case "+c.Index+": return new " +MangleClass(c.Name)+"Properties();"); } } EmitLine(" default: break;"); EmitLine(" }"); EmitLine(" throw new RabbitMQ.Client.Impl.UnknownClassOrMethodException(classId, 0);"); EmitLine(" }"); } public Attribute Attribute(MemberInfo mi, Type t) { return Attribute(mi.GetCustomAttributes(t, false), t); } public Attribute Attribute(ParameterInfo pi, Type t) { return Attribute(pi.GetCustomAttributes(t, false), t); } public Attribute Attribute(ICustomAttributeProvider p, Type t) { return Attribute(p.GetCustomAttributes(t, false), t); } public Attribute Attribute(IEnumerable<object> attributes, Type t) { if (t.IsSubclassOf(typeof(AmqpApigenAttribute))) { AmqpApigenAttribute result = null; foreach (AmqpApigenAttribute candidate in attributes) { if (candidate.m_namespaceName == null && result == null) { result = candidate; } if (candidate.m_namespaceName == ApiNamespaceBase) { result = candidate; } } return result; } else { foreach (Attribute attribute in attributes) { return attribute; } return null; } } public void EmitModelImplementation() { EmitLine(" public class Model: RabbitMQ.Client.Impl.ModelBase {"); EmitLine(" public Model(RabbitMQ.Client.Impl.ISession session): base(session) {}"); IList<MethodInfo> asynchronousHandlers = new List<MethodInfo>(); foreach (Type t in m_modelTypes) { foreach (MethodInfo method in t.GetMethods()) { if (method.DeclaringType.Namespace != null && method.DeclaringType.Namespace.StartsWith("RabbitMQ.Client")) { if (method.Name.StartsWith("Handle") || (Attribute(method, typeof(AmqpAsynchronousHandlerAttribute)) != null)) { if ((Attribute(method, typeof(AmqpMethodDoNotImplementAttribute)) == null) && Attribute(method, typeof(AmqpUnsupportedAttribute)) == null) { asynchronousHandlers.Add(method); } } else { MaybeEmitModelMethod(method); } } } } EmitAsynchronousHandlers(asynchronousHandlers); EmitLine(" }"); } public void EmitContentHeaderFactory(MethodInfo method) { AmqpContentHeaderFactoryAttribute factoryAnnotation = (AmqpContentHeaderFactoryAttribute) Attribute(method, typeof(AmqpContentHeaderFactoryAttribute)); string contentClass = factoryAnnotation.m_contentClass; EmitModelMethodPreamble(method); EmitLine(" {"); if (Attribute(method, typeof(AmqpUnsupportedAttribute)) != null) { EmitLine(String.Format(" throw new UnsupportedMethodException(\"" + method.Name + "\");")); } else { EmitLine(" return new " + MangleClass(contentClass) + "Properties();"); } EmitLine(" }"); } public void MaybeEmitModelMethod(MethodInfo method) { if (method.IsSpecialName) { // It's some kind of event- or property-related method. // It shouldn't be autogenerated. } else if (method.Name.EndsWith("NoWait")) { // Skip *Nowait versions } else if (Attribute(method, typeof(AmqpMethodDoNotImplementAttribute)) != null) { // Skip this method, by request (AmqpMethodDoNotImplement) } else if (Attribute(method, typeof(AmqpContentHeaderFactoryAttribute)) != null) { EmitContentHeaderFactory(method); } else if (Attribute(method, typeof(AmqpUnsupportedAttribute)) != null) { EmitModelMethodPreamble(method); EmitLine(" {"); EmitLine(" throw new UnsupportedMethodException(\""+method.Name+"\");"); EmitLine(" }"); } else { EmitModelMethod(method); } } public string SanitisedFullName(Type t) { CodeTypeReferenceExpression tre = new CodeTypeReferenceExpression(t.FullName); StringBuilder sb = new StringBuilder(); using (StringWriter writer = new StringWriter(sb)) { this.m_csharpProvider.GenerateCodeFromExpression(tre, writer, new CodeGeneratorOptions()); } return sb.ToString().Trim(' ', '\t', '\r', '\n'); } public void EmitModelMethodPreamble(MethodInfo method) { Emit(" public override "+SanitisedFullName(method.ReturnType)+" "+method.Name); ParameterInfo[] parameters = method.GetParameters(); int remaining = parameters.Length; if (remaining == 0) { EmitLine("()"); } else { EmitLine("("); foreach (ParameterInfo pi in parameters) { Emit(" "+SanitisedFullName(pi.ParameterType)+" @"+pi.Name); remaining--; if (remaining > 0) { EmitLine(","); } else { EmitLine(")"); } } } } public void LookupAmqpMethod(MethodInfo method, string methodName, out AmqpClass amqpClass, out AmqpMethod amqpMethod) { amqpClass = null; amqpMethod = null; // First, try autodetecting the class/method via the // IModel method name. foreach (AmqpClass c in m_classes) { foreach (AmqpMethod m in c.m_Methods) { if (methodName.Equals(MangleMethodClass(c,m))) { amqpClass = c; amqpMethod = m; goto stopSearching; // wheee } } } stopSearching: // If an explicit mapping was provided as an attribute, // then use that instead, whether the autodetect worked or // not. { AmqpMethodMappingAttribute methodMapping = Attribute(method, typeof(AmqpMethodMappingAttribute)) as AmqpMethodMappingAttribute; if (methodMapping != null) { amqpClass = null; foreach (AmqpClass c in m_classes) { if (c.Name == methodMapping.m_className) { amqpClass = c; break; } } amqpMethod = amqpClass.MethodNamed(methodMapping.m_methodName); } } // At this point, if can't find either the class or the // method, we can't proceed. Complain. if (amqpClass == null || amqpMethod == null) { throw new Exception("Could not find AMQP class or method for IModel method " + method.Name); } } public void EmitModelMethod(MethodInfo method) { ParameterInfo[] parameters = method.GetParameters(); AmqpClass amqpClass = null; AmqpMethod amqpMethod = null; LookupAmqpMethod(method, method.Name, out amqpClass, out amqpMethod); string requestImplClass = MangleMethodClass(amqpClass, amqpMethod); // At this point, we know which request method to // send. Now compute whether it's an RPC or not. AmqpMethod amqpReplyMethod = null; AmqpMethodMappingAttribute replyMapping = Attribute(method.ReturnTypeCustomAttributes, typeof(AmqpMethodMappingAttribute)) as AmqpMethodMappingAttribute; if (Attribute(method, typeof(AmqpForceOneWayAttribute)) == null && (amqpMethod.IsSimpleRpcRequest || replyMapping != null)) { // We're not forcing oneway, and either are a simple // RPC request, or have an explicit replyMapping amqpReplyMethod = amqpClass.MethodNamed(replyMapping == null ? (string) amqpMethod.m_ResponseMethods[0] : replyMapping.m_methodName); if (amqpReplyMethod == null) { throw new Exception("Could not find AMQP reply method for IModel method " + method.Name); } } // If amqpReplyMethod is null at this point, it's a // one-way operation, and no continuation needs to be // consed up. Otherwise, we should expect a reply of kind // identified by amqpReplyMethod - unless there's a nowait // parameter thrown into the equation! // // Examine the parameters to discover which might be // nowait, content header or content body. ParameterInfo nowaitParameter = null; string nowaitExpression = "null"; ParameterInfo contentHeaderParameter = null; ParameterInfo contentBodyParameter = null; foreach (ParameterInfo pi in parameters) { AmqpNowaitArgumentAttribute nwAttr = Attribute(pi, typeof(AmqpNowaitArgumentAttribute)) as AmqpNowaitArgumentAttribute; if (nwAttr != null) { nowaitParameter = pi; if (nwAttr.m_replacementExpression != null) { nowaitExpression = nwAttr.m_replacementExpression; } } if (Attribute(pi, typeof(AmqpContentHeaderMappingAttribute)) != null) { contentHeaderParameter = pi; } if (Attribute(pi, typeof(AmqpContentBodyMappingAttribute)) != null) { contentBodyParameter = pi; } } // Compute expression text for the content header and body. string contentHeaderExpr = contentHeaderParameter == null ? "null" : " ("+MangleClass(amqpClass.Name)+"Properties) "+contentHeaderParameter.Name; string contentBodyExpr = contentBodyParameter == null ? "null" : contentBodyParameter.Name; // Emit the method declaration and preamble. EmitModelMethodPreamble(method); EmitLine(" {"); // Emit the code to build the request. EmitLine(" "+requestImplClass+" __req = new "+requestImplClass+"();"); foreach (ParameterInfo pi in parameters) { if (pi != contentHeaderParameter && pi != contentBodyParameter) { if (Attribute(pi, typeof(AmqpUnsupportedAttribute)) != null) { EmitLine(" if (@"+pi.Name+" != null) {"); EmitLine(" throw new UnsupportedMethodFieldException(\""+method.Name+"\",\""+pi.Name+"\");"); EmitLine(" }"); } else { AmqpFieldMappingAttribute fieldMapping = Attribute(pi, typeof(AmqpFieldMappingAttribute)) as AmqpFieldMappingAttribute; if (fieldMapping != null) { EmitLine(" __req.m_"+fieldMapping.m_fieldName+" = @" + pi.Name + ";"); } else { EmitLine(" __req.m_"+pi.Name+" = @" + pi.Name + ";"); } } } } // If we have a nowait parameter, sometimes that can turn // a ModelRpc call into a ModelSend call. if (nowaitParameter != null) { EmitLine(" if ("+nowaitParameter.Name+") {"); EmitLine(" ModelSend(__req,"+contentHeaderExpr+","+contentBodyExpr+");"); if (method.ReturnType == typeof(void)) { EmitLine(" return;"); } else { EmitLine(" return "+nowaitExpression+";"); } EmitLine(" }"); } // At this point, perform either a ModelRpc or a // ModelSend. if (amqpReplyMethod == null) { EmitLine(" ModelSend(__req,"+contentHeaderExpr+","+contentBodyExpr+");"); } else { string replyImplClass = MangleMethodClass(amqpClass, amqpReplyMethod); EmitLine(" RabbitMQ.Client.Impl.MethodBase __repBase = ModelRpc(__req,"+contentHeaderExpr+","+contentBodyExpr+");"); EmitLine(" "+replyImplClass+" __rep = __repBase as "+replyImplClass+";"); EmitLine(" if (__rep == null) throw new UnexpectedMethodException(__repBase);"); if (method.ReturnType == typeof(void)) { // No need to further examine the reply. } else { // At this point, we have the reply method. Extract values from it. AmqpFieldMappingAttribute returnMapping = Attribute(method.ReturnTypeCustomAttributes, typeof(AmqpFieldMappingAttribute)) as AmqpFieldMappingAttribute; if (returnMapping == null) { string fieldPrefix = IsAmqpClass(method.ReturnType) ? "m_" : ""; // No field mapping --> it's assumed to be a struct to fill in. EmitLine(" "+method.ReturnType+" __result = new "+method.ReturnType+"();"); foreach (FieldInfo fi in method.ReturnType.GetFields()) { AmqpFieldMappingAttribute returnFieldMapping = Attribute(fi, typeof(AmqpFieldMappingAttribute)) as AmqpFieldMappingAttribute; if (returnFieldMapping != null) { EmitLine(" __result." + fi.Name + " = __rep." + fieldPrefix + returnFieldMapping.m_fieldName + ";"); } else { EmitLine(" __result." + fi.Name + " = __rep." + fieldPrefix + fi.Name + ";"); } } EmitLine(" return __result;"); } else { // Field mapping --> return just the field we're interested in. EmitLine(" return __rep.m_"+returnMapping.m_fieldName+";"); } } } // All the IO and result-extraction has been done. Emit // the method postamble. EmitLine(" }"); } public void EmitAsynchronousHandlers(IList<MethodInfo> asynchronousHandlers) { EmitLine(" public override bool DispatchAsynchronous(RabbitMQ.Client.Impl.Command cmd) {"); EmitLine(" RabbitMQ.Client.Impl.MethodBase __method = (RabbitMQ.Client.Impl.MethodBase) cmd.Method;"); EmitLine(" switch ((__method.ProtocolClassId << 16) | __method.ProtocolMethodId) {"); foreach (MethodInfo method in asynchronousHandlers) { string methodName = method.Name; if (methodName.StartsWith("Handle")) { methodName = methodName.Substring(6); } AmqpClass amqpClass = null; AmqpMethod amqpMethod = null; LookupAmqpMethod(method, methodName, out amqpClass, out amqpMethod); string implClass = MangleMethodClass(amqpClass, amqpMethod); EmitLine(" case "+((amqpClass.Index << 16) | amqpMethod.Index)+": {"); ParameterInfo[] parameters = method.GetParameters(); if (parameters.Length > 0) { EmitLine(" "+implClass+" __impl = ("+implClass+") __method;"); EmitLine(" "+method.Name+"("); int remaining = parameters.Length; foreach (ParameterInfo pi in parameters) { if (Attribute(pi, typeof(AmqpContentHeaderMappingAttribute)) != null) { Emit(" ("+pi.ParameterType+") cmd.Header"); } else if (Attribute(pi, typeof(AmqpContentBodyMappingAttribute)) != null) { Emit(" cmd.Body"); } else { AmqpFieldMappingAttribute fieldMapping = Attribute(pi, typeof(AmqpFieldMappingAttribute)) as AmqpFieldMappingAttribute; Emit(" __impl.m_"+(fieldMapping == null ? pi.Name : fieldMapping.m_fieldName)); } remaining--; if (remaining > 0) { EmitLine(","); } } EmitLine(");"); } else { EmitLine(" "+method.Name+"();"); } EmitLine(" return true;"); EmitLine(" }"); } EmitLine(" default: return false;"); EmitLine(" }"); EmitLine(" }"); } } }
// 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.Buffers; using System.Numerics; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography; using Xunit; namespace System.Text.Tests { // Since many of the methods we'll be testing are internal, we'll need to invoke // them via reflection. public static unsafe partial class AsciiUtilityTests { private const int SizeOfVector128 = 128 / 8; // The delegate definitions and members below provide us access to CoreLib's internals. // We use UIntPtr instead of nuint everywhere here since we don't know what our target arch is. private delegate UIntPtr FnGetIndexOfFirstNonAsciiByte(byte* pBuffer, UIntPtr bufferLength); private static readonly UnsafeLazyDelegate<FnGetIndexOfFirstNonAsciiByte> _fnGetIndexOfFirstNonAsciiByte = new UnsafeLazyDelegate<FnGetIndexOfFirstNonAsciiByte>("GetIndexOfFirstNonAsciiByte"); private delegate UIntPtr FnGetIndexOfFirstNonAsciiChar(char* pBuffer, UIntPtr bufferLength); private static readonly UnsafeLazyDelegate<FnGetIndexOfFirstNonAsciiChar> _fnGetIndexOfFirstNonAsciiChar = new UnsafeLazyDelegate<FnGetIndexOfFirstNonAsciiChar>("GetIndexOfFirstNonAsciiChar"); private delegate UIntPtr FnNarrowUtf16ToAscii(char* pUtf16Buffer, byte* pAsciiBuffer, UIntPtr elementCount); private static readonly UnsafeLazyDelegate<FnNarrowUtf16ToAscii> _fnNarrowUtf16ToAscii = new UnsafeLazyDelegate<FnNarrowUtf16ToAscii>("NarrowUtf16ToAscii"); private delegate UIntPtr FnWidenAsciiToUtf16(byte* pAsciiBuffer, char* pUtf16Buffer, UIntPtr elementCount); private static readonly UnsafeLazyDelegate<FnWidenAsciiToUtf16> _fnWidenAsciiToUtf16 = new UnsafeLazyDelegate<FnWidenAsciiToUtf16>("WidenAsciiToUtf16"); [Fact] public static void GetIndexOfFirstNonAsciiByte_EmptyInput_NullReference() { Assert.Equal(UIntPtr.Zero, _fnGetIndexOfFirstNonAsciiByte.Delegate(null, UIntPtr.Zero)); } [Fact] public static void GetIndexOfFirstNonAsciiByte_EmptyInput_NonNullReference() { byte b = default; Assert.Equal(UIntPtr.Zero, _fnGetIndexOfFirstNonAsciiByte.Delegate(&b, UIntPtr.Zero)); } [Fact] public static void GetIndexOfFirstNonAsciiByte_Vector128InnerLoop() { // The purpose of this test is to make sure we're identifying the correct // vector (of the two that we're reading simultaneously) when performing // the final ASCII drain at the end of the method once we've broken out // of the inner loop. using (BoundedMemory<byte> mem = BoundedMemory.Allocate<byte>(1024)) { Span<byte> bytes = mem.Span; for (int i = 0; i < bytes.Length; i++) { bytes[i] &= 0x7F; // make sure each byte (of the pre-populated random data) is ASCII } // Two vectors have offsets 0 .. 31. We'll go backward to avoid having to // re-clear the vector every time. for (int i = 2 * SizeOfVector128 - 1; i >= 0; i--) { bytes[100 + i * 13] = 0x80; // 13 is relatively prime to 32, so it ensures all possible positions are hit Assert.Equal(100 + i * 13, CallGetIndexOfFirstNonAsciiByte(bytes)); } } } [Fact] public static void GetIndexOfFirstNonAsciiByte_Boundaries() { // The purpose of this test is to make sure we're hitting all of the vectorized // and draining logic correctly both in the SSE2 and in the non-SSE2 enlightened // code paths. We shouldn't be reading beyond the boundaries we were given. // The 5 * Vector test should make sure that we're exercising all possible // code paths across both implementations. using (BoundedMemory<byte> mem = BoundedMemory.Allocate<byte>(5 * Vector<byte>.Count)) { Span<byte> bytes = mem.Span; // First, try it with all-ASCII buffers. for (int i = 0; i < bytes.Length; i++) { bytes[i] &= 0x7F; // make sure each byte (of the pre-populated random data) is ASCII } for (int i = bytes.Length; i >= 0; i--) { Assert.Equal(i, CallGetIndexOfFirstNonAsciiByte(bytes.Slice(0, i))); } // Then, try it with non-ASCII bytes. for (int i = bytes.Length; i >= 1; i--) { bytes[i - 1] = 0x80; // set non-ASCII Assert.Equal(i - 1, CallGetIndexOfFirstNonAsciiByte(bytes.Slice(0, i))); } } } [Fact] public static void GetIndexOfFirstNonAsciiChar_EmptyInput_NullReference() { Assert.Equal(UIntPtr.Zero, _fnGetIndexOfFirstNonAsciiChar.Delegate(null, UIntPtr.Zero)); } [Fact] public static void GetIndexOfFirstNonAsciiChar_EmptyInput_NonNullReference() { char c = default; Assert.Equal(UIntPtr.Zero, _fnGetIndexOfFirstNonAsciiChar.Delegate(&c, UIntPtr.Zero)); } [Fact] public static void GetIndexOfFirstNonAsciiChar_Vector128InnerLoop() { // The purpose of this test is to make sure we're identifying the correct // vector (of the two that we're reading simultaneously) when performing // the final ASCII drain at the end of the method once we've broken out // of the inner loop. // // Use U+0123 instead of U+0080 for this test because if our implementation // uses pminuw / pmovmskb incorrectly, U+0123 will incorrectly show up as ASCII, // causing our test to produce a false negative. using (BoundedMemory<char> mem = BoundedMemory.Allocate<char>(1024)) { Span<char> chars = mem.Span; for (int i = 0; i < chars.Length; i++) { chars[i] &= '\u007F'; // make sure each char (of the pre-populated random data) is ASCII } // Two vectors have offsets 0 .. 31. We'll go backward to avoid having to // re-clear the vector every time. for (int i = 2 * SizeOfVector128 - 1; i >= 0; i--) { chars[100 + i * 13] = '\u0123'; // 13 is relatively prime to 32, so it ensures all possible positions are hit Assert.Equal(100 + i * 13, CallGetIndexOfFirstNonAsciiChar(chars)); } } } [Fact] public static void GetIndexOfFirstNonAsciiChar_Boundaries() { // The purpose of this test is to make sure we're hitting all of the vectorized // and draining logic correctly both in the SSE2 and in the non-SSE2 enlightened // code paths. We shouldn't be reading beyond the boundaries we were given. // // The 5 * Vector test should make sure that we're exercising all possible // code paths across both implementations. The sizeof(char) is because we're // specifying element count, but underlying implementation reintepret casts to bytes. // // Use U+0123 instead of U+0080 for this test because if our implementation // uses pminuw / pmovmskb incorrectly, U+0123 will incorrectly show up as ASCII, // causing our test to produce a false negative. using (BoundedMemory<char> mem = BoundedMemory.Allocate<char>(5 * Vector<byte>.Count / sizeof(char))) { Span<char> chars = mem.Span; for (int i = 0; i < chars.Length; i++) { chars[i] &= '\u007F'; // make sure each char (of the pre-populated random data) is ASCII } for (int i = chars.Length; i >= 0; i--) { Assert.Equal(i, CallGetIndexOfFirstNonAsciiChar(chars.Slice(0, i))); } // Then, try it with non-ASCII bytes. for (int i = chars.Length; i >= 1; i--) { chars[i - 1] = '\u0123'; // set non-ASCII Assert.Equal(i - 1, CallGetIndexOfFirstNonAsciiChar(chars.Slice(0, i))); } } } [Fact] public static void WidenAsciiToUtf16_EmptyInput_NullReferences() { Assert.Equal(UIntPtr.Zero, _fnWidenAsciiToUtf16.Delegate(null, null, UIntPtr.Zero)); } [Fact] public static void WidenAsciiToUtf16_EmptyInput_NonNullReference() { byte b = default; char c = default; Assert.Equal(UIntPtr.Zero, _fnWidenAsciiToUtf16.Delegate(&b, &c, UIntPtr.Zero)); } [Fact] public static void WidenAsciiToUtf16_AllAsciiInput() { using BoundedMemory<byte> asciiMem = BoundedMemory.Allocate<byte>(128); using BoundedMemory<char> utf16Mem = BoundedMemory.Allocate<char>(128); // Fill source with 00 .. 7F, then trap future writes. Span<byte> asciiSpan = asciiMem.Span; for (int i = 0; i < asciiSpan.Length; i++) { asciiSpan[i] = (byte)i; } asciiMem.MakeReadonly(); // We'll write to the UTF-16 span. // We test with a variety of span lengths to test alignment and fallthrough code paths. Span<char> utf16Span = utf16Mem.Span; for (int i = 0; i < asciiSpan.Length; i++) { utf16Span.Clear(); // remove any data from previous iteration // First, validate that the workhorse saw the incoming data as all-ASCII. Assert.Equal(128 - i, CallWidenAsciiToUtf16(asciiSpan.Slice(i), utf16Span.Slice(i))); // Then, validate that the data was transcoded properly. for (int j = i; j < 128; j++) { Assert.Equal((ushort)asciiSpan[i], (ushort)utf16Span[i]); } } } [Fact] public static void WidenAsciiToUtf16_SomeNonAsciiInput() { using BoundedMemory<byte> asciiMem = BoundedMemory.Allocate<byte>(128); using BoundedMemory<char> utf16Mem = BoundedMemory.Allocate<char>(128); // Fill source with 00 .. 7F, then trap future writes. Span<byte> asciiSpan = asciiMem.Span; for (int i = 0; i < asciiSpan.Length; i++) { asciiSpan[i] = (byte)i; } // We'll write to the UTF-16 span. Span<char> utf16Span = utf16Mem.Span; for (int i = asciiSpan.Length - 1; i >= 0; i--) { RandomNumberGenerator.Fill(MemoryMarshal.Cast<char, byte>(utf16Span)); // fill with garbage // First, keep track of the garbage we wrote to the destination. // We want to ensure it wasn't overwritten. char[] expectedTrailingData = utf16Span.Slice(i).ToArray(); // Then, set the desired byte as non-ASCII, then check that the workhorse // correctly saw the data as non-ASCII. asciiSpan[i] |= (byte)0x80; Assert.Equal(i, CallWidenAsciiToUtf16(asciiSpan, utf16Span)); // Next, validate that the ASCII data was transcoded properly. for (int j = 0; j < i; j++) { Assert.Equal((ushort)asciiSpan[j], (ushort)utf16Span[j]); } // Finally, validate that the trailing data wasn't overwritten with non-ASCII data. Assert.Equal(expectedTrailingData, utf16Span.Slice(i).ToArray()); } } [Fact] public static unsafe void NarrowUtf16ToAscii_EmptyInput_NullReferences() { Assert.Equal(UIntPtr.Zero, _fnNarrowUtf16ToAscii.Delegate(null, null, UIntPtr.Zero)); } [Fact] public static void NarrowUtf16ToAscii_EmptyInput_NonNullReference() { char c = default; byte b = default; Assert.Equal(UIntPtr.Zero, _fnNarrowUtf16ToAscii.Delegate(&c, &b, UIntPtr.Zero)); } [Fact] public static void NarrowUtf16ToAscii_AllAsciiInput() { using BoundedMemory<char> utf16Mem = BoundedMemory.Allocate<char>(128); using BoundedMemory<byte> asciiMem = BoundedMemory.Allocate<byte>(128); // Fill source with 00 .. 7F. Span<char> utf16Span = utf16Mem.Span; for (int i = 0; i < utf16Span.Length; i++) { utf16Span[i] = (char)i; } utf16Mem.MakeReadonly(); // We'll write to the ASCII span. // We test with a variety of span lengths to test alignment and fallthrough code paths. Span<byte> asciiSpan = asciiMem.Span; for (int i = 0; i < utf16Span.Length; i++) { asciiSpan.Clear(); // remove any data from previous iteration // First, validate that the workhorse saw the incoming data as all-ASCII. Assert.Equal(128 - i, CallNarrowUtf16ToAscii(utf16Span.Slice(i), asciiSpan.Slice(i))); // Then, validate that the data was transcoded properly. for (int j = i; j < 128; j++) { Assert.Equal((ushort)utf16Span[i], (ushort)asciiSpan[i]); } } } [Fact] public static void NarrowUtf16ToAscii_SomeNonAsciiInput() { using BoundedMemory<char> utf16Mem = BoundedMemory.Allocate<char>(128); using BoundedMemory<byte> asciiMem = BoundedMemory.Allocate<byte>(128); // Fill source with 00 .. 7F. Span<char> utf16Span = utf16Mem.Span; for (int i = 0; i < utf16Span.Length; i++) { utf16Span[i] = (char)i; } // We'll write to the ASCII span. Span<byte> asciiSpan = asciiMem.Span; for (int i = utf16Span.Length - 1; i >= 0; i--) { RandomNumberGenerator.Fill(asciiSpan); // fill with garbage // First, keep track of the garbage we wrote to the destination. // We want to ensure it wasn't overwritten. byte[] expectedTrailingData = asciiSpan.Slice(i).ToArray(); // Then, set the desired byte as non-ASCII, then check that the workhorse // correctly saw the data as non-ASCII. utf16Span[i] = '\u0123'; // use U+0123 instead of U+0080 since it catches inappropriate pmovmskb usage Assert.Equal(i, CallNarrowUtf16ToAscii(utf16Span, asciiSpan)); // Next, validate that the ASCII data was transcoded properly. for (int j = 0; j < i; j++) { Assert.Equal((ushort)utf16Span[j], (ushort)asciiSpan[j]); } // Finally, validate that the trailing data wasn't overwritten with non-ASCII data. Assert.Equal(expectedTrailingData, asciiSpan.Slice(i).ToArray()); } } private static int CallGetIndexOfFirstNonAsciiByte(ReadOnlySpan<byte> buffer) { fixed (byte* pBuffer = &MemoryMarshal.GetReference(buffer)) { // Conversions between UIntPtr <-> int are not checked by default. return checked((int)_fnGetIndexOfFirstNonAsciiByte.Delegate(pBuffer, (UIntPtr)buffer.Length)); } } private static int CallGetIndexOfFirstNonAsciiChar(ReadOnlySpan<char> buffer) { fixed (char* pBuffer = &MemoryMarshal.GetReference(buffer)) { // Conversions between UIntPtr <-> int are not checked by default. return checked((int)_fnGetIndexOfFirstNonAsciiChar.Delegate(pBuffer, (UIntPtr)buffer.Length)); } } private static int CallNarrowUtf16ToAscii(ReadOnlySpan<char> utf16, Span<byte> ascii) { Assert.Equal(utf16.Length, ascii.Length); fixed (char* pUtf16 = &MemoryMarshal.GetReference(utf16)) fixed (byte* pAscii = &MemoryMarshal.GetReference(ascii)) { // Conversions between UIntPtr <-> int are not checked by default. return checked((int)_fnNarrowUtf16ToAscii.Delegate(pUtf16, pAscii, (UIntPtr)utf16.Length)); } } private static int CallWidenAsciiToUtf16(ReadOnlySpan<byte> ascii, Span<char> utf16) { Assert.Equal(ascii.Length, utf16.Length); fixed (byte* pAscii = &MemoryMarshal.GetReference(ascii)) fixed (char* pUtf16 = &MemoryMarshal.GetReference(utf16)) { // Conversions between UIntPtr <-> int are not checked by default. return checked((int)_fnWidenAsciiToUtf16.Delegate(pAscii, pUtf16, (UIntPtr)ascii.Length)); } } private static Type GetAsciiUtilityType() { return typeof(object).Assembly.GetType("System.Text.ASCIIUtility"); } private sealed class UnsafeLazyDelegate<TDelegate> where TDelegate : class { private readonly Lazy<TDelegate> _lazyDelegate; public UnsafeLazyDelegate(string methodName) { _lazyDelegate = new Lazy<TDelegate>(() => { Assert.True(typeof(TDelegate).IsSubclassOf(typeof(MulticastDelegate))); // Get the MethodInfo for the target method MethodInfo methodInfo = GetAsciiUtilityType().GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); Assert.NotNull(methodInfo); // Construct the TDelegate pointing to this method return (TDelegate)Activator.CreateInstance(typeof(TDelegate), new object[] { null, methodInfo.MethodHandle.GetFunctionPointer() }); }); } public TDelegate Delegate => _lazyDelegate.Value; } } }
//------------------------------------------------------------------------------ // <copyright file="Compiler.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Xml.Serialization { using System.Reflection; using System.Reflection.Emit; using System.Collections; using System.IO; using System; using System.Text; using System.ComponentModel; using System.CodeDom.Compiler; using System.Security; using System.Security.Permissions; using System.Diagnostics; using System.Security.Principal; using System.Security.Policy; using System.Threading; using System.Xml.Serialization.Configuration; using System.Globalization; using System.Runtime.Versioning; using System.Runtime.CompilerServices; internal class Compiler { bool debugEnabled = DiagnosticsSwitches.KeepTempFiles.Enabled; Hashtable imports = new Hashtable(); StringWriter writer = new StringWriter(CultureInfo.InvariantCulture); [ResourceExposure(ResourceScope.Machine)] protected string[] Imports { get { string[] array = new string[imports.Values.Count]; imports.Values.CopyTo(array, 0); return array; } } // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] [ResourceExposure(ResourceScope.None)] internal void AddImport(Type type, Hashtable types) { if (type == null) return; if (TypeScope.IsKnownType(type)) return; if (types[type] != null) return; types[type] = type; Type baseType = type.BaseType; if (baseType != null) AddImport(baseType, types); Type declaringType = type.DeclaringType; if (declaringType != null) AddImport(declaringType, types); foreach (Type intf in type.GetInterfaces()) AddImport(intf, types); ConstructorInfo[] ctors = type.GetConstructors(); for (int i = 0; i < ctors.Length; i++) { ParameterInfo[] parms = ctors[i].GetParameters(); for (int j = 0; j < parms.Length; j++) { AddImport(parms[j].ParameterType, types); } } if (type.IsGenericType) { Type[] arguments = type.GetGenericArguments(); for (int i = 0; i < arguments.Length; i++) { AddImport(arguments[i], types); } } TempAssembly.FileIOPermission.Assert(); Module module = type.Module; Assembly assembly = module.Assembly; if (DynamicAssemblies.IsTypeDynamic(type)) { DynamicAssemblies.Add(assembly); return; } object[] typeForwardedFromAttribute = type.GetCustomAttributes(typeof(TypeForwardedFromAttribute), false); if (typeForwardedFromAttribute.Length > 0) { TypeForwardedFromAttribute originalAssemblyInfo = typeForwardedFromAttribute[0] as TypeForwardedFromAttribute; Assembly originalAssembly = Assembly.Load(originalAssemblyInfo.AssemblyFullName); imports[originalAssembly] = originalAssembly.Location; } imports[assembly] = assembly.Location; } // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] [ResourceExposure(ResourceScope.None)] internal void AddImport(Assembly assembly) { TempAssembly.FileIOPermission.Assert(); imports[assembly] = assembly.Location; } internal TextWriter Source { get { return writer; } } internal void Close() { } [ResourceConsumption(ResourceScope.Machine)] [ResourceExposure(ResourceScope.Machine)] internal static string GetTempAssemblyPath(string baseDir, Assembly assembly, string defaultNamespace) { if (assembly.IsDynamic) { throw new InvalidOperationException(Res.GetString(Res.XmlPregenAssemblyDynamic)); } PermissionSet perms = new PermissionSet(PermissionState.None); perms.AddPermission(new FileIOPermission(PermissionState.Unrestricted)); perms.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted)); perms.Assert(); try { if (baseDir != null && baseDir.Length > 0) { // check that the dirsctory exists if (!Directory.Exists(baseDir)) { throw new UnauthorizedAccessException(Res.GetString(Res.XmlPregenMissingDirectory, baseDir)); } } else { baseDir = Path.GetTempPath(); // check that the dirsctory exists if (!Directory.Exists(baseDir)) { throw new UnauthorizedAccessException(Res.GetString(Res.XmlPregenMissingTempDirectory)); } } if (baseDir.EndsWith("\\", StringComparison.Ordinal)) baseDir += GetTempAssemblyName(assembly.GetName(), defaultNamespace); else baseDir += "\\" + GetTempAssemblyName(assembly.GetName(), defaultNamespace); } finally { CodeAccessPermission.RevertAssert(); } return baseDir + ".dll"; } internal static string GetTempAssemblyName(AssemblyName parent, string ns) { return parent.Name + ".XmlSerializers" + (ns == null || ns.Length == 0 ? "" : "." + ns.GetHashCode()); } // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] [ResourceExposure(ResourceScope.None)] internal Assembly Compile(Assembly parent, string ns, XmlSerializerCompilerParameters xmlParameters, Evidence evidence) { CodeDomProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); CompilerParameters parameters = xmlParameters.CodeDomParameters; parameters.ReferencedAssemblies.AddRange(Imports); if (debugEnabled) { parameters.GenerateInMemory = false; parameters.IncludeDebugInformation = true; parameters.TempFiles.KeepFiles = true; } PermissionSet perms = new PermissionSet(PermissionState.None); if (xmlParameters.IsNeedTempDirAccess) { perms.AddPermission(TempAssembly.FileIOPermission); } perms.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted)); perms.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)); perms.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlEvidence)); perms.Assert(); if (parent != null && (parameters.OutputAssembly == null || parameters.OutputAssembly.Length ==0)) { string assemblyName = AssemblyNameFromOptions(parameters.CompilerOptions); if (assemblyName == null) assemblyName = GetTempAssemblyPath(parameters.TempFiles.TempDir, parent, ns); // parameters.OutputAssembly = assemblyName; } if (parameters.CompilerOptions == null || parameters.CompilerOptions.Length == 0) parameters.CompilerOptions = "/nostdlib"; else parameters.CompilerOptions += " /nostdlib"; parameters.CompilerOptions += " /D:_DYNAMIC_XMLSERIALIZER_COMPILATION"; #pragma warning disable 618 parameters.Evidence = evidence; #pragma warning restore 618 CompilerResults results = null; Assembly assembly = null; try { results = codeProvider.CompileAssemblyFromSource(parameters, writer.ToString()); // check the output for errors or a certain level-1 warning (1595) if (results.Errors.Count > 0) { StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture); stringWriter.WriteLine(Res.GetString(Res.XmlCompilerError, results.NativeCompilerReturnValue.ToString(CultureInfo.InvariantCulture))); bool foundOne = false; foreach (CompilerError e in results.Errors) { // clear filename. This makes ToString() print just error number and message. e.FileName = ""; if (!e.IsWarning || e.ErrorNumber == "CS1595") { foundOne = true; stringWriter.WriteLine(e.ToString()); } } if (foundOne) { throw new InvalidOperationException(stringWriter.ToString()); } } assembly = results.CompiledAssembly; } catch (UnauthorizedAccessException) { // try to get the user token string user = GetCurrentUser(); if (user == null || user.Length == 0) { throw new UnauthorizedAccessException(Res.GetString(Res.XmlSerializerAccessDenied)); } else { throw new UnauthorizedAccessException(Res.GetString(Res.XmlIdentityAccessDenied, user)); } } catch (FileLoadException fle) { throw new InvalidOperationException(Res.GetString(Res.XmlSerializerCompileFailed), fle); } finally { CodeAccessPermission.RevertAssert(); } // somehow we got here without generating an assembly if (assembly == null) throw new InvalidOperationException(Res.GetString(Res.XmlInternalError)); return assembly; } static string AssemblyNameFromOptions(string options) { if (options == null || options.Length == 0) return null; string outName = null; string[] flags = options.ToLower(CultureInfo.InvariantCulture).Split(null); for (int i = 0; i < flags.Length; i++) { string val = flags[i].Trim(); if (val.StartsWith("/out:", StringComparison.Ordinal)) { outName = val.Substring(5); } } return outName; } internal static string GetCurrentUser() { #if !FEATURE_PAL try { WindowsIdentity id = WindowsIdentity.GetCurrent(); if (id != null && id.Name != null) return id.Name; } catch (Exception e) { if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } } #endif // !FEATURE_PAL return ""; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.IO; using System.Text; using System.Diagnostics; using System.Reflection; using System.Runtime.Serialization; using System.Reflection.Runtime.General; using System.Reflection.Runtime.Modules; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.TypeParsing; using System.Reflection.Runtime.CustomAttributes; using System.Collections.Generic; using Internal.Reflection.Core; using Internal.Reflection.Core.Execution; using Internal.Reflection.Tracing; using System.Security; namespace System.Reflection.Runtime.Assemblies { // // The runtime's implementation of an Assembly. // internal abstract partial class RuntimeAssembly : Assembly, IEquatable<RuntimeAssembly> { public bool Equals(RuntimeAssembly other) { if (other == null) return false; return this.Equals((object)other); } public sealed override String FullName { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.Assembly_FullName(this); #endif return GetName().FullName; } } public sealed override void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } public abstract override Module ManifestModule { get; } public sealed override IEnumerable<Module> Modules { get { yield return ManifestModule; } } public sealed override Type GetType(String name, bool throwOnError, bool ignoreCase) { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.Assembly_GetType(this, name); #endif if (name == null) throw new ArgumentNullException(); if (name.Length == 0) throw new ArgumentException(); TypeName typeName = TypeParser.ParseAssemblyQualifiedTypeName(name, throwOnError: throwOnError); if (typeName == null) return null; if (typeName is AssemblyQualifiedTypeName) { if (throwOnError) throw new ArgumentException(SR.Argument_AssemblyGetTypeCannotSpecifyAssembly); // Cannot specify an assembly qualifier in a typename passed to Assembly.GetType() else return null; } CoreAssemblyResolver coreAssemblyResolver = RuntimeAssembly.GetRuntimeAssemblyIfExists; CoreTypeResolver coreTypeResolver = delegate (Assembly containingAssemblyIfAny, string coreTypeName) { if (containingAssemblyIfAny == null) return GetTypeCore(coreTypeName, ignoreCase: ignoreCase); else return containingAssemblyIfAny.GetTypeCore(coreTypeName, ignoreCase: ignoreCase); }; GetTypeOptions getTypeOptions = new GetTypeOptions(coreAssemblyResolver, coreTypeResolver, throwOnError: throwOnError, ignoreCase: ignoreCase); return typeName.ResolveType(this, getTypeOptions); } #pragma warning disable 0067 // Silence warning about ModuleResolve not being used. public sealed override event ModuleResolveEventHandler ModuleResolve; #pragma warning restore 0067 public sealed override bool ReflectionOnly { get { return false; // ReflectionOnly loading not supported. } } internal abstract RuntimeAssemblyName RuntimeAssemblyName { get; } public sealed override AssemblyName GetName() { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.Assembly_GetName(this); #endif return RuntimeAssemblyName.ToAssemblyName(); } /// <summary> /// Helper routine for the more general Type.GetType() family of apis. /// /// Resolves top-level named types only. No nested types. No constructed types. /// /// Returns null if the type does not exist. Throws for all other error cases. /// </summary> internal RuntimeTypeInfo GetTypeCore(string fullName, bool ignoreCase) { if (ignoreCase) return GetTypeCoreCaseInsensitive(fullName); else return GetTypeCoreCaseSensitive(fullName); } // Types that derive from RuntimeAssembly must implement the following public surface area members public abstract override IEnumerable<CustomAttributeData> CustomAttributes { get; } public abstract override IEnumerable<TypeInfo> DefinedTypes { get; } public abstract override MethodInfo EntryPoint { get; } public abstract override IEnumerable<Type> ExportedTypes { get; } public abstract override ManifestResourceInfo GetManifestResourceInfo(String resourceName); public abstract override String[] GetManifestResourceNames(); public abstract override Stream GetManifestResourceStream(String name); public abstract override bool Equals(Object obj); public abstract override int GetHashCode(); /// <summary> /// Ensures a module is loaded and that its module constructor is executed. If the module is fully /// loaded and its constructor already ran, we do not run it again. /// </summary> internal abstract void RunModuleConstructor(); /// <summary> /// Perform a lookup for a type based on a name. Overriders are expected to /// have a non-cached implementation, as the result is expected to be cached by /// callers of this method. Should be implemented by every format specific /// RuntimeAssembly implementor /// </summary> internal abstract RuntimeTypeInfo UncachedGetTypeCoreCaseSensitive(string fullName); /// <summary> /// Perform a lookup for a type based on a name. Overriders may or may not /// have a cached implementation, as the result is not expected to be cached by /// callers of this method, but it is also a rarely used api. Should be /// implemented by every format specific RuntimeAssembly implementor /// </summary> internal abstract RuntimeTypeInfo GetTypeCoreCaseInsensitive(string fullName); internal RuntimeTypeInfo GetTypeCoreCaseSensitive(string fullName) { return this.CaseSensitiveTypeTable.GetOrAdd(fullName); } private CaseSensitiveTypeCache CaseSensitiveTypeTable { get { return _lazyCaseSensitiveTypeTable ?? (_lazyCaseSensitiveTypeTable = new CaseSensitiveTypeCache(this)); } } public sealed override bool GlobalAssemblyCache { get { return false; } } public sealed override long HostContext { get { return 0; } } public sealed override Module LoadModule(string moduleName, byte[] rawModule, byte[] rawSymbolStore) { throw new PlatformNotSupportedException(); } public sealed override FileStream GetFile(string name) { throw new PlatformNotSupportedException(); } public sealed override FileStream[] GetFiles(bool getResourceModules) { throw new PlatformNotSupportedException(); } public sealed override SecurityRuleSet SecurityRuleSet { get { return SecurityRuleSet.None; } } /// <summary> /// Returns a *freshly allocated* array of loaded Assemblies. /// </summary> internal static Assembly[] GetLoadedAssemblies() { // Important: The result of this method is the return value of the AppDomain.GetAssemblies() api so // so it must return a freshly allocated array on each call. AssemblyBinder binder = ReflectionCoreExecution.ExecutionDomain.ReflectionDomainSetup.AssemblyBinder; IList<AssemblyBindResult> bindResults = binder.GetLoadedAssemblies(); Assembly[] results = new Assembly[bindResults.Count]; for (int i = 0; i < bindResults.Count; i++) { Assembly assembly = GetRuntimeAssembly(bindResults[i]); results[i] = assembly; } return results; } private volatile CaseSensitiveTypeCache _lazyCaseSensitiveTypeTable; private sealed class CaseSensitiveTypeCache : ConcurrentUnifier<string, RuntimeTypeInfo> { public CaseSensitiveTypeCache(RuntimeAssembly runtimeAssembly) { _runtimeAssembly = runtimeAssembly; } protected sealed override RuntimeTypeInfo Factory(string key) { return _runtimeAssembly.UncachedGetTypeCoreCaseSensitive(key); } private readonly RuntimeAssembly _runtimeAssembly; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Linq; using System.Collections.Generic; using System.Globalization; using System.Text.RegularExpressions; using System.Diagnostics.CodeAnalysis; using AutoRest.Core.Model; using AutoRest.Core.Utilities; using AutoRest.Swagger.Properties; using AutoRest.Core.Validation; using AutoRest.Swagger.Validation; using Newtonsoft.Json; using static AutoRest.Core.Utilities.DependencyInjection; namespace AutoRest.Swagger.Model { /// <summary> /// Describes a single operation determining with this object is mandatory. /// https://github.com/wordnik/swagger-spec/blob/master/versions/2.0.md#parameterObject /// </summary> [Rule(typeof(DefaultMustBeInEnum))] public abstract class SwaggerObject : SwaggerBase { private string _description; public virtual bool IsRequired { get; set; } /// <summary> /// The type of the parameter. /// </summary> public virtual DataType? Type { get; set; } /// <summary> /// The extending format for the previously mentioned type. /// </summary> [Rule(typeof(ValidFormats))] public virtual string Format { get; set; } /// <summary> /// Returns the KnownFormat of the Format string (provided it matches a KnownFormat) /// Otherwise, returns KnownFormat.none /// </summary> public KnownFormat KnownFormat => KnownFormatExtensions.Parse(Format); /// <summary> /// Describes the type of items in the array. /// </summary> public virtual Schema Items { get; set; } [JsonProperty(PropertyName = "$ref")] public string Reference { get; set; } /// <summary> /// Describes the type of additional properties in the data type. /// </summary> public virtual Schema AdditionalProperties { get; set; } [Rule(typeof(DescriptiveDescriptionRequired))] public virtual string Description { get { return _description; } set { _description = value.StripControlCharacters(); } } /// <summary> /// Determines the format of the array if type array is used. /// </summary> public virtual CollectionFormat CollectionFormat { get; set; } /// <summary> /// Sets a default value to the parameter. /// </summary> public virtual string Default { get; set; } [Rule(typeof(InvalidConstraint))] public virtual string MultipleOf { get; set; } [Rule(typeof(InvalidConstraint))] public virtual string Maximum { get; set; } [Rule(typeof(InvalidConstraint))] public virtual bool ExclusiveMaximum { get; set; } [Rule(typeof(InvalidConstraint))] public virtual string Minimum { get; set; } [Rule(typeof(InvalidConstraint))] public virtual bool ExclusiveMinimum { get; set; } [Rule(typeof(InvalidConstraint))] public virtual string MaxLength { get; set; } [Rule(typeof(InvalidConstraint))] public virtual string MinLength { get; set; } [Rule(typeof(InvalidConstraint))] public virtual string Pattern { get; set; } [Rule(typeof(InvalidConstraint))] public virtual string MaxItems { get; set; } [Rule(typeof(InvalidConstraint))] public virtual string MinItems { get; set; } [Rule(typeof(InvalidConstraint))] public virtual bool UniqueItems { get; set; } public virtual IList<string> Enum { get; set; } public ObjectBuilder GetBuilder(SwaggerModeler swaggerSpecBuilder) { if (this is SwaggerParameter) { return new ParameterBuilder(this as SwaggerParameter, swaggerSpecBuilder); } if (this is Schema) { return new SchemaBuilder(this as Schema, swaggerSpecBuilder); } return new ObjectBuilder(this, swaggerSpecBuilder); } /// <summary> /// Returns the PrimaryType that the SwaggerObject maps to, given the Type and the KnownFormat. /// /// Note: Since a given language still may interpret the value of the Format after this, /// it is possible the final implemented type may not be the type given here. /// /// This allows languages to not have a specific PrimaryType decided by the Modeler. /// /// For example, if the Type is DataType.String, and the KnownFormat is 'char' the C# generator /// will end up creating a char type in the generated code, but other languages will still /// use string. /// </summary> /// <returns> /// The PrimaryType that best represents this object. /// </returns> public PrimaryType ToType() { switch (Type) { case DataType.String: switch (KnownFormat) { case KnownFormat.date: return New<PrimaryType>(KnownPrimaryType.Date); case KnownFormat.date_time: return New<PrimaryType>(KnownPrimaryType.DateTime); case KnownFormat.date_time_rfc1123: return New<PrimaryType>(KnownPrimaryType.DateTimeRfc1123); case KnownFormat.@byte: return New<PrimaryType>(KnownPrimaryType.ByteArray); case KnownFormat.duration: return New<PrimaryType>(KnownPrimaryType.TimeSpan); case KnownFormat.uuid: return New<PrimaryType>(KnownPrimaryType.Uuid); case KnownFormat.base64url: return New<PrimaryType>(KnownPrimaryType.Base64Url); default: return New<PrimaryType>(KnownPrimaryType.String); } case DataType.Number: switch (KnownFormat) { case KnownFormat.@decimal: return New<PrimaryType>(KnownPrimaryType.Decimal); default: return New<PrimaryType>(KnownPrimaryType.Double); } case DataType.Integer: switch (KnownFormat) { case KnownFormat.int64: return New<PrimaryType>(KnownPrimaryType.Long); case KnownFormat.unixtime: return New<PrimaryType>(KnownPrimaryType.UnixTime); default: return New<PrimaryType>(KnownPrimaryType.Int); } case DataType.Boolean: return New<PrimaryType>(KnownPrimaryType.Boolean); case DataType.Object: case DataType.Array: case null: return New<PrimaryType>(KnownPrimaryType.Object); case DataType.File: return New<PrimaryType>(KnownPrimaryType.Stream); default: throw new NotImplementedException( string.Format(CultureInfo.InvariantCulture, Resources.InvalidTypeInSwaggerSchema, Type)); } } /// <summary> /// Compare a modified document node (this) to a previous one and look for breaking as well as non-breaking changes. /// </summary> /// <param name="context">The modified document context.</param> /// <param name="previous">The original document model.</param> /// <returns>A list of messages from the comparison.</returns> public override IEnumerable<ComparisonMessage> Compare(ComparisonContext context, SwaggerBase previous) { var prior = previous as SwaggerObject; if (prior == null) { throw new ArgumentNullException("priorVersion"); } if (context == null) { throw new ArgumentNullException("context"); } base.Compare(context, previous); if (Reference != null && !Reference.Equals(prior.Reference)) { context.LogBreakingChange(ComparisonMessages.ReferenceRedirection); } if (IsRequired != prior.IsRequired) { if (context.Direction != DataDirection.Response) { if (IsRequired && !prior.IsRequired) { context.LogBreakingChange(ComparisonMessages.RequiredStatusChange); } else { context.LogInfo(ComparisonMessages.RequiredStatusChange); } } } // Are the types the same? if (prior.Type.HasValue != Type.HasValue || (Type.HasValue && prior.Type.Value != Type.Value)) { context.LogBreakingChange(ComparisonMessages.TypeChanged); } // What about the formats? CompareFormats(context, prior); CompareItems(context, prior); if (Default != null && !Default.Equals(prior.Default) || (Default == null && !string.IsNullOrEmpty(prior.Default))) { context.LogBreakingChange(ComparisonMessages.DefaultValueChanged); } if (Type.HasValue && Type.Value == DataType.Array && prior.CollectionFormat != CollectionFormat) { context.LogBreakingChange(ComparisonMessages.ArrayCollectionFormatChanged); } CompareConstraints(context, prior); CompareProperties(context, prior); CompareEnums(context, prior); return context.Messages; } private void CompareEnums(ComparisonContext context, SwaggerObject prior) { if (prior.Enum == null && this.Enum == null) return; bool relaxes = (prior.Enum != null && this.Enum == null); bool constrains = (prior.Enum == null && this.Enum != null); if (!relaxes && !constrains) { // 1. Look for removed elements (constraining). constrains = prior.Enum.Any(str => !this.Enum.Contains(str)); // 2. Look for added elements (relaxing). relaxes = this.Enum.Any(str => !prior.Enum.Contains(str)); } if (context.Direction == DataDirection.Request) { if (constrains) { context.LogBreakingChange(relaxes ? ComparisonMessages.ConstraintChanged : ComparisonMessages.ConstraintIsStronger, "enum"); return; } } else if (context.Direction == DataDirection.Response) { if (relaxes) { context.LogBreakingChange(constrains ? ComparisonMessages.ConstraintChanged : ComparisonMessages.ConstraintIsWeaker, "enum"); return; } } if (relaxes && constrains) context.LogInfo(ComparisonMessages.ConstraintChanged, "enum"); else if (relaxes || constrains) context.LogInfo(relaxes ? ComparisonMessages.ConstraintIsWeaker : ComparisonMessages.ConstraintIsStronger, "enum"); } private void CompareProperties(ComparisonContext context, SwaggerObject prior) { // Additional properties if (prior.AdditionalProperties == null && AdditionalProperties != null) { context.LogBreakingChange(ComparisonMessages.AddedAdditionalProperties); } else if (prior.AdditionalProperties != null && AdditionalProperties == null) { context.LogBreakingChange(ComparisonMessages.RemovedAdditionalProperties); } else if (AdditionalProperties != null) { context.PushProperty("additionalProperties"); AdditionalProperties.Compare(context, prior.AdditionalProperties); context.Pop(); } } protected void CompareFormats(ComparisonContext context, SwaggerObject prior) { if (prior == null) { throw new ArgumentNullException("prior"); } if (context == null) { throw new ArgumentNullException("context"); } if (prior.Format == null && Format != null || prior.Format != null && Format == null || prior.Format != null && Format != null && !prior.Format.Equals(Format)) { context.LogBreakingChange(ComparisonMessages.TypeFormatChanged); } } [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "It may look complex, but it really isn't.")] protected void CompareConstraints(ComparisonContext context, SwaggerObject prior) { if (prior == null) { throw new ArgumentNullException("prior"); } if (context == null) { throw new ArgumentNullException("context"); } if ((prior.MultipleOf == null && MultipleOf != null) || (prior.MultipleOf != null && !prior.MultipleOf.Equals(MultipleOf))) { context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "multipleOf"); } if ((prior.Maximum == null && Maximum != null) || (prior.Maximum != null && !prior.Maximum.Equals(Maximum)) || prior.ExclusiveMaximum != ExclusiveMaximum) { // Flag stricter constraints for requests and relaxed constraints for responses. if (prior.ExclusiveMaximum != ExclusiveMaximum || context.Direction == DataDirection.None) context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "maximum"); else if (context.Direction == DataDirection.Request && Narrows(prior.Maximum, Maximum, true)) context.LogBreakingChange(ComparisonMessages.ConstraintIsStronger, "maximum"); else if (context.Direction == DataDirection.Response && Widens(prior.Maximum, Maximum, true)) context.LogBreakingChange(ComparisonMessages.ConstraintIsWeaker, "maximum"); else if (Narrows(prior.Maximum, Maximum, false)) context.LogInfo(ComparisonMessages.ConstraintIsStronger, "maximum"); else if (Widens(prior.Maximum, Maximum, false)) context.LogInfo(ComparisonMessages.ConstraintIsWeaker, "maximum"); } if ((prior.Minimum == null && Minimum != null) || (prior.Minimum != null && !prior.Minimum.Equals(Minimum)) || prior.ExclusiveMinimum != ExclusiveMinimum) { // Flag stricter constraints for requests and relaxed constraints for responses. if (prior.ExclusiveMinimum != ExclusiveMinimum || context.Direction == DataDirection.None) context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "minimum"); else if (context.Direction == DataDirection.Request && Narrows(prior.Minimum, Minimum, true)) context.LogBreakingChange(ComparisonMessages.ConstraintIsStronger, "minimum"); else if (context.Direction == DataDirection.Response && Widens(prior.Minimum, Minimum, true)) context.LogBreakingChange(ComparisonMessages.ConstraintIsWeaker, "minimum"); else if (Narrows(prior.Minimum, Minimum, false)) context.LogInfo(ComparisonMessages.ConstraintIsStronger, "minimum"); else if (Widens(prior.Minimum, Minimum, false)) context.LogInfo(ComparisonMessages.ConstraintIsWeaker, "minimum"); } if ((prior.MaxLength == null && MaxLength != null) || (prior.MaxLength != null && !prior.MaxLength.Equals(MaxLength))) { // Flag stricter constraints for requests and relaxed constraints for responses. if (context.Direction == DataDirection.None) context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "maxLength"); else if (context.Direction == DataDirection.Request && Narrows(prior.MaxLength, MaxLength, false)) context.LogBreakingChange(ComparisonMessages.ConstraintIsStronger, "maxLength"); else if (context.Direction == DataDirection.Response && Widens(prior.MaxLength, MaxLength, false)) context.LogBreakingChange(ComparisonMessages.ConstraintIsWeaker, "maxLength"); else if (Narrows(prior.MaxLength, MaxLength, false)) context.LogInfo(ComparisonMessages.ConstraintIsStronger, "maxLength"); else if (Widens(prior.MaxLength, MaxLength, false)) context.LogInfo(ComparisonMessages.ConstraintIsWeaker, "maxLength"); } if ((prior.MinLength == null && MinLength != null) || (prior.MinLength != null && !prior.MinLength.Equals(MinLength))) { // Flag stricter constraints for requests and relaxed constraints for responses. if (context.Direction == DataDirection.None) context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "minLength"); else if (context.Direction == DataDirection.Request && Narrows(prior.MinLength, MinLength, true)) context.LogBreakingChange(ComparisonMessages.ConstraintIsStronger, "minimum"); else if (context.Direction == DataDirection.Response && Widens(prior.MinLength, MinLength, true)) context.LogBreakingChange(ComparisonMessages.ConstraintIsWeaker, "minimum"); else if (Narrows(prior.MinLength, MinLength, false)) context.LogInfo(ComparisonMessages.ConstraintIsStronger, "minLength"); else if (Widens(prior.MinLength, MinLength, false)) context.LogInfo(ComparisonMessages.ConstraintIsWeaker, "minLength"); } if ((prior.Pattern == null && Pattern != null) || (prior.Pattern != null && !prior.Pattern.Equals(Pattern))) { context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "pattern"); } if ((prior.MaxItems == null && MaxItems != null) || (prior.MaxItems != null && !prior.MaxItems.Equals(MaxItems))) { // Flag stricter constraints for requests and relaxed constraints for responses. if (context.Direction == DataDirection.None) context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "maxItems"); else if (context.Direction == DataDirection.Request && Narrows(prior.MaxItems, MaxItems, false)) context.LogBreakingChange(ComparisonMessages.ConstraintIsStronger, "maxItems"); else if (context.Direction == DataDirection.Response && Widens(prior.MaxItems, MaxItems, false)) context.LogBreakingChange(ComparisonMessages.ConstraintIsWeaker, "maxItems"); else if (Narrows(prior.MaxItems, MaxItems, false)) context.LogInfo(ComparisonMessages.ConstraintIsStronger, "maxItems"); else if (Widens(prior.MaxItems, MaxItems, false)) context.LogInfo(ComparisonMessages.ConstraintIsWeaker, "maxItems"); } if ((prior.MinItems == null && MinItems != null) || (prior.MinItems != null && !prior.MinItems.Equals(MinItems))) { // Flag stricter constraints for requests and relaxed constraints for responses. if (context.Direction == DataDirection.None) context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "minItems"); else if (context.Direction == DataDirection.Request && Narrows(prior.MinItems, MinItems, true)) context.LogBreakingChange(ComparisonMessages.ConstraintIsStronger, "minItems"); else if (context.Direction == DataDirection.Response && Widens(prior.MinItems, MinItems, true)) context.LogBreakingChange(ComparisonMessages.ConstraintIsWeaker, "minItems"); else if (Narrows(prior.MinItems, MinItems, true)) context.LogInfo(ComparisonMessages.ConstraintIsStronger, "minItems"); else if (Widens(prior.MinItems, MinItems, true)) context.LogInfo(ComparisonMessages.ConstraintIsWeaker, "minItems"); } if (prior.UniqueItems != UniqueItems) { context.LogBreakingChange(ComparisonMessages.ConstraintChanged, "uniqueItems"); } } private bool Narrows(string previous, string current, bool isLowerBound) { int p = 0; int c = 0; return int.TryParse(previous, out p) && int.TryParse(current, out c) && (isLowerBound ? (c > p) : (c < p)); } private bool Widens(string previous, string current, bool isLowerBound) { int p = 0; int c = 0; return int.TryParse(previous, out p) && int.TryParse(current, out c) && (isLowerBound ? (c < p) : (c > p)); } protected void CompareItems(ComparisonContext context, SwaggerObject prior) { if (prior == null) { throw new ArgumentNullException("prior"); } if (context == null) { throw new ArgumentNullException("context"); } if (prior.Items != null && Items != null) { context.PushProperty("items"); Items.Compare(context, prior.Items); context.Pop(); } } } }
// // 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. // using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using DiscUtils.CoreCompat; using DiscUtils.Internal; using DiscUtils.Partitions; using DiscUtils.Raw; using DiscUtils.Streams; namespace DiscUtils { /// <summary> /// VolumeManager interprets partitions and other on-disk structures (possibly combining multiple disks). /// </summary> /// <remarks> /// <para>Although file systems commonly are placed directly within partitions on a disk, in some /// cases a logical volume manager / logical disk manager may be used, to combine disk regions in multiple /// ways for data redundancy or other purposes.</para> /// </remarks> public sealed class VolumeManager #if !NETCORE : MarshalByRefObject #endif { private static List<LogicalVolumeFactory> s_logicalVolumeFactories; private readonly List<VirtualDisk> _disks; private bool _needScan; private Dictionary<string, PhysicalVolumeInfo> _physicalVolumes; private Dictionary<string, LogicalVolumeInfo> _logicalVolumes; private static readonly Assembly _coreAssembly = ReflectionHelper.GetAssembly(typeof(VolumeManager)); /// <summary> /// Initializes a new instance of the VolumeManager class. /// </summary> public VolumeManager() { _disks = new List<VirtualDisk>(); _physicalVolumes = new Dictionary<string, PhysicalVolumeInfo>(); _logicalVolumes = new Dictionary<string, LogicalVolumeInfo>(); } /// <summary> /// Initializes a new instance of the VolumeManager class. /// </summary> /// <param name="initialDisk">The initial disk to add.</param> public VolumeManager(VirtualDisk initialDisk) : this() { AddDisk(initialDisk); } /// <summary> /// Initializes a new instance of the VolumeManager class. /// </summary> /// <param name="initialDiskContent">Content of the initial disk to add.</param> public VolumeManager(Stream initialDiskContent) : this() { AddDisk(initialDiskContent); } private static List<LogicalVolumeFactory> LogicalVolumeFactories { get { if (s_logicalVolumeFactories == null) { List<LogicalVolumeFactory> factories = new List<LogicalVolumeFactory>(); factories.AddRange(GetLogicalVolumeFactories(_coreAssembly)); s_logicalVolumeFactories = factories; } return s_logicalVolumeFactories; } } private static IEnumerable<LogicalVolumeFactory> GetLogicalVolumeFactories(Assembly assembly) { foreach (Type type in assembly.GetTypes()) { foreach (LogicalVolumeFactoryAttribute attr in ReflectionHelper.GetCustomAttributes(type, typeof(LogicalVolumeFactoryAttribute), false)) { yield return (LogicalVolumeFactory)Activator.CreateInstance(type); } } } /// <summary> /// Register new LogicalVolumeFactories detected in an assembly /// </summary> /// <param name="assembly">The assembly to inspect</param> public static void RegisterLogicalVolumeFactory(Assembly assembly) { if (assembly == _coreAssembly) return; LogicalVolumeFactories.AddRange(GetLogicalVolumeFactories(assembly)); } /// <summary> /// Gets the physical volumes held on a disk. /// </summary> /// <param name="diskContent">The contents of the disk to inspect.</param> /// <returns>An array of volumes.</returns> /// <remarks> /// <para>By preference, use the form of this method that takes a disk parameter.</para> /// <para>If the disk isn't partitioned, this method returns the entire disk contents /// as a single volume.</para> /// </remarks> public static PhysicalVolumeInfo[] GetPhysicalVolumes(Stream diskContent) { return GetPhysicalVolumes(new Disk(diskContent, Ownership.None)); } /// <summary> /// Gets the physical volumes held on a disk. /// </summary> /// <param name="disk">The disk to inspect.</param> /// <returns>An array of volumes.</returns> /// <remarks>If the disk isn't partitioned, this method returns the entire disk contents /// as a single volume.</remarks> public static PhysicalVolumeInfo[] GetPhysicalVolumes(VirtualDisk disk) { return new VolumeManager(disk).GetPhysicalVolumes(); } /// <summary> /// Adds a disk to the volume manager. /// </summary> /// <param name="disk">The disk to add.</param> /// <returns>The GUID the volume manager will use to identify the disk.</returns> public string AddDisk(VirtualDisk disk) { _needScan = true; int ordinal = _disks.Count; _disks.Add(disk); return GetDiskId(ordinal); } /// <summary> /// Adds a disk to the volume manager. /// </summary> /// <param name="content">The contents of the disk to add.</param> /// <returns>The GUID the volume manager will use to identify the disk.</returns> public string AddDisk(Stream content) { return AddDisk(new Disk(content, Ownership.None)); } /// <summary> /// Gets the physical volumes from all disks added to this volume manager. /// </summary> /// <returns>An array of physical volumes.</returns> public PhysicalVolumeInfo[] GetPhysicalVolumes() { if (_needScan) { Scan(); } return new List<PhysicalVolumeInfo>(_physicalVolumes.Values).ToArray(); } /// <summary> /// Gets the logical volumes from all disks added to this volume manager. /// </summary> /// <returns>An array of logical volumes.</returns> public LogicalVolumeInfo[] GetLogicalVolumes() { if (_needScan) { Scan(); } return new List<LogicalVolumeInfo>(_logicalVolumes.Values).ToArray(); } /// <summary> /// Gets a particular volume, based on it's identity. /// </summary> /// <param name="identity">The volume's identity.</param> /// <returns>The volume information for the volume, or returns <c>null</c>.</returns> public VolumeInfo GetVolume(string identity) { if (_needScan) { Scan(); } PhysicalVolumeInfo pvi; if (_physicalVolumes.TryGetValue(identity, out pvi)) { return pvi; } LogicalVolumeInfo lvi; if (_logicalVolumes.TryGetValue(identity, out lvi)) { return lvi; } return null; } private static void MapPhysicalVolumes(IEnumerable<PhysicalVolumeInfo> physicalVols, Dictionary<string, LogicalVolumeInfo> result) { foreach (PhysicalVolumeInfo physicalVol in physicalVols) { LogicalVolumeInfo lvi = new LogicalVolumeInfo( physicalVol.PartitionIdentity, physicalVol, physicalVol.Open, physicalVol.Length, physicalVol.BiosType, LogicalVolumeStatus.Healthy); result.Add(lvi.Identity, lvi); } } /// <summary> /// Scans all of the disks for their physical and logical volumes. /// </summary> private void Scan() { Dictionary<string, PhysicalVolumeInfo> newPhysicalVolumes = ScanForPhysicalVolumes(); Dictionary<string, LogicalVolumeInfo> newLogicalVolumes = ScanForLogicalVolumes(newPhysicalVolumes.Values); _physicalVolumes = newPhysicalVolumes; _logicalVolumes = newLogicalVolumes; _needScan = false; } private Dictionary<string, LogicalVolumeInfo> ScanForLogicalVolumes(IEnumerable<PhysicalVolumeInfo> physicalVols) { List<PhysicalVolumeInfo> unhandledPhysical = new List<PhysicalVolumeInfo>(); Dictionary<string, LogicalVolumeInfo> result = new Dictionary<string, LogicalVolumeInfo>(); foreach (PhysicalVolumeInfo pvi in physicalVols) { bool handled = false; foreach (LogicalVolumeFactory volFactory in LogicalVolumeFactories) { if (volFactory.HandlesPhysicalVolume(pvi)) { handled = true; break; } } if (!handled) { unhandledPhysical.Add(pvi); } } MapPhysicalVolumes(unhandledPhysical, result); foreach (LogicalVolumeFactory volFactory in LogicalVolumeFactories) { volFactory.MapDisks(_disks, result); } return result; } private Dictionary<string, PhysicalVolumeInfo> ScanForPhysicalVolumes() { Dictionary<string, PhysicalVolumeInfo> result = new Dictionary<string, PhysicalVolumeInfo>(); // First scan physical volumes for (int i = 0; i < _disks.Count; ++i) { VirtualDisk disk = _disks[i]; string diskId = GetDiskId(i); if (PartitionTable.IsPartitioned(disk.Content)) { foreach (PartitionTable table in PartitionTable.GetPartitionTables(disk)) { foreach (PartitionInfo part in table.Partitions) { PhysicalVolumeInfo pvi = new PhysicalVolumeInfo(diskId, disk, part); result.Add(pvi.Identity, pvi); } } } else { PhysicalVolumeInfo pvi = new PhysicalVolumeInfo(diskId, disk); result.Add(pvi.Identity, pvi); } } return result; } private string GetDiskId(int ordinal) { VirtualDisk disk = _disks[ordinal]; if (disk.IsPartitioned) { Guid guid = disk.Partitions.DiskGuid; if (guid != Guid.Empty) { return "DG" + guid.ToString("B"); } } int sig = disk.Signature; if (sig != 0) { return "DS" + sig.ToString("X8", CultureInfo.InvariantCulture); } return "DO" + ordinal; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.UI.WebControls.Style.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.UI.WebControls { public partial class Style : System.ComponentModel.Component, System.Web.UI.IStateManager { #region Methods and constructors public virtual new void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer, WebControl owner) { } public void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer) { } public virtual new void CopyFrom(System.Web.UI.WebControls.Style s) { } protected virtual new void FillStyleAttributes(System.Web.UI.CssStyleCollection attributes, System.Web.UI.IUrlResolutionService urlResolver) { } public System.Web.UI.CssStyleCollection GetStyleAttributes(System.Web.UI.IUrlResolutionService urlResolver) { return default(System.Web.UI.CssStyleCollection); } protected internal void LoadViewState(Object state) { } public virtual new void MergeWith(System.Web.UI.WebControls.Style s) { } public virtual new void Reset() { } protected internal virtual new Object SaveViewState() { return default(Object); } protected internal virtual new void SetBit(int bit) { } public void SetDirty() { } public Style() { } public Style(System.Web.UI.StateBag bag) { } void System.Web.UI.IStateManager.LoadViewState(Object state) { } Object System.Web.UI.IStateManager.SaveViewState() { return default(Object); } void System.Web.UI.IStateManager.TrackViewState() { } protected internal virtual new void TrackViewState() { } #endregion #region Properties and indexers public System.Drawing.Color BackColor { get { return default(System.Drawing.Color); } set { } } public System.Drawing.Color BorderColor { get { return default(System.Drawing.Color); } set { } } public BorderStyle BorderStyle { get { return default(BorderStyle); } set { } } public Unit BorderWidth { get { return default(Unit); } set { } } public string CssClass { get { return default(string); } set { } } public FontInfo Font { get { return default(FontInfo); } } public System.Drawing.Color ForeColor { get { return default(System.Drawing.Color); } set { } } public Unit Height { get { return default(Unit); } set { } } public virtual new bool IsEmpty { get { return default(bool); } } protected bool IsTrackingViewState { get { return default(bool); } } public string RegisteredCssClass { get { return default(string); } } bool System.Web.UI.IStateManager.IsTrackingViewState { get { return default(bool); } } internal protected System.Web.UI.StateBag ViewState { get { return default(System.Web.UI.StateBag); } } public Unit Width { get { return default(Unit); } set { } } #endregion } }
using System; using System.Drawing; using FastQuant; using FastQuant.Indicators; using System.Linq; namespace Samples.ChannelBreakout { public class MyStrategy : InstrumentStrategy { private double highest; private double lowest; private Group barsGroup; private Group fillGroup; private Group equityGroup; private Group highestGroup; private Group lowestGroup; [Parameter] public double AllocationPerInstrument = 100000; [Parameter] double Qty = 100; [Parameter] int Length = 8; public MyStrategy(Framework framework, string name) : base(framework, name) { } protected override void OnStrategyStart() { Portfolio.Account.Deposit(AllocationPerInstrument, CurrencyId.USD, "Initial allocation"); AddGroups(); } protected override void OnBar(Instrument instrument, Bar bar) { // Add bar to bar series. Bars.Add(bar); // Add bar to group. Log(bar, barsGroup); // Add highest value to group. if (highest != 0) Log(highest, highestGroup); // Add lowest value to group. if (lowest != 0) Log(lowest, lowestGroup); // Calculate performance. Portfolio.Performance.Update(); // Add equity to group. Log(Portfolio.Value, equityGroup); // Check strategy logic. if (highest != 0 && lowest != 0) { if (!HasPosition(instrument)) { // Enter long/short. if (bar.Close > highest) { Order enterOrder = BuyOrder(Instrument, Qty, "Enter Long"); Send(enterOrder); } else if (bar.Close < lowest) { Order enterOrder = SellOrder(Instrument, Qty, "Enter Short"); Send(enterOrder); } } else { // Reverse to long/short. if (Position.Side == PositionSide.Long && bar.Close < lowest) { Order reverseOrder = SellOrder(Instrument, Math.Abs(Position.Amount) + Qty, "Reverse to Short"); Send(reverseOrder); } else if (Position.Side == PositionSide.Short && bar.Close > highest) { Order reverseOrder = BuyOrder(Instrument, Math.Abs(Position.Amount) + Qty, "Reverse to Long"); Send(reverseOrder); } } } // Calculate channel's highest/lowest values. if (Bars.Count > Length) { highest = Bars.HighestHigh(Length); lowest = Bars.LowestLow(Length); } } protected override void OnFill(Fill fill) { // Add fill to group. Log(fill, fillGroup); } private void AddGroups() { // Create bars group. barsGroup = new Group("Bars"); barsGroup.Add("Pad", DataObjectType.String, 0); barsGroup.Add("SelectorKey", Instrument.Symbol); // Create fills group. fillGroup = new Group("Fills"); fillGroup.Add("Pad", 0); fillGroup.Add("SelectorKey", Instrument.Symbol); // Create equity group. equityGroup = new Group("Equity"); equityGroup.Add("Pad", 1); equityGroup.Add("SelectorKey", Instrument.Symbol); // Create channel's highest values group. highestGroup = new Group("Highest"); highestGroup.Add("Pad", 0); highestGroup.Add("SelectorKey", Instrument.Symbol); highestGroup.Add("Color", Color.Green); // Create channel's lowest values group. lowestGroup = new Group("Lowest"); lowestGroup.Add("Pad", 0); lowestGroup.Add("SelectorKey", Instrument.Symbol); lowestGroup.Add("Color", Color.Red); // Add groups to manager. GroupManager.Add(barsGroup); GroupManager.Add(fillGroup); GroupManager.Add(equityGroup); GroupManager.Add(highestGroup); GroupManager.Add(lowestGroup); } } public class Backtest : Scenario { private long barSize = 300; public Backtest(Framework framework) : base(framework) { } public override void Run() { Instrument instrument1 = InstrumentManager.Instruments["AAPL"]; Instrument instrument2 = InstrumentManager.Instruments["MSFT"]; strategy = new MyStrategy(framework, "ChannelBreakout"); strategy.AddInstrument(instrument1); strategy.AddInstrument(instrument2); DataSimulator.DateTime1 = new DateTime(2013, 01, 01); DataSimulator.DateTime2 = new DateTime(2013, 12, 31); BarFactory.Add(instrument1, BarType.Time, barSize); BarFactory.Add(instrument2, BarType.Time, barSize); StartStrategy(); } } public class Realtime : Scenario { private long barSize = 300; public Realtime(Framework framework) : base(framework) { } public override void Run() { Instrument instrument1 = InstrumentManager.Instruments["AAPL"]; Instrument instrument2 = InstrumentManager.Instruments["MSFT"]; strategy = new MyStrategy(framework, "BollingerBands"); strategy.AddInstrument(instrument1); strategy.AddInstrument(instrument2); strategy.DataProvider = ProviderManager.GetDataProvider("QuantRouter"); strategy.ExecutionProvider = ProviderManager.GetExecutionProvider("QuantRouter"); BarFactory.Add(instrument1, BarType.Time, barSize); BarFactory.Add(instrument2, BarType.Time, barSize); StartStrategy(); } } class Program { static void Main(string[] args) { var scenario = args.Contains("--realtime") ? (Scenario)new Realtime(Framework.Current) : (Scenario)new Backtest(Framework.Current); scenario.Run(); } } }
using Newtonsoft.Json.Linq; using System.Net.Http; using ShopifySharp.Filters; using System.Collections.Generic; using System.Threading.Tasks; using ShopifySharp.Infrastructure; namespace ShopifySharp { /// <summary> /// A service for manipulating Shopify metafields. /// </summary> public class MetaFieldService : ShopifyService { /// <summary> /// Creates a new instance of <see cref="MetaFieldService" />. /// </summary> /// <param name="myShopifyUrl">The shop's *.myshopify.com URL.</param> /// <param name="shopAccessToken">An API access token for the shop.</param> public MetaFieldService(string myShopifyUrl, string shopAccessToken) : base(myShopifyUrl, shopAccessToken) { } private async Task<int> _CountAsync(string path, MetaFieldFilter filter = null) { var req = PrepareRequest(path); if (filter != null) { req.QueryParams.AddRange(filter.ToParameters()); } return await ExecuteRequestAsync<int>(req, HttpMethod.Get, rootElement: "count"); } /// <summary> /// Gets a count of the metafields on the shop itself. /// </summary> /// <param name="filter">Options to filter the results.</param> public virtual async Task<int> CountAsync(MetaFieldFilter filter = null) { return await _CountAsync("metafields/count.json", filter); } /// <summary> /// Gets a count of the metafields for the given entity type and filter options. /// </summary> /// <param name="resourceType">The type of shopify resource to obtain metafields for. This could be variants, products, orders, customers, custom_collections.</param> /// <param name="resourceId">The Id for the resource type.</param> /// <param name="filter">Options to filter the results.</param> public virtual async Task<int> CountAsync(long resourceId, string resourceType, MetaFieldFilter filter = null) { return await _CountAsync($"{resourceType}/{resourceId}/metafields/count.json", filter); } /// <summary> /// Gets a count of the metafields for the given entity type and filter options. /// </summary> /// <param name="resourceType">The type of shopify resource to obtain metafields for. This could be variants, products, orders, customers, custom_collections.</param> /// <param name="resourceId">The Id for the resource type.</param> /// <param name="parentResourceType">The type of shopify parent resource to obtain metafields for. This could be blogs, products.</param> /// <param name="parentResourceId">The Id for the resource type.</param> /// <param name="filter">Options to filter the results.</param> public virtual async Task<int> CountAsync(long resourceId, string resourceType, long parentResourceId, string parentResourceType, MetaFieldFilter filter = null) { return await _CountAsync($"{parentResourceType}/{parentResourceId}/{resourceType}/{resourceId}/metafields/count.json", filter); } private async Task<IEnumerable<MetaField>> _ListAsync(string path, MetaFieldFilter filter = null) { var req = PrepareRequest(path); if (filter != null) { req.QueryParams.AddRange(filter.ToParameters()); } return await ExecuteRequestAsync<List<MetaField>>(req, HttpMethod.Get, rootElement: "metafields"); } /// <summary> /// Gets a list of the metafields for the shop itself. /// </summary> /// <param name="filter">Options to filter the results.</param> public virtual async Task<IEnumerable<MetaField>> ListAsync(MetaFieldFilter filter = null) { return await _ListAsync("metafields.json", filter); } /// <summary> /// Gets a list of the metafields for the given entity type and filter options. /// </summary> /// <param name="resourceType">The type of shopify resource to obtain metafields for. This could be variants, products, orders, customers, custom_collections.</param> /// <param name="resourceId">The Id for the resource type.</param> /// <param name="filter">Options to filter the results.</param> public virtual async Task<IEnumerable<MetaField>> ListAsync(long resourceId, string resourceType, MetaFieldFilter filter = null) { return await _ListAsync($"{resourceType}/{resourceId}/metafields.json", filter); } /// <summary> /// Gets a list of the metafields for the given entity type and filter options. /// </summary> /// <param name="parentResourceType">The type of shopify parentresource to obtain metafields for. This could be blogs, products.</param> /// <param name="parentResourceId">The Id for the parent resource type.</param> /// <param name="resourceType">The type of shopify resource to obtain metafields for. This could be variants, products, orders, customers, custom_collections.</param> /// <param name="resourceId">The Id for the resource type.</param> /// <param name="filter">Options to filter the results.</param> public virtual async Task<IEnumerable<MetaField>> ListAsync(long resourceId, string resourceType, long parentResourceId, string parentResourceType, MetaFieldFilter filter = null) { return await _ListAsync($"{parentResourceType}/{parentResourceId}/{resourceType}/{resourceId}/metafields.json", filter); } /// <summary> /// Retrieves the metafield with the given id. /// </summary> /// <param name="metafieldId">The id of the metafield to retrieve.</param> /// <param name="fields">A comma-separated list of fields to return.</param> public virtual async Task<MetaField> GetAsync(long metafieldId, string fields = null) { var req = PrepareRequest($"metafields/{metafieldId}.json"); if (!string.IsNullOrEmpty(fields)) { req.QueryParams.Add("fields", fields); } return await ExecuteRequestAsync<MetaField>(req, HttpMethod.Get, rootElement: "metafield"); } /// <summary> /// Creates a new metafield on the shop itself. /// </summary> /// <param name="metafield">A new metafield. Id should be set to null.</param> public virtual async Task<MetaField> CreateAsync(MetaField metafield) { var req = PrepareRequest("metafields.json"); var content = new JsonContent(new { metafield = metafield }); return await ExecuteRequestAsync<MetaField>(req, HttpMethod.Post, content, "metafield"); } /// <summary> /// Creates a new metafield on the given entity. /// </summary> /// <param name="metafield">A new metafield. Id should be set to null.</param> /// <param name="resourceId">The Id of the resource the metafield will be associated with. This can be variants, products, orders, customers, custom_collections, etc.</param> /// <param name="resourceType">The resource type the metaifeld will be associated with. This can be variants, products, orders, customers, custom_collections, etc.</param> /// <param name="parentResourceId">The Id of the parent resource the metafield will be associated with. This can be blogs, products.</param> /// <param name="parentResourceType">The resource type the metaifeld will be associated with. This can be articles, variants.</param> public virtual async Task<MetaField> CreateAsync(MetaField metafield, long resourceId, string resourceType, long parentResourceId, string parentResourceType) { var req = PrepareRequest($"{parentResourceType}/{parentResourceId}/{resourceType}/{resourceId}/metafields.json"); var content = new JsonContent(new { metafield = metafield }); return await ExecuteRequestAsync<MetaField>(req, HttpMethod.Post, content, "metafield"); } /// <summary> /// Creates a new metafield on the given entity. /// </summary> /// <param name="metafield">A new metafield. Id should be set to null.</param> /// <param name="resourceId">The Id of the resource the metafield will be associated with. This can be variants, products, orders, customers, custom_collections, etc.</param> /// <param name="resourceType">The resource type the metaifeld will be associated with. This can be variants, products, orders, customers, custom_collections, etc.</param> public virtual async Task<MetaField> CreateAsync(MetaField metafield, long resourceId, string resourceType) { var req = PrepareRequest($"{resourceType}/{resourceId}/metafields.json"); var content = new JsonContent(new { metafield = metafield }); return await ExecuteRequestAsync<MetaField>(req, HttpMethod.Post, content, "metafield"); } /// <summary> /// Updates the given metafield. /// </summary> /// <param name="metafieldId">Id of the object being updated.</param> /// <param name="metafield">The metafield to update.</param> public virtual async Task<MetaField> UpdateAsync(long metafieldId, MetaField metafield) { var req = PrepareRequest($"metafields/{metafieldId}.json"); var content = new JsonContent(new { metafield = metafield }); return await ExecuteRequestAsync<MetaField>(req, HttpMethod.Put, content, "metafield"); } /// <summary> /// Deletes a metafield with the given Id. /// </summary> /// <param name="metafieldId">The metafield object's Id.</param> public virtual async Task DeleteAsync(long metafieldId) { var req = PrepareRequest($"metafields/{metafieldId}.json"); await ExecuteRequestAsync(req, HttpMethod.Delete); } } }
// *********************************************************************** // Copyright (c) 2011 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using NUnit.Framework.Constraints; using NUnit.Framework.Internal; namespace NUnit.Framework { /// <summary> /// The Assert class contains a collection of static methods that /// implement the most common assertions used in NUnit. /// </summary> public partial class Assert { #region Assert.That #region Boolean /// <summary> /// Asserts that a condition is true. If the condition is false the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> /// <param name="message">The message to display if the condition is false</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void That(bool condition, string message, params object[] args) { Assert.That(condition, Is.True, message, args); } /// <summary> /// Asserts that a condition is true. If the condition is false the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> public static void That(bool condition) { Assert.That(condition, Is.True, null, null); } #if !NET_2_0 /// <summary> /// Asserts that a condition is true. If the condition is false the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">The evaluated condition</param> /// <param name="getExceptionMessage">A function to build the message included with the Exception</param> public static void That(bool condition, Func<string> getExceptionMessage) { Assert.That(condition, Is.True, getExceptionMessage); } #endif #endregion #region Lambda returning Boolean #if !NET_2_0 /// <summary> /// Asserts that a condition is true. If the condition is false the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">A lambda that returns a Boolean</param> /// <param name="message">The message to display if the condition is false</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void That(Func<bool> condition, string message, params object[] args) { Assert.That(condition.Invoke(), Is.True, message, args); } /// <summary> /// Asserts that a condition is true. If the condition is false the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">A lambda that returns a Boolean</param> public static void That(Func<bool> condition) { Assert.That(condition.Invoke(), Is.True, null, null); } /// <summary> /// Asserts that a condition is true. If the condition is false the method throws /// an <see cref="AssertionException"/>. /// </summary> /// <param name="condition">A lambda that returns a Boolean</param> /// <param name="getExceptionMessage">A function to build the message included with the Exception</param> public static void That(Func<bool> condition, Func<string> getExceptionMessage) { Assert.That(condition.Invoke(), Is.True, getExceptionMessage); } #endif #endregion #region ActualValueDelegate /// <summary> /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and throwing an assertion exception on failure. /// </summary> /// <typeparam name="TActual">The Type being compared.</typeparam> /// <param name="del">An ActualValueDelegate returning the value to be tested</param> /// <param name="expr">A Constraint expression to be applied</param> public static void That<TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr) { Assert.That(del, expr.Resolve(), null, null); } /// <summary> /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and throwing an assertion exception on failure. /// </summary> /// <typeparam name="TActual">The Type being compared.</typeparam> /// <param name="del">An ActualValueDelegate returning the value to be tested</param> /// <param name="expr">A Constraint expression to be applied</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void That<TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr, string message, params object[] args) { var constraint = expr.Resolve(); IncrementAssertCount(); var result = constraint.ApplyTo(del); if (!result.IsSuccess) ReportFailure(result, message, args); } #if !NET_2_0 /// <summary> /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and throwing an assertion exception on failure. /// </summary> /// <typeparam name="TActual">The Type being compared.</typeparam> /// <param name="del">An ActualValueDelegate returning the value to be tested</param> /// <param name="expr">A Constraint expression to be applied</param> /// <param name="getExceptionMessage">A function to build the message included with the Exception</param> public static void That<TActual>( ActualValueDelegate<TActual> del, IResolveConstraint expr, Func<string> getExceptionMessage) { var constraint = expr.Resolve(); IncrementAssertCount(); var result = constraint.ApplyTo(del); if (!result.IsSuccess) ReportFailure(result, getExceptionMessage()); } #endif #endregion #region TestDelegate /// <summary> /// Asserts that the code represented by a delegate throws an exception /// that satisfies the constraint provided. /// </summary> /// <param name="code">A TestDelegate to be executed</param> /// <param name="constraint">A ThrowsConstraint used in the test</param> public static void That(TestDelegate code, IResolveConstraint constraint) { Assert.That(code, constraint, null, null); } /// <summary> /// Asserts that the code represented by a delegate throws an exception /// that satisfies the constraint provided. /// </summary> /// <param name="code">A TestDelegate to be executed</param> /// <param name="constraint">A ThrowsConstraint used in the test</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void That(TestDelegate code, IResolveConstraint constraint, string message, params object[] args) { Assert.That((object)code, constraint, message, args); } #if !NET_2_0 /// <summary> /// Asserts that the code represented by a delegate throws an exception /// that satisfies the constraint provided. /// </summary> /// <param name="code">A TestDelegate to be executed</param> /// <param name="constraint">A ThrowsConstraint used in the test</param> /// <param name="getExceptionMessage">A function to build the message included with the Exception</param> public static void That(TestDelegate code, IResolveConstraint constraint, Func<string> getExceptionMessage) { Assert.That((object)code, constraint, getExceptionMessage); } #endif #endregion #endregion #region Assert.That<TActual> /// <summary> /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and throwing an assertion exception on failure. /// </summary> /// <typeparam name="TActual">The Type being compared.</typeparam> /// <param name="actual">The actual value to test</param> /// <param name="expression">A Constraint to be applied</param> public static void That<TActual>(TActual actual, IResolveConstraint expression) { Assert.That(actual, expression, null, null); } /// <summary> /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and throwing an assertion exception on failure. /// </summary> /// <typeparam name="TActual">The Type being compared.</typeparam> /// <param name="actual">The actual value to test</param> /// <param name="expression">A Constraint expression to be applied</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void That<TActual>(TActual actual, IResolveConstraint expression, string message, params object[] args) { var constraint = expression.Resolve(); IncrementAssertCount(); var result = constraint.ApplyTo(actual); if (!result.IsSuccess) ReportFailure(result, message, args); } #if !NET_2_0 /// <summary> /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and throwing an assertion exception on failure. /// </summary> /// <typeparam name="TActual">The Type being compared.</typeparam> /// <param name="actual">The actual value to test</param> /// <param name="expression">A Constraint expression to be applied</param> /// <param name="getExceptionMessage">A function to build the message included with the Exception</param> public static void That<TActual>( TActual actual, IResolveConstraint expression, Func<string> getExceptionMessage) { var constraint = expression.Resolve(); IncrementAssertCount(); var result = constraint.ApplyTo(actual); if (!result.IsSuccess) ReportFailure(result, getExceptionMessage()); } #endif #endregion #region Assert.ByVal /// <summary> /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and throwing an assertion exception on failure. /// Used as a synonym for That in rare cases where a private setter /// causes a Visual Basic compilation error. /// </summary> /// <param name="actual">The actual value to test</param> /// <param name="expression">A Constraint to be applied</param> public static void ByVal(object actual, IResolveConstraint expression) { Assert.That(actual, expression, null, null); } /// <summary> /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and throwing an assertion exception on failure. /// Used as a synonym for That in rare cases where a private setter /// causes a Visual Basic compilation error. /// </summary> /// <remarks> /// This method is provided for use by VB developers needing to test /// the value of properties with private setters. /// </remarks> /// <param name="actual">The actual value to test</param> /// <param name="expression">A Constraint expression to be applied</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void ByVal(object actual, IResolveConstraint expression, string message, params object[] args) { Assert.That(actual, expression, message, args); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * 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 CompareGreaterThanInt32() { var test = new SimpleBinaryOpTest__CompareGreaterThanInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local 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__CompareGreaterThanInt32 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Int32); private const int Op2ElementCount = VectorSize / sizeof(Int32); private const int RetElementCount = VectorSize / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable; static SimpleBinaryOpTest__CompareGreaterThanInt32() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__CompareGreaterThanInt32() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.CompareGreaterThan( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.CompareGreaterThan( Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.CompareGreaterThan( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareGreaterThan), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareGreaterThan), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareGreaterThan), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.CompareGreaterThan( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = Sse2.CompareGreaterThan(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareGreaterThan(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareGreaterThan(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__CompareGreaterThanInt32(); var result = Sse2.CompareGreaterThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.CompareGreaterThan(_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(Vector128<Int32> left, Vector128<Int32> right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, 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 = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { if (result[0] != ((left[0] > right[0]) ? unchecked((int)(-1)) : 0)) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] > right[i]) ? unchecked((int)(-1)) : 0)) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.CompareGreaterThan)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
/* MIT License Copyright (c) 2017 Saied Zarrinmehr Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Input; using SpatialAnalysis.Geometry; using SpatialAnalysis.CellularEnvironment; using System.Windows.Shapes; using System.Windows.Threading; using System.Threading; using System.Windows.Media.Media3D; using SpatialAnalysis.Data; using SpatialAnalysis.Events; using System.Windows.Data; using SpatialAnalysis.Miscellaneous; namespace SpatialAnalysis.Agents.OptionalScenario.Visualization { /// <summary> /// This class controls the animation control panel, visualizes the 2D animation, and implements the interaction logic among user, the 2d scene and the control panel. For protection its members are private. /// </summary> /// <seealso cref="System.Windows.Controls.Canvas" /> internal class OptionalScenarioAnimationVisualHost : Canvas { private Line _lineToTarget { get; set; } private Path _destinationLines { get; set; } private StreamGeometry _destinationLinesGeometry { get; set; } private bool _animationInProgress; private VisualAgentOptionalScenario agent { get; set; } private OSMDocument _host; private MenuItem _calculateScapeRoutesMenu { get; set; } private MenuItem _getWalkingTrailDataMenu { get; set; } private MenuItem _captureEventMenu { get; set; } private MenuItem _trainingMenu { get; set; } public MenuItem _animation_Menu { get; set; } private Line _closestEdge { get; set; } private Line _repulsionTrajectoryLine { get; set; } private RealTimeFreeNavigationControler _settings { get; set; } /// <summary> /// Initializes a new instance of the <see cref="OptionalScenarioAnimationVisualHost"/> class. /// </summary> public OptionalScenarioAnimationVisualHost() { this._animation_Menu = new MenuItem { Header="Free Navigation Control Panel", IsEnabled=false, }; this._animation_Menu.Click += animation_Menu_Click; this._getWalkingTrailDataMenu = new MenuItem() { Header="Simulate", IsEnabled = false, }; this._getWalkingTrailDataMenu.Click += new RoutedEventHandler(_getWalkingTrailDataMenu_Click); this._captureEventMenu = new MenuItem { Header = "Capture Events" }; this._captureEventMenu.Click += new RoutedEventHandler(_captureEventMenu_Click); this._trainingMenu = new MenuItem { Header = "Train Agent" }; this._trainingMenu.Click += new RoutedEventHandler(_trainingMenu_Click); } void _captureEventMenu_Click(object sender, RoutedEventArgs e) { EventCapturingInterface eventCapturingInterface = new EventCapturingInterface(this._host, EvaluationEventType.Optional); eventCapturingInterface.Owner = this._host; eventCapturingInterface.ShowDialog(); eventCapturingInterface = null; } WalkingTrailData _walkingTrailDataComputer { get; set; } void _getWalkingTrailDataMenu_Click(object sender, RoutedEventArgs e) { this._walkingTrailDataComputer = new WalkingTrailData(); foreach (SimulationResult item in this._host.AllSimulationResults.Values) { this._walkingTrailDataComputer.dataNames.Items.Add(item.Name); } foreach (ISpatialData item in this._host.AllOccupancyEvent.Values) { this._walkingTrailDataComputer.dataNames.Items.Add(item.Name); } foreach (ISpatialData item in this._host.AllActivities.Values) { this._walkingTrailDataComputer.dataNames.Items.Add(item.Name); } foreach (ISpatialData item in this._host.cellularFloor.AllSpatialDataFields.Values) { this._walkingTrailDataComputer.dataNames.Items.Add(item.Name); } this._walkingTrailDataComputer._getWalkingTrailBtn.Click += _getWalkingTrailBtn_Click; this._walkingTrailDataComputer.Owner = this._host; this._walkingTrailDataComputer.ShowDialog(); } void _getWalkingTrailBtn_Click(object sender, RoutedEventArgs e) { this._walkingTrailDataComputer._getWalkingTrailBtn.Click -= _getWalkingTrailBtn_Click; string name = string.Empty; if (string.IsNullOrEmpty(this._walkingTrailDataComputer._spatialDataName.Text)) { MessageBox.Show("Enter a name for the 'Spatial Data Field'!"); return; } else { if (this._host.ContainsSpatialData(name)) { MessageBox.Show("'A Data Field' with the same name already exists! \nTry a new name."); return; } name = this._walkingTrailDataComputer._spatialDataName.Text; } double h, duration; if (!double.TryParse(this._walkingTrailDataComputer._timeStep.Text, out h) || !double.TryParse(this._walkingTrailDataComputer._timeDuration.Text, out duration)) { MessageBox.Show("Invalid input for 'time step' and/or 'duration'"); return; } if (h <= 0 || duration <= 0) { MessageBox.Show("'Time step' and/or 'duration' must be larger than zero!"); return; } this._walkingTrailDataComputer.Close(); bool notification = this._walkingTrailDataComputer._notify.IsChecked.Value; var simulator = new OptionalScenarioSimulation(this._host, h, duration); Thread simulationThread = new Thread( () => simulator.Simulate(name, notification) ); simulationThread.Start(); } void animation_Menu_Click(object sender, RoutedEventArgs e) { this._settings = new RealTimeFreeNavigationControler(); { double t_ = double.Parse(this._settings._strokeThicknessMax.Text); this._settings._strokeThicknessMax.Text = this._host.UnitConvertor.Convert(t_).ToString("0.000"); this._settings._strokeThickness.Value *= this._host.UnitConvertor.Convert(1.0d, 4); } //set events this._settings._addAgent.Click += _addAgent_Click; this._settings.Closing += _settings_Closing; //show the dialog this._settings.Owner = this._host; this._settings.ShowDialog(); } void _settings_Closing(object sender, System.ComponentModel.CancelEventArgs e) { this.stopAnimation(); if (this.agent != null) { this.cleanUpAgent(); } //set events this._settings._addAgent.Click -= _addAgent_Click; this.Children.Clear(); } void _addAgent_Click(object sender, RoutedEventArgs e) { //events for locating the agent this._settings._addAgent.Click -= _addAgent_Click; this._settings._addAgent.IsEnabled = false; this._settings._clearAgent.Click += _clearAgent_Click; #region Agent Creation this.agent = new VisualAgentOptionalScenario { StrokeThickness = this._settings._strokeThickness.Value, Stroke = VisualAgentOptionalScenario.OutsideRange, Fill = VisualAgentOptionalScenario.OutsideRange, VelocityMagnitude = this._settings._velocity.Value, ShowVisibilityCone = this._settings._showVisibiityAngle.IsChecked.Value, ShowSafetyBuffer = this._settings._showSafetyBuffer.IsChecked.Value, BodySize = this._settings._bodySize.Value, VisibilityAngle = this._settings._viewAngle.Value * Math.PI / 180.0d, AngularVelocity = this._settings._angularVelocity.Value, DecisionMakingPeriodLambdaFactor = this._settings._decisionMakingPeriod.Value, Destination = null, DesirabilityDistributionLambdaFactor = this._settings._desirabilityWeight.Value, AngleDistributionLambdaFactor=this._settings._angleWeight.Value, DecisionMakingPeriodDistribution = new MathNet.Numerics.Distributions.Exponential(1.0d/this._settings._decisionMakingPeriod.Value), BarrierRepulsionRange = this._settings._barrierRepulsionRange.Value, RepulsionChangeRate = this._settings._repulsionChangeRate.Value, AccelerationMagnitude = this._settings._accelerationMagnitude.Value, }; //I am calling this from outside to initiate the DecisionMakingPeriodDistribution property Canvas.SetZIndex(this.agent, 100); #endregion this.Children.Add(this.agent); #region Agent Events' Registration this._settings._strokeThickness.ValueChanged += _strokeThickness_ValueChanged; this._settings._viewAngle.ValueChanged += _viewAngle_ValueChanged; this._host.FloorScene.MouseMove += scene_AgentPositionSet; this._host.FloorScene.MouseLeftButtonDown += scene_AgentPositionSetTerminated; this._settings._velocity.ValueChanged += _velocity_ValueChanged; this._settings._accelerationMagnitude.ValueChanged += _accelerationMagnitude_ValueChanged; this._settings._bodySize.ValueChanged += _scale_ValueChanged; this._settings._angularVelocity.ValueChanged += _angularVelocity_ValueChanged; this._settings._showVisibiityAngle.Checked += _showVisibilityAngle_Checked; this._settings._showVisibiityAngle.Unchecked += _showVisibilityAngle_Unchecked; this._settings._showSafetyBuffer.Checked += _showSafetyBuffer_Checked; this._settings._showSafetyBuffer.Unchecked += _showSafetyBuffer_Unchecked; this._settings._showVisibeDestinations.Checked += _showVisibleDestinations_Checked; this._settings._showVisibeDestinations.Unchecked += _showVisibleDestinations_Unchecked; this._settings._decisionMakingPeriod.ValueChanged += _decisionMakingPeriod_ValueChanged; this._settings._captureVisualEvents.Checked += _captureVisualEvents_Checked; this._settings._captureVisualEvents.Unchecked += _captureVisualEvents_Unchecked; this._settings._showClosestBarrier.Checked += _showClosestBarrier_Checked; this._settings._showClosestBarrier.Unchecked += _showClosestBarrier_Unchecked; this._settings._angleWeight.ValueChanged += _angleWeight_ValueChanged; this._settings._desirabilityWeight.ValueChanged += _desirabilityWeight_ValueChanged; this._settings._barrierRepulsionRange.ValueChanged += _barrierRepulsionRange_ValueChanged; this._settings._repulsionChangeRate.ValueChanged += _repulsionChangeRate_ValueChanged; this._settings._showRepulsionTrajectory.Checked += this._showRepulsionTrajectory_Checked; this._settings._showRepulsionTrajectory.Unchecked += this._showRepulsionTrajectory_Unchecked; this._settings._barrierFriction.ValueChanged += _barrierFriction_ValueChanged; this._settings._bodyElasticity.ValueChanged += _bodyElasticity_ValueChanged; #endregion this._settings.Hide(); } void _bodyElasticity_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { this.agent.Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.agent.SetValue(VisualAgentOptionalScenario.BodyElasticityProperty, e.NewValue); } , null); } void _barrierFriction_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { this.agent.Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.agent.SetValue(VisualAgentOptionalScenario.BarrierFrictionProperty, e.NewValue); } , null); } void _showRepulsionTrajectory_Unchecked(object sender, RoutedEventArgs e) { this.agent.ShowRepulsionTrajectory -= this.showRepulsionTrajectory; if (this._repulsionTrajectoryLine != null) { int index = this.Children.IndexOf(this._repulsionTrajectoryLine); if (index != -1) { this.Children.RemoveAt(index); } this._repulsionTrajectoryLine = null; } } private void showRepulsionTrajectory() { if (this._repulsionTrajectoryLine != null && this.agent.EdgeCollisionState != null) { this._repulsionTrajectoryLine.Visibility = System.Windows.Visibility.Visible; this._repulsionTrajectoryLine.X1 = this.agent.CurrentState.Location.U; this._repulsionTrajectoryLine.Y1 = this.agent.CurrentState.Location.V; this._repulsionTrajectoryLine.X2 = this.agent.EdgeCollisionState.ClosestPointOnBarrier.U; this._repulsionTrajectoryLine.Y2 = this.agent.EdgeCollisionState.ClosestPointOnBarrier.V; } else { this._repulsionTrajectoryLine.Visibility = System.Windows.Visibility.Hidden; } } void _showRepulsionTrajectory_Checked(object sender, RoutedEventArgs e) { if (this._repulsionTrajectoryLine == null) { this._repulsionTrajectoryLine = new Line() { Stroke = Brushes.DarkTurquoise, StrokeThickness = this._settings._strokeThickness.Value * 1.5d, }; this.Children.Add(this._repulsionTrajectoryLine); } this.agent.ShowRepulsionTrajectory += this.showRepulsionTrajectory; } void _showClosestBarrier_Unchecked(object sender, RoutedEventArgs e) { this.agent.ShowClosestBarrier -= this.showClosestBarrier; if (this._closestEdge != null) { int index = this.Children.IndexOf(this._closestEdge); if (index != -1) { this.Children.RemoveAt(index); } this._closestEdge = null; } } void _showClosestBarrier_Checked(object sender, RoutedEventArgs e) { if (this._closestEdge == null) { this._closestEdge = new Line() { Stroke = Brushes.DarkSalmon, StrokeThickness = this._settings._strokeThickness.Value * 3, }; this.Children.Add(this._closestEdge); } this.agent.ShowClosestBarrier += this.showClosestBarrier; } private void showClosestBarrier() { if (this.agent.EdgeCollisionState.Barrrier != null) { this._closestEdge.Visibility = System.Windows.Visibility.Visible; this._closestEdge.X1 = this.agent.EdgeCollisionState.Barrrier.Start.U; this._closestEdge.X2 = this.agent.EdgeCollisionState.Barrrier.End.U; this._closestEdge.Y1 = this.agent.EdgeCollisionState.Barrrier.Start.V; this._closestEdge.Y2 = this.agent.EdgeCollisionState.Barrrier.End.V; } else { this._closestEdge.Visibility = System.Windows.Visibility.Hidden; } } void _accelerationMagnitude_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { this.agent.Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.agent.SetValue(VisualAgentOptionalScenario.AccelerationMagnitudeProperty, e.NewValue); } , null); } void _repulsionChangeRate_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { this.agent.Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.agent.SetValue(VisualAgentOptionalScenario.RepulsionChangeRateProperty, e.NewValue); } , null); } void _barrierRepulsionRange_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { this.agent.Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.agent.SetValue(VisualAgentOptionalScenario.BarrierRepulsionRangeProperty, e.NewValue); } , null); } void _desirabilityWeight_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { this.agent.Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.agent.SetValue(VisualAgentOptionalScenario.DesirabilityDistributionLambdaFactorProperty, e.NewValue); } , null); } void _angleWeight_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { this.agent.Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.agent.SetValue(VisualAgentOptionalScenario.AngleDistributionLambdaFactorProperty, e.NewValue); } , null); } void _captureVisualEvents_Unchecked(object sender, RoutedEventArgs e) { this.agent.RaiseVisualEvent -= this.raiseVisualEvent; if (this._lineToTarget!= null) { try { this.Children.Remove(this._lineToTarget); this._lineToTarget = null; } catch (Exception) { } } } void _captureVisualEvents_Checked(object sender, RoutedEventArgs e) { this.agent.RaiseVisualEvent += this.raiseVisualEvent; } private void raiseVisualEvent() { if (!VisibilityTarget.ReferenceEquals(this._host.VisualEventSettings, null)) { UV visualTarget = this._host.VisualEventSettings.TargetVisibilityTest(this.agent.CurrentState, this.agent.VisibilityCosineFactor, this._host.cellularFloor); if (visualTarget!= null) { if (this._lineToTarget == null) { this._lineToTarget = new Line(); this.Children.Add(this._lineToTarget); } this._lineToTarget.Visibility = System.Windows.Visibility.Visible; this._lineToTarget.X1 = this.agent.CurrentState.Location.U; this._lineToTarget.Y1 = this.agent.CurrentState.Location.V; this._lineToTarget.X2 = visualTarget.U; this._lineToTarget.Y2 = visualTarget.V; this._lineToTarget.Stroke = Brushes.DarkRed; this._lineToTarget.StrokeThickness = this.agent.StrokeThickness; } else { if (this._lineToTarget!=null) { this._lineToTarget.Visibility = System.Windows.Visibility.Collapsed; } } } } void _decisionMakingPeriod_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { this.agent.DecisionMakingPeriodLambdaFactor = e.NewValue; } void _showVisibleDestinations_Unchecked(object sender, RoutedEventArgs e) { this.agent.RaiseVisualEvent -= this.visualizeAgentPossibleDestinations; if (this._destinationLines != null) { int index = this.Children.IndexOf(this._destinationLines); if (index != -1) { this.Children.Remove(this._destinationLines); this._destinationLinesGeometry.Clear(); } this._destinationLines = null; } } void _showVisibleDestinations_Checked(object sender, RoutedEventArgs e) { this.agent.RaiseVisualEvent += this.visualizeAgentPossibleDestinations; } void _strokeThickness_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { this.agent.Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.agent.SetValue(VisualAgentOptionalScenario.StrokeThicknessProperty, e.NewValue); } , null); } void _viewAngle_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { this.agent.Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.agent.SetValue(VisualAgentOptionalScenario.VisibilityAngleProperty, e.NewValue * Math.PI / 180); } , null); } void _angularVelocity_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { this.agent.Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.agent.SetValue(VisualAgentOptionalScenario.AngularVelocityProperty, e.NewValue); } , null); } void _scale_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { this.agent.Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.agent.SetValue(VisualAgentOptionalScenario.BodySizeProperty, e.NewValue); } , null); } void _velocity_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { this.agent.Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.agent.SetValue(VisualAgentOptionalScenario.VelocityMagnitudeProperty, e.NewValue); } , null); } void scene_AgentPositionSet(object sender, MouseEventArgs e) { Point p = this._host.InverseRenderTransform.Transform(Mouse.GetPosition(this._host.FloorScene)); UV uv = new UV(p.X, p.Y); this.agent.SetInitialPosition(uv); this._host.UIMessage.Visibility = System.Windows.Visibility.Visible; this._host.UIMessage.Text = "Click on the scene to locate the agent"; } void scene_AgentPositionSetTerminated(object sender, MouseButtonEventArgs e) { Point p = this._host.InverseRenderTransform.Transform(Mouse.GetPosition(this._host.FloorScene)); UV uv = new UV(p.X, p.Y); Cell agentCell = this._host.cellularFloor.FindCell(uv); if (!this._host.AgentScapeRoutes.ContainsKey(agentCell)) { MessageBox.Show("Agent cannot be located inside boundary buffer"); return; } this._host.FloorScene.MouseMove -= scene_AgentPositionSet; this._host.FloorScene.MouseLeftButtonDown -= scene_AgentPositionSetTerminated; this._host.FloorScene.MouseMove += scene_AgentDirectionSet; this._host.FloorScene.MouseLeftButtonDown += scene_AgentDirectionSetTerminated; } void scene_AgentDirectionSet(object sender, MouseEventArgs e) { Point p = this._host.InverseRenderTransform.Transform(Mouse.GetPosition(this._host.FloorScene)); UV direction = new UV(p.X, p.Y) - this.agent.CurrentState.Location; this.agent.SetInitialDirection(direction); this._host.UIMessage.Text = "Click on the scene to set the direction of the agent"; } private void _showVisibilityAngle_Unchecked(object sender, RoutedEventArgs e) { if (this.agent != null) { this.agent.Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.agent.SetValue(VisualAgentOptionalScenario.ShowVisibilityConeProperty, false); } , null); } } private void _showVisibilityAngle_Checked(object sender, RoutedEventArgs e) { if (this.agent != null) { this.agent.Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.agent.SetValue(VisualAgentOptionalScenario.ShowVisibilityConeProperty, true); } , null); } } void _showSafetyBuffer_Unchecked(object sender, RoutedEventArgs e) { if (this.agent != null) { this.agent.Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.agent.SetValue(VisualAgentOptionalScenario.ShowSafetyBufferProperty, false); } , null); } } void _showSafetyBuffer_Checked(object sender, RoutedEventArgs e) { if (this.agent != null) { this.agent.Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { this.agent.SetValue(VisualAgentOptionalScenario.ShowSafetyBufferProperty, true); } , null); } } void scene_AgentDirectionSetTerminated(object sender, MouseButtonEventArgs e) { this._host.FloorScene.MouseMove -= scene_AgentDirectionSet; this._host.FloorScene.MouseLeftButtonDown -= scene_AgentDirectionSetTerminated; this._settings._init.Click += _initStart_Click; this._settings._clearAgent.IsEnabled = true; this._host.UIMessage.Visibility = System.Windows.Visibility.Hidden; this._settings.ShowDialog(); } void _initStart_Click(object sender, RoutedEventArgs e) { #region Debug only VisualAgentOptionalScenario.UIMessage = this._host.UIMessage; this._host.UIMessage.Text = string.Empty; this._host.UIMessage.Visibility = System.Windows.Visibility.Visible; #endregion this._settings._walkThrough.IsEnabled= true; this._settings._walkThrough.Checked += _walkThrough_Checked; this._settings._walkThrough.Unchecked += _walkThrough_Unchecked; this.agent.WalkInit(this._host.cellularFloor, this._host.AgentScapeRoutes); this._settings.init_Title.Text = "Stop Animation"; this._settings._init.Click -= _initStart_Click; this._settings._init.Click += _initStop_Click; this._animationInProgress = true; this._settings._hide.Visibility = System.Windows.Visibility.Visible; this._settings._hide.Click += _hide_Click; } void _walkThrough_Checked(object sender, RoutedEventArgs e) { this._settings.view3d.Visibility = System.Windows.Visibility.Visible; if (this._settings._allModels.Children.Count<2) { var models = this._host.BIM_To_OSM.ParseBIM(this._host.cellularFloor.Territory_Min, this._host.cellularFloor.Territory_Max, 1);//offset); List<GeometryModel3D> meshObjects = new List<GeometryModel3D>(models.Count); foreach (GeometryModel3D item in models) { meshObjects.Add(item); } this._settings._allModels.Children = new System.Windows.Media.Media3D.Model3DCollection(meshObjects); var light = new DirectionalLight() { Color = Colors.White, Direction = new Vector3D(-1, -1, -3), }; this._settings._allModels.Children.Add(light); } this.agent.RaiseVisualEvent += this.updateCamera; this._settings._camera.UpDirection = new System.Windows.Media.Media3D.Vector3D(0, 0, 1); } void _walkThrough_Unchecked(object sender, RoutedEventArgs e) { this._settings.view3d.Visibility = System.Windows.Visibility.Collapsed; this.agent.RaiseVisualEvent -= this.updateCamera; } void _hide_Click(object sender, RoutedEventArgs e) { this._host.Menues.IsEnabled = false; this._host.UIMessage.Visibility = System.Windows.Visibility.Visible; this._host.UIMessage.Text = "Press the ARROW to show agent control panel"; this._host.MouseBtn.MouseDown += _unhide_Click; this._settings.Hide(); } void _unhide_Click(object sender, MouseButtonEventArgs e) { this._host.Menues.IsEnabled = true; this._host.UIMessage.Visibility = System.Windows.Visibility.Collapsed; this._host.MouseBtn.MouseDown -= _unhide_Click; this._settings.ShowDialog(); } void _initStop_Click(object sender, RoutedEventArgs e) { this.stopAnimation(); var reporter = new SpatialAnalysis.Visualization.DebugReporter(); reporter.AddReport(VisualAgentOptionalScenario.Debuger.ToString()); VisualAgentOptionalScenario.Debuger.Clear(); reporter.Owner = this._host; reporter.ShowDialog(); } public void stopAnimation() { if (this._animationInProgress) { this._host.FreeNavigationAgentCharacter = FreeNavigationAgent.Create(this.agent.CurrentState);// new FreeNavigationAgent(this.agent); this._getWalkingTrailDataMenu.IsEnabled = true; this._settings._walkThrough.IsEnabled = false; this._settings._walkThrough.IsChecked = false; this._settings._walkThrough.Checked -= _walkThrough_Checked; this._settings._walkThrough.Unchecked -= _walkThrough_Unchecked; this._settings._hide.Visibility = System.Windows.Visibility.Collapsed; this._settings._hide.Click -= _hide_Click; this._settings.init_Title.Text = "Start Animation"; this.agent.StopAnimation(); this._settings._init.Click += _initStart_Click; this._settings._init.Click -= _initStop_Click; this._animationInProgress = false; } } private void updateCamera() { this._settings._camera.Position = new System.Windows.Media.Media3D.Point3D(this.agent.CurrentState.Location.U, this.agent.CurrentState.Location.V, this._host.BIM_To_OSM.PlanElevation + this._host.BIM_To_OSM.VisibilityObstacleHeight); this._settings._camera.LookDirection = new System.Windows.Media.Media3D.Vector3D(this.agent.CurrentState.Direction.U, this.agent.CurrentState.Direction.V, 0); } // clear agent and the events related to it private void _clearAgent_Click(object sender, RoutedEventArgs e) { this.stopAnimation(); this.cleanUpAgent(); } private void cleanUpAgent() { if (this._animationInProgress) { MessageBox.Show("Stop the animation before removing the agent"); return; } this._settings._showRepulsionTrajectory.Checked -= _showRepulsionTrajectory_Checked; this._settings._showRepulsionTrajectory.Unchecked -= _showRepulsionTrajectory_Unchecked; this._settings._showClosestBarrier.Checked -= _showClosestBarrier_Checked; this._settings._showClosestBarrier.Unchecked -= _showClosestBarrier_Unchecked; this._settings._accelerationMagnitude.ValueChanged -= _accelerationMagnitude_ValueChanged; this._settings._barrierRepulsionRange.ValueChanged -= _barrierRepulsionRange_ValueChanged; this._settings._repulsionChangeRate.ValueChanged -= _repulsionChangeRate_ValueChanged; this._settings._angleWeight.ValueChanged -= _angleWeight_ValueChanged; this._settings._desirabilityWeight.ValueChanged -= _desirabilityWeight_ValueChanged; this._settings._decisionMakingPeriod.ValueChanged -= _decisionMakingPeriod_ValueChanged; this._settings._captureVisualEvents.Checked -= _captureVisualEvents_Checked; this._settings._captureVisualEvents.Unchecked -= _captureVisualEvents_Unchecked; this._settings._showVisibeDestinations.Checked -= _showVisibleDestinations_Checked; this._settings._showVisibeDestinations.Unchecked -= _showVisibleDestinations_Unchecked; this._settings._angularVelocity.ValueChanged -= _angularVelocity_ValueChanged; this._settings._velocity.ValueChanged -= _velocity_ValueChanged; this._settings._bodySize.ValueChanged -= _scale_ValueChanged; this._settings._viewAngle.ValueChanged -= _viewAngle_ValueChanged; this._settings._showVisibiityAngle.Checked -= _showVisibilityAngle_Checked; this._settings._showVisibiityAngle.Unchecked -= _showVisibilityAngle_Unchecked; this._settings._init.Click -= _initStart_Click; this._settings._strokeThickness.ValueChanged -= _strokeThickness_ValueChanged; this._settings._showSafetyBuffer.Checked -= _showSafetyBuffer_Checked; this._settings._showSafetyBuffer.Unchecked -= _showSafetyBuffer_Unchecked; this._settings._barrierFriction.ValueChanged -= _barrierFriction_ValueChanged; this._settings._bodyElasticity.ValueChanged -= _bodyElasticity_ValueChanged; this.Children.Remove(this.agent); this.agent = null; VisualAgentOptionalScenario.UIMessage = null; this._host.UIMessage.Text = string.Empty; this._host.UIMessage.Visibility = System.Windows.Visibility.Hidden; this._host.UIMessage.Foreground = Brushes.DarkRed; if (this._destinationLines != null) { if (this._destinationLines != null) { int index = this.Children.IndexOf(this._destinationLines); if (index != -1) { this.Children.Remove(this._destinationLines); this._destinationLinesGeometry.Clear(); } } } this._destinationLinesGeometry = null; this._destinationLines = null; if (this._lineToTarget != null) { try { this.Children.Remove(this._lineToTarget); } catch (Exception) { } this._lineToTarget = null; } this._settings._addAgent.IsEnabled = true; this._settings._addAgent.Click += this._addAgent_Click; this._settings._clearAgent.IsEnabled = false; } //visualize Agent's Possible Destinations private void visualizeAgentPossibleDestinations() { Cell vantageCell = this._host.cellularFloor.FindCell(this.agent.CurrentState.Location); if (vantageCell == null || !this._host.AgentScapeRoutes.ContainsKey(vantageCell)) { return; } if (this._destinationLines == null) { this._destinationLinesGeometry=new StreamGeometry(); this._destinationLines = new Path() { Stroke = Brushes.Green, StrokeThickness = this.agent.StrokeThickness, StrokeDashArray = new DoubleCollection() { this.agent.StrokeThickness, this.agent.StrokeThickness }, }; this.Children.Add(this._destinationLines); } this._destinationLinesGeometry.Clear(); using (var sgo = this._destinationLinesGeometry.Open()) { Point p0 = new Point(this.agent.CurrentState.Location.U, this.agent.CurrentState.Location.V); sgo.BeginFigure(p0, false, false); foreach (var item in this._host.AgentScapeRoutes[vantageCell].Destinations) { sgo.LineTo(p0, false, false); sgo.LineTo(new Point(item.Destination.U, item.Destination.V), true, true); } } this._destinationLines.Data = this._destinationLinesGeometry; } void _trainingMenu_Click(object sender, RoutedEventArgs e) { if (this._host.trailVisualization.AgentWalkingTrail == null) { MessageBox.Show("Setting a walking trail for training is required", "Walking Trail Not Defined"); return; } OptionalScenarioTraining training = new OptionalScenarioTraining(this._host); training.Owner = this._host; training.ShowDialog(); } /// <summary> /// Sets the host. /// </summary> /// <param name="host">The main document to which this control belongs.</param> public void SetHost(OSMDocument host) { this._host = host; this.RenderTransform = this._host.RenderTransformation; this._host.OptionalScenarios.Items.Insert(2, this._captureEventMenu); this._host.OptionalScenarios.Items.Insert(2, this._getWalkingTrailDataMenu); this._host.OptionalScenarios.Items.Insert(2, this._animation_Menu); this._host.OptionalScenarios.Items.Add(this._trainingMenu); var bindConvector = new ValueToBoolConverter(); Binding bind = new Binding("FreeNavigationAgentCharacter"); bind.Source = this._host; bind.Converter = bindConvector; bind.Mode = BindingMode.OneWay; this._captureEventMenu.SetBinding(MenuItem.IsEnabledProperty, bind); this._getWalkingTrailDataMenu.SetBinding(MenuItem.IsEnabledProperty, bind); Binding animation = new Binding("AgentScapeRoutes"); animation.Source = this._host; animation.Converter = bindConvector; animation.Mode = BindingMode.OneWay; this._animation_Menu.SetBinding(MenuItem.IsEnabledProperty, animation); this._trainingMenu.SetBinding(MenuItem.IsEnabledProperty, animation); } } }
// =========================================================== // Copyright (C) 2014-2015 Kendar.org // // 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS // BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF // OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // =========================================================== using System; using System.Diagnostics; using System.IO; using System.Threading; using ConcurrencyHelpers.Interfaces; using ConcurrencyHelpers.Utils; using GenericHelpers; using Node.Cs.Lib.Exceptions; using Node.Cs.Lib.Settings; namespace Node.Cs.Lib { public class NodeCsRunner : MarshalByRefObject { private const int RECYCLE_POLL = 1000; //static NodeCsSettings _settings; private static string _currentPath; private static AppDomain _runningAppDomain; private NodeCsServer _server; private static NodeCsRunner _runner; private static SystemTimer _recycleTimer; private static Process _process; private static string _executableCodeBase; private static string[] _args; private static string _help; public static int MaxMemorySize { get; set; } internal int StartInstance(string[] args, string executableCodeBase, string help) { var clp = new CommandLineParser(args, help); try { _currentPath = Path.GetDirectoryName(executableCodeBase); if (string.IsNullOrEmpty(_currentPath)) { throw new NodeCsException("Missing Root Path"); } var settingsFile = ReRootPath("node.config"); if (clp.Has("config")) { settingsFile = ReRootPath(clp["config"]); } Console.WriteLine("Using settings from: {0}.", settingsFile); NodeCsSettings nodeCsSettings = null; if (!File.Exists(settingsFile)) { _currentPath = Path.GetDirectoryName(settingsFile); nodeCsSettings = InitializeSettingsFromCommandLine(clp); } else { _currentPath = Path.GetDirectoryName(settingsFile); } NodeCsConfiguration.InitializeConfigurations(settingsFile, nodeCsSettings); } catch (Exception ex) { Console.WriteLine(ex); clp.ShowHelp(); } var basicNodeCsSetting = new NodeCsSettings(); try { basicNodeCsSetting = NodeCsConfiguration.GetSection<NodeCsSettings>("NodeCsSettings"); _server = new NodeCsServer(basicNodeCsSetting, _currentPath); _server.Start(); } catch (System.Reflection.ReflectionTypeLoadException le) { Console.WriteLine(le); } catch (Exception ex) { Console.WriteLine(ex); } return basicNodeCsSetting.Threading.MaxMemorySize; } internal void StopInstance() { try { _server.Stop(); } catch (Exception ex) { Console.WriteLine(ex); } } private static void CreateDomain() { _runningAppDomain = AppDomain.CreateDomain(Guid.NewGuid().ToString()); var typeToInvoke = typeof(NodeCsRunner); _runner = (NodeCsRunner)_runningAppDomain.CreateInstanceAndUnwrap( typeToInvoke.Assembly.FullName, typeToInvoke.FullName); } static void OnRecycleTimer(object sender, ElapsedTimerEventArgs e) { if (_process.PrivateMemorySize64 > MaxMemorySize) { Recycle(); } } static string ReRootPath(string path) { if (Path.IsPathRooted(path)) return path; return Path.Combine(_currentPath.TrimEnd(new[] { '/', '\\' }), path.TrimStart(new[] { '/', '\\' })); } private static NodeCsSettings InitializeSettingsFromCommandLine(CommandLineParser clp) { var settings = NodeCsSettings.Defaults(_currentPath); if (clp.Has("webpath")) { settings.Paths.WebPaths[0].FileSystemPath = ReRootPath(clp["webpath"]); } if (clp.Has("binpath")) { settings.Paths.BinPaths[0] = ReRootPath(clp["binpath"]); } if (clp.Has("datadir")) { settings.Paths.DataDir = ReRootPath(clp["datapath"]); } if (clp.Has("threads")) { int threads; if (int.TryParse(clp["threads"], out threads)) { settings.Threading.ThreadNumber = threads; } } if (clp.Has("port")) { int port; if (int.TryParse(clp["port"], out port)) { settings.Listener.Port = port; } } return settings; } public static void Recycle() { var oldAppDomain = _runningAppDomain; var oldRunner = _runner; CreateDomain(); oldRunner = null; AppDomain.Unload(oldAppDomain); _runner.StartInstance(_args, _executableCodeBase, _help); Thread.Sleep(100); } public static void StartServer(string[] args, string executableCodeBase, string help = "") { _help = help; _args = args; _executableCodeBase = executableCodeBase; _process = Process.GetCurrentProcess(); _recycleTimer = new SystemTimer(RECYCLE_POLL, RECYCLE_POLL); _recycleTimer.Elapsed += OnRecycleTimer; CreateDomain(); MaxMemorySize = _runner.StartInstance(_args, _executableCodeBase, _help); _recycleTimer.Start(); } public static void StopServer() { _runner.StopInstance(); AppDomain.Unload(_runningAppDomain); } public bool IsRunning { get { return _server.IsRunning; } } public static void CleanCache() { _runningAppDomain.SetData(CLEAR_CACHE_COMMAND, CLEAR_CACHE_COMMAND); } public const string CLEAR_CACHE_COMMAND = "CLEAR_CACHE"; } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoadSoftDelete.Business.ERCLevel { /// <summary> /// H05Level111ReChild (editable child object).<br/> /// This is a generated base class of <see cref="H05Level111ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="H04Level11"/> collection. /// </remarks> [Serializable] public partial class H05Level111ReChild : BusinessBase<H05Level111ReChild> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Level_1_1_1_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Level_1_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_Child_Name, "Level_1_1_1 Child Name"); /// <summary> /// Gets or sets the Level_1_1_1 Child Name. /// </summary> /// <value>The Level_1_1_1 Child Name.</value> public string Level_1_1_1_Child_Name { get { return GetProperty(Level_1_1_1_Child_NameProperty); } set { SetProperty(Level_1_1_1_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="H05Level111ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="H05Level111ReChild"/> object.</returns> internal static H05Level111ReChild NewH05Level111ReChild() { return DataPortal.CreateChild<H05Level111ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="H05Level111ReChild"/> object, based on given parameters. /// </summary> /// <param name="cMarentID2">The CMarentID2 parameter of the H05Level111ReChild to fetch.</param> /// <returns>A reference to the fetched <see cref="H05Level111ReChild"/> object.</returns> internal static H05Level111ReChild GetH05Level111ReChild(int cMarentID2) { return DataPortal.FetchChild<H05Level111ReChild>(cMarentID2); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="H05Level111ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> private H05Level111ReChild() { // Prevent direct creation // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="H05Level111ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="H05Level111ReChild"/> object from the database, based on given criteria. /// </summary> /// <param name="cMarentID2">The CMarent ID2.</param> protected void Child_Fetch(int cMarentID2) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetH05Level111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@CMarentID2", cMarentID2).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, cMarentID2); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); } BusinessRules.CheckRules(); } } /// <summary> /// Loads a <see cref="H05Level111ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Level_1_1_1_Child_NameProperty, dr.GetString("Level_1_1_1_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="H05Level111ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(H04Level11 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddH05Level111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_ID", parent.Level_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_Child_Name", ReadProperty(Level_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="H05Level111ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(H04Level11 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateH05Level111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_ID", parent.Level_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_Child_Name", ReadProperty(Level_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="H05Level111ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(H04Level11 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteH05Level111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_ID", parent.Level_1_1_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region Pseudo Events /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
/* * Naiad ver. 0.5 * Copyright (c) Microsoft Corporation * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT * LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR * A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing * permissions and limitations under the License. */ #define VAR_LENGTH_INT using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Microsoft.Research.Naiad.Serialization { internal static class NativeSASerializers { public static unsafe NativeSA Serialize(NativeSA target, byte[] array) { int arrayLength = array.Length; if (target.EnsureAvailable(arrayLength * sizeof(byte) + sizeof(int))) { target = Serialize(target, arrayLength); byte* dest = (byte *)(target.ArrayBegin + target.CurPos); for (int i = 0; i < arrayLength; i++) { *dest++ = array[i]; } target.CurPos += arrayLength; } return target; } public static unsafe NativeSA Serialize(NativeSA target, float[] array) { int arrayLength = array.Length; if (target.EnsureAvailable(arrayLength * sizeof(float) + sizeof(int))) { target = Serialize(target, arrayLength); float* dest = (float*)(target.ArrayBegin + target.CurPos); for (int i = 0; i < arrayLength; i++) { *dest++ = array[i]; } target.CurPos += arrayLength * sizeof(float); } return target; } public static unsafe NativeSA Serialize(NativeSA target, int[] array) { int arrayLength = array.Length; if (target.EnsureAvailable(arrayLength * sizeof(int) + sizeof(int))) { target = Serialize(target, arrayLength); int* dest = (int*)(target.ArrayBegin + target.CurPos); for (int i = 0; i < arrayLength; i++) { *dest++ = array[i]; } target.CurPos += arrayLength * sizeof(int); } return target; } public static unsafe NativeSA Serialize(NativeSA target, string source) { int stringLength = source.Length; if (target.EnsureAvailable(stringLength * sizeof(char) + sizeof(int))) { target = Serialize(target, stringLength); if (stringLength > 0) { char* targetCharPtr = (char*)(target.ArrayBegin + target.CurPos); fixed (char* strPtr = source) { char* sourceCharPtr = strPtr; for (int i = 0; i < stringLength; ++i) { *targetCharPtr++ = *sourceCharPtr++; } } target.CurPos += stringLength * sizeof(char); } } return target; } public static unsafe NativeSA Serialize(NativeSA target, long source) { if (target.EnsureAvailable(sizeof(long))) { long* dest = (long *)(target.ArrayBegin + target.CurPos); *dest = source; target.CurPos += sizeof(long); } return target; } public static unsafe NativeSA Serialize(NativeSA target, ulong source) { if (target.EnsureAvailable(sizeof(ulong))) { ulong* dest = (ulong*)(target.ArrayBegin + target.CurPos); *dest = source; target.CurPos += sizeof(ulong); } return target; } public static unsafe NativeSA Serialize(NativeSA target, short source) { if (target.EnsureAvailable(sizeof(short))) { short* dest = (short*)(target.ArrayBegin + target.CurPos); *dest = source; target.CurPos += sizeof(short); } return target; } public static unsafe NativeSA Serialize(NativeSA target, int source) { if (target.EnsureAvailable(sizeof(int))) { int* dest = (int*)(target.ArrayBegin + target.CurPos); *dest = source; target.CurPos += sizeof(int); } return target; } public static unsafe NativeSA Serialize(NativeSA target, uint source) { if (target.EnsureAvailable(sizeof(uint))) { uint *dest = (uint *)(target.ArrayBegin + target.CurPos); *dest = source; target.CurPos += sizeof(uint); } return target; } public static unsafe NativeSA Serialize(NativeSA target, bool source) { return Serialize(target, (int)(source ? 1 : 0)); } public static unsafe NativeSA Serialize(NativeSA target, byte source) { if (target.EnsureAvailable(sizeof(byte))) { byte* dest = (byte*)(target.ArrayBegin + target.CurPos); *dest = source; target.CurPos += sizeof(byte); } return target; } public static unsafe NativeSA Serialize(NativeSA target, double source) { if (target.EnsureAvailable(sizeof(double))) { double* dest = (double*)(target.ArrayBegin + target.CurPos); *dest = source; target.CurPos += sizeof(double); } return target; } public static unsafe NativeSA Serialize(NativeSA target, float source) { if (target.EnsureAvailable(sizeof(float))) { float* dest = (float*)(target.ArrayBegin + target.CurPos); *dest = source; target.CurPos += sizeof(float); } return target; } } /// <summary> /// Serializer implementations for primitive types. /// </summary> public static class Serializers { /// <summary> /// Attempts to serialize the given array to the given target buffer. /// </summary> /// <param name="target">The target buffer.</param> /// <param name="array">The array to be serialized.</param> /// <returns>The original target buffer if serialization failed, otherwise the updated target buffer.</returns> public static unsafe SubArray<byte> Serialize(this SubArray<byte> target, byte[] array) { int arrayLength = array.Length; if (target.EnsureAvailable(arrayLength * sizeof(byte) + sizeof(int))) { target = target.Serialize(arrayLength); #if false fixed (byte* dest = &target.Array[target.Count]) { byte* ptr = dest; for (int i = 0; i < array.Length; ++i) { *ptr++ = array[i]; } } #else Buffer.BlockCopy(array, 0, target.Array, target.Count, arrayLength * sizeof(byte)); #endif target.Count += arrayLength; } return target; } /// <summary> /// Attempts to serialize the given array to the given target buffer. /// </summary> /// <param name="target">The target buffer.</param> /// <param name="array">The array to be serialized.</param> /// <returns>The original target buffer if serialization failed, otherwise the updated target buffer.</returns> public static unsafe SubArray<byte> Serialize(this SubArray<byte> target, float[] array) { int arrayLength = array.Length; if (target.EnsureAvailable(arrayLength * sizeof(float) + sizeof(int))) { target = target.Serialize(array.Length); #if false fixed (byte* dest = &target.Array[target.Count]) { float* ptr = (float*)dest; for (int i = 0; i < array.Length; ++i) { *ptr++ = array[i]; } } #else Buffer.BlockCopy(array, 0, target.Array, target.Count, arrayLength * sizeof(float)); #endif target.Count += array.Length * sizeof(float); } return target; } /// <summary> /// Attempts to serialize the given array to the given target buffer. /// </summary> /// <param name="target">The target buffer.</param> /// <param name="array">The array to be serialized.</param> /// <returns>The original target buffer if serialization failed, otherwise the updated target buffer.</returns> public static unsafe SubArray<byte> Serialize(this SubArray<byte> target, int[] array) { if (target.EnsureAvailable(array.Length * sizeof(int) + sizeof(int))) { target = target.Serialize(array.Length); #if false fixed (byte* dest = &target.Array[target.Count]) { int* ptr = (int*)dest; for (int i = 0; i < array.Length; ++i) { *ptr++ = array[i]; } } #else Buffer.BlockCopy(array, 0, target.Array, target.Count, array.Length * sizeof(int)); #endif target.Count += array.Length * sizeof(int); } return target; } /// <summary> /// Attempts to serialize the given string to the given target buffer. /// </summary> /// <param name="target">The target buffer.</param> /// <param name="source">The string to be serialized.</param> /// <returns>The original target buffer if serialization failed, otherwise the updated target buffer.</returns> public static unsafe SubArray<byte> Serialize(this SubArray<byte> target, string source) { int stringLength = source.Length; if (target.EnsureAvailable(stringLength * sizeof(char) + sizeof(int))) { target = target.Serialize(stringLength); if (stringLength > 0) { fixed (byte* ptr = &target.Array[target.Count]) { fixed (char* strPtr = source) { char* sourceCharPtr = strPtr; char* targetCharPtr = (char*)ptr; for (int i = 0; i < stringLength; ++i) { *targetCharPtr++ = *sourceCharPtr++; } } } target.Count += stringLength * sizeof(char); } } return target; } /// <summary> /// Attempts to serialize the given value to the given target buffer. /// </summary> /// <param name="target">The target buffer.</param> /// <param name="source">The value to be serialized.</param> /// <returns>The original target buffer if serialization failed, otherwise the updated target buffer.</returns> public static unsafe SubArray<byte> Serialize(this SubArray<byte> target, long source) { if (target.EnsureAvailable(sizeof(long))) { fixed (byte* ptr = &target.Array[target.Count]) { *(long*)ptr = source; } target.Count += sizeof(long); } return target; } /// <summary> /// Attempts to serialize the given value to the given target buffer. /// </summary> /// <param name="target">The target buffer.</param> /// <param name="source">The value to be serialized.</param> /// <returns>The original target buffer if serialization failed, otherwise the updated target buffer.</returns> public static unsafe SubArray<byte> Serialize(this SubArray<byte> target, ulong source) { if (target.EnsureAvailable(4)) { fixed (byte* ptr = &target.Array[target.Count]) { *(ulong*)ptr = source; } target.Count += 4; } return target; } /// <summary> /// Attempts to serialize the given value to the given target buffer. /// </summary> /// <param name="target">The target buffer.</param> /// <param name="source">The value to be serialized.</param> /// <returns>The original target buffer if serialization failed, otherwise the updated target buffer.</returns> public static unsafe SubArray<byte> Serialize(this SubArray<byte> target, short source) { if (target.EnsureAvailable(sizeof(short))) { fixed (byte* ptr = &target.Array[target.Count]) { *(long*)ptr = source; } target.Count += sizeof(short); } return target; } /// <summary> /// Attempts to serialize the given value to the given target buffer. /// </summary> /// <param name="target">The target buffer.</param> /// <param name="source">The value to be serialized.</param> /// <returns>The original target buffer if serialization failed, otherwise the updated target buffer.</returns> public static unsafe SubArray<byte> Serialize(this SubArray<byte> target, int source) { if (target.EnsureAvailable(4)) { fixed (byte* ptr = &target.Array[target.Count]) { *(int*)ptr = source; } target.Count += 4; /* target.Array[target.Count++] = (byte)((source >> 0) % 256); target.Array[target.Count++] = (byte)((source >> 8) % 256); target.Array[target.Count++] = (byte)((source >> 16) % 256); target.Array[target.Count++] = (byte)((source >> 24) % 256);*/ } return target; } /// <summary> /// Attempts to serialize the given value to the given target buffer. /// </summary> /// <param name="target">The target buffer.</param> /// <param name="source">The value to be serialized.</param> /// <returns>The original target buffer if serialization failed, otherwise the updated target buffer.</returns> public static unsafe SubArray<byte> Serialize(this SubArray<byte> target, uint source) { if (target.EnsureAvailable(4)) { fixed (byte* ptr = &target.Array[target.Count]) { *(uint*)ptr = source; } target.Count += 4; } return target; } /// <summary> /// Attempts to serialize the given value to the given target buffer. /// </summary> /// <param name="target">The target buffer.</param> /// <param name="source">The value to be serialized.</param> /// <returns>The original target buffer if serialization failed, otherwise the updated target buffer.</returns> public static unsafe SubArray<byte> Serialize(this SubArray<byte> target, bool source) { return Serialize(target, (int)(source ? 1 : 0)); } /// <summary> /// Attempts to serialize the given value to the given target buffer. /// </summary> /// <param name="target">The target buffer.</param> /// <param name="source">The value to be serialized.</param> /// <returns>The original target buffer if serialization failed, otherwise the updated target buffer.</returns> public static SubArray<byte> Serialize(this SubArray<byte> target, byte source) { if (target.EnsureAvailable(1)) { target.Array[target.Count++] = source; } return target; } /// <summary> /// Attempts to serialize the given value to the given target buffer. /// </summary> /// <param name="target">The target buffer.</param> /// <param name="source">The value to be serialized.</param> /// <returns>The original target buffer if serialization failed, otherwise the updated target buffer.</returns> public static unsafe SubArray<byte> Serialize(this SubArray<byte> target, double source) { if (target.EnsureAvailable(8)) { fixed (byte* ptr = &target.Array[target.Count]) { *(double*)ptr = source; } target.Count += 8; /*byte[] bytes = BitConverter.GetBytes(source); for (int i = 0; i < bytes.Length; ++i) target.Array[target.Count++] = bytes[i];*/ } return target; } /// <summary> /// Attempts to serialize the given value to the given target buffer. /// </summary> /// <param name="target">The target buffer.</param> /// <param name="source">The value to be serialized.</param> /// <returns>The original target buffer if serialization failed, otherwise the updated target buffer.</returns> public static unsafe SubArray<byte> Serialize(this SubArray<byte> target, float source) { if (target.EnsureAvailable(sizeof(float))) { fixed (byte* ptr = &target.Array[target.Count]) { *(float*)ptr = source; } target.Count += sizeof(float); /*byte[] bytes = BitConverter.GetBytes(source); for (int i = 0; i < bytes.Length; ++i) target.Array[target.Count++] = bytes[i];*/ } return target; } } /// <summary> /// Deserializer implementations for primitive types. /// </summary> public static class Deserializers { #if false public static bool TryDeserialize<K, V>(ref RecvBuffer source, out Dictionary<K, V> dictionary) { var thingy = default(Pair<K, V>[]); var serializer = CodeGeneration.AutoSerialization.GetSerializer<Pair<K, V>[]>(); var result = serializer.TryDeserialize(ref source, out thingy); dictionary = thingy.ToDictionary(x => x.v1, x => x.v2); return result; } #endif /// <summary> /// Attempts to deserialize a value from the given source buffer. /// </summary> /// <param name="source">The target buffer. In the event of success, the current position of the buffer will be advanced.</param> /// <param name="value">The deserialized value, if this method returns true.</param> /// <returns>True if deserialization succeeded, otherwise false.</returns> public unsafe static bool TryDeserialize(ref RecvBuffer source, out bool value) { value = false; int b; if (TryDeserialize(ref source, out b)) { value = (b == 1); return true; } return false; } /// <summary> /// Attempts to deserialize a value from the given source buffer. /// </summary> /// <param name="source">The target buffer. In the event of success, the current position of the buffer will be advanced.</param> /// <param name="value">The deserialized value, if this method returns true.</param> /// <returns>True if deserialization succeeded, otherwise false.</returns> public unsafe static bool TryDeserialize(ref RecvBuffer source, out byte value) { if (source.End - source.CurrentPos < sizeof(byte)) { value = default(byte); return false; } fixed (byte* ptr = &source.Buffer[source.CurrentPos]) { value = *ptr; } source.CurrentPos += sizeof(byte); return true; } /// <summary> /// Attempts to deserialize a value from the given source buffer. /// </summary> /// <param name="source">The target buffer. In the event of success, the current position of the buffer will be advanced.</param> /// <param name="value">The deserialized value, if this method returns true.</param> /// <returns>True if deserialization succeeded, otherwise false.</returns> public unsafe static bool TryDeserialize(ref RecvBuffer source, out char value) { if (source.End - source.CurrentPos < sizeof(char)) { value = default(char); return false; } fixed (byte* ptr = &source.Buffer[source.CurrentPos]) { value = *(char*)ptr; } source.CurrentPos += sizeof(char); return true; } /// <summary> /// Attempts to deserialize a value from the given source buffer. /// </summary> /// <param name="source">The target buffer. In the event of success, the current position of the buffer will be advanced.</param> /// <param name="value">The deserialized value, if this method returns true.</param> /// <returns>True if deserialization succeeded, otherwise false.</returns> public unsafe static bool TryDeserialize(ref RecvBuffer source, out short value) { if (source.End - source.CurrentPos < sizeof(short)) { value = default(short); return false; } fixed (byte* ptr = &source.Buffer[source.CurrentPos]) { value = *(short*)ptr; } source.CurrentPos += sizeof(short); return true; } /// <summary> /// Attempts to deserialize a value from the given source buffer. /// </summary> /// <param name="source">The target buffer. In the event of success, the current position of the buffer will be advanced.</param> /// <param name="value">The deserialized value, if this method returns true.</param> /// <returns>True if deserialization succeeded, otherwise false.</returns> public unsafe static bool TryDeserialize(ref RecvBuffer source, out int value) { if (source.End - source.CurrentPos < sizeof(int)) { value = default(int); return false; } fixed (byte* ptr = &source.Buffer[source.CurrentPos]) { value = *(int*)ptr; } source.CurrentPos += sizeof(int); return true; } /// <summary> /// Attempts to deserialize a value from the given source buffer. /// </summary> /// <param name="source">The target buffer. In the event of success, the current position of the buffer will be advanced.</param> /// <param name="value">The deserialized value, if this method returns true.</param> /// <returns>True if deserialization succeeded, otherwise false.</returns> public unsafe static bool TryDeserialize(ref RecvBuffer source, out uint value) { if (source.End - source.CurrentPos < sizeof(uint)) { value = default(uint); return false; } fixed (byte* ptr = &source.Buffer[source.CurrentPos]) { value = *(uint*)ptr; } source.CurrentPos += sizeof(uint); return true; } /// <summary> /// Attempts to deserialize a value from the given source buffer. /// </summary> /// <param name="source">The target buffer. In the event of success, the current position of the buffer will be advanced.</param> /// <param name="value">The deserialized value, if this method returns true.</param> /// <returns>True if deserialization succeeded, otherwise false.</returns> public unsafe static bool TryDeserialize(ref RecvBuffer source, out long value) { if (source.End - source.CurrentPos < sizeof(long)) { value = default(long); return false; } fixed (byte* ptr = &source.Buffer[source.CurrentPos]) { value = *(long*)ptr; } source.CurrentPos += sizeof(long); return true; } /// <summary> /// Attempts to deserialize a value from the given source buffer. /// </summary> /// <param name="source">The target buffer. In the event of success, the current position of the buffer will be advanced.</param> /// <param name="value">The deserialized value, if this method returns true.</param> /// <returns>True if deserialization succeeded, otherwise false.</returns> public unsafe static bool TryDeserialize(ref RecvBuffer source, out ulong value) { if (source.End - source.CurrentPos < sizeof(ulong)) { value = default(ulong); return false; } fixed (byte* ptr = &source.Buffer[source.CurrentPos]) { value = *(ulong*)ptr; } source.CurrentPos += sizeof(ulong); return true; } /// <summary> /// Attempts to deserialize a value from the given source buffer. /// </summary> /// <param name="source">The target buffer. In the event of success, the current position of the buffer will be advanced.</param> /// <param name="value">The deserialized value, if this method returns true.</param> /// <returns>True if deserialization succeeded, otherwise false.</returns> public unsafe static bool TryDeserialize(ref RecvBuffer source, out float value) { if (source.End - source.CurrentPos < sizeof(float)) { value = default(float); return false; } fixed (byte* ptr = &source.Buffer[source.CurrentPos]) { value = *(float*)ptr; } source.CurrentPos += sizeof(float); return true; } /// <summary> /// Attempts to deserialize a value from the given source buffer. /// </summary> /// <param name="source">The target buffer. In the event of success, the current position of the buffer will be advanced.</param> /// <param name="value">The deserialized value, if this method returns true.</param> /// <returns>True if deserialization succeeded, otherwise false.</returns> public unsafe static bool TryDeserialize(ref RecvBuffer source, out double value) { if (source.End - source.CurrentPos < sizeof(double)) { value = default(double); return false; } fixed (byte* ptr = &source.Buffer[source.CurrentPos]) { value = *(double*)ptr; } source.CurrentPos += sizeof(double); return true; } /// <summary> /// Attempts to deserialize a string from the given source buffer. /// </summary> /// <param name="source">The target buffer. In the event of success, the current position of the buffer will be advanced.</param> /// <param name="value">The deserialized string, if this method returns true.</param> /// <returns>True if deserialization succeeded, otherwise false.</returns> public unsafe static bool TryDeserialize(ref RecvBuffer source, out string value) { int resetPosition = source.CurrentPos; int stringLength = -1; if (!TryDeserialize(ref source, out stringLength)) { value = default(string); return false; } if (source.End - source.CurrentPos < sizeof(char) * stringLength) { source.CurrentPos = resetPosition; value = default(string); return false; } fixed (byte* bufPtr = source.Buffer) { char* stringStart = (char*)(bufPtr + source.CurrentPos); value = new string(stringStart, 0, stringLength); } source.CurrentPos += stringLength * sizeof(char); return true; } /// <summary> /// Attempts to deserialize an array from the given source buffer. /// </summary> /// <param name="source">The target buffer. In the event of success, the current position of the buffer will be advanced.</param> /// <param name="value">The deserialized array, if this method returns true.</param> /// <returns>True if deserialization succeeded, otherwise false.</returns> public unsafe static bool TryDeserialize(ref RecvBuffer source, out byte[] value) { int resetPosition = source.CurrentPos; int arrayLength = -1; if (!TryDeserialize(ref source, out arrayLength)) { value = default(byte[]); return false; } if (source.End - source.CurrentPos < sizeof(byte) * arrayLength) { source.CurrentPos = resetPosition; value = default(byte[]); return false; } value = new byte[arrayLength]; #if false fixed (byte* bufPtr = source.Buffer) { byte* arrayStart = (byte*)(bufPtr + source.CurrentPos); for (int i = 0; i < arrayLength; ++i) value[i] = arrayStart[i]; } #else Buffer.BlockCopy(source.Buffer, source.CurrentPos, value, 0, arrayLength * sizeof(byte)); #endif source.CurrentPos += arrayLength * sizeof(byte); return true; } /// <summary> /// Attempts to deserialize an array from the given source buffer. /// </summary> /// <param name="source">The target buffer. In the event of success, the current position of the buffer will be advanced.</param> /// <param name="value">The deserialized array, if this method returns true.</param> /// <returns>True if deserialization succeeded, otherwise false.</returns> public unsafe static bool TryDeserialize(ref RecvBuffer source, out int[] value) { int resetPosition = source.CurrentPos; int arrayLength = -1; if (!TryDeserialize(ref source, out arrayLength)) { value = default(int[]); return false; } if (source.End - source.CurrentPos < sizeof(int) * arrayLength) { source.CurrentPos = resetPosition; value = default(int[]); return false; } value = new int[arrayLength]; #if false fixed (byte* bufPtr = source.Buffer) { int* arrayStart = (int*)(bufPtr + source.CurrentPos); for (int i = 0; i < arrayLength; ++i) value[i] = arrayStart[i]; } #else Buffer.BlockCopy(source.Buffer, source.CurrentPos, value, 0, arrayLength * sizeof(int)); #endif source.CurrentPos += arrayLength * sizeof(int); return true; } /// <summary> /// Attempts to deserialize an array from the given source buffer. /// </summary> /// <param name="source">The target buffer. In the event of success, the current position of the buffer will be advanced.</param> /// <param name="value">The deserialized array, if this method returns true.</param> /// <returns>True if deserialization succeeded, otherwise false.</returns> public unsafe static bool TryDeserialize(ref RecvBuffer source, out float[] value) { int resetPosition = source.CurrentPos; int arrayLength = -1; if (!TryDeserialize(ref source, out arrayLength)) { value = default(float[]); return false; } if (source.End - source.CurrentPos < sizeof(float) * arrayLength) { source.CurrentPos = resetPosition; value = default(float[]); return false; } value = new float[arrayLength]; #if false fixed (byte* bufPtr = source.Buffer) { float* arrayStart = (float*)(bufPtr + source.CurrentPos); for (int i = 0; i < arrayLength; ++i) value[i] = arrayStart[i]; } #else Buffer.BlockCopy(source.Buffer, source.CurrentPos, value, 0, arrayLength * sizeof(float)); #endif source.CurrentPos += arrayLength * sizeof(float); return true; } } }
using System.Collections.ObjectModel; namespace Meziantou.Framework; public static partial class EnumerableExtensions { /// <summary> /// Allow to use the foreach keyword with an IEnumerator /// </summary> public static IEnumerator<T> GetEnumerator<T>(this IEnumerator<T> enumerator) => enumerator; /// <summary> /// Allow to use the foreach keyword with an IAsyncEnumerator /// </summary> public static IAsyncEnumerator<T> GetAsyncEnumerator<T>(this IAsyncEnumerator<T> enumerator) => enumerator; public static void AddRange<T>(this ICollection<T> collection!!, params T[] items) { foreach (var item in items) { collection.Add(item); } } public static void AddRange<T>(this ICollection<T> collection!!, IEnumerable<T>? items) { if (items != null) { foreach (var item in items) { collection.Add(item); } } } public static void Replace<T>(this IList<T> list!!, T oldItem, T newItem) { var index = list.IndexOf(oldItem); if (index < 0) throw new ArgumentOutOfRangeException(nameof(oldItem)); list[index] = newItem; } public static void AddOrReplace<T>(this IList<T> list!!, T? oldItem, T newItem) { var index = list.IndexOf(oldItem!); if (index < 0) { list.Add(newItem); } else { list[index] = newItem; } } public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> items) where T : struct { foreach (var item in items) { if (item.HasValue) yield return item.GetValueOrDefault(); } } public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> source!!) where T : class { return source.Where(item => item != null)!; } public static IEnumerable<string> WhereNotNullOrEmpty(this IEnumerable<string?> source!!) { return source.Where(item => !string.IsNullOrEmpty(item))!; } public static IEnumerable<string> WhereNotNullOrWhiteSpace(this IEnumerable<string?> source!!) { return source.Where(item => !string.IsNullOrWhiteSpace(item))!; } #if NET6_0_OR_GREATER public static IEnumerable<TSource> DistinctBy<TSource, TKey>(IEnumerable<TSource> source, Func<TSource, TKey> keySelector) #elif NET5_0 || NETSTANDARD2_0 public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) #else #error Platform not supported #endif { return DistinctBy(source, keySelector, EqualityComparer<TKey>.Default); } #if NET6_0_OR_GREATER public static IEnumerable<TSource> DistinctBy<TSource, TKey>(IEnumerable<TSource> source!!, Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? comparer) #elif NET5_0 || NETSTANDARD2_0 public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source!!, Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? comparer) #else #error Platform not supported #endif { var hash = new HashSet<TKey>(comparer); return source.Where(p => hash.Add(keySelector(p))); } public static bool IsDistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { return IsDistinctBy(source, keySelector, EqualityComparer<TKey>.Default); } public static bool IsDistinctBy<TSource, TKey>(this IEnumerable<TSource> source!!, Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? comparer) { var hash = new HashSet<TKey>(comparer); foreach (var item in source) { if (!hash.Add(keySelector(item))) return false; } return true; } public static bool IsDistinct<TSource>(this IEnumerable<TSource> source) { return IsDistinct(source, EqualityComparer<TSource>.Default); } public static bool IsDistinct<TSource>(this IEnumerable<TSource> source!!, IEqualityComparer<TSource>? comparer) { var hash = new HashSet<TSource>(comparer); foreach (var item in source) { if (!hash.Add(item)) return false; } return true; } public static IEnumerable<T> Sort<T>(this IEnumerable<T> list) { return Sort(list, comparer: null); } public static IEnumerable<T> Sort<T>(this IEnumerable<T> list, IComparer<T>? comparer) { return list.OrderBy(item => item, comparer); } public static int IndexOf<T>(this IEnumerable<T> list, T value) { return list.IndexOf(value, comparer: null); } public static int IndexOf<T>(this IEnumerable<T> list!!, T value, IEqualityComparer<T>? comparer) { comparer ??= EqualityComparer<T>.Default; var index = 0; foreach (var item in list) { if (comparer.Equals(item, value)) return index; index++; } return -1; } public static long LongIndexOf<T>(this IEnumerable<T> list, T value) where T : IEquatable<T> { return list.LongIndexOf(value, EqualityComparer<T>.Default); } public static long LongIndexOf<T>(this IEnumerable<T> list!!, T value, IEqualityComparer<T> comparer!!) { var index = 0L; foreach (var item in list) { if (comparer.Equals(item, value)) return index; index++; } return -1L; } public static bool ContainsIgnoreCase(this IEnumerable<string> str!!, string value) { return str.Contains(value, StringComparer.OrdinalIgnoreCase); } public static void EnumerateAll<TSource>(this IEnumerable<TSource> source!!) { using var enumerator = source.GetEnumerator(); while (enumerator.MoveNext()) { } } public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T>? items) { if (items == null) return Enumerable.Empty<T>(); return items; } public static void ForEach<TSource>(this IEnumerable<TSource> source!!, Action<TSource> action) { foreach (var item in source) { action(item); } } public static void ForEach<TSource>(this IEnumerable<TSource> source!!, Action<TSource, int> action) { var index = 0; foreach (var item in source) { action(item, index); index++; } } #if NET6_0_OR_GREATER public static T MaxBy<T, TValue>(IEnumerable<T> enumerable!!, Func<T, TValue> selector!!) #elif NET5_0 || NETSTANDARD2_0 public static T MaxBy<T, TValue>(this IEnumerable<T> enumerable!!, Func<T, TValue> selector!!) #else #error Platform not supported #endif where TValue : IComparable { var enumerator = enumerable.GetEnumerator(); try { if (!enumerator.MoveNext()) throw new ArgumentException("Collection is empty", nameof(enumerable)); var maxElem = enumerator.Current; var maxVal = selector(maxElem); while (enumerator.MoveNext()) { var currVal = selector(enumerator.Current); if (currVal.CompareTo(maxVal) > 0) { maxVal = currVal; maxElem = enumerator.Current; } } return maxElem; } finally { enumerator.Dispose(); } } #if NET6_0_OR_GREATER public static T MaxBy<T, TValue>(IEnumerable<T> enumerable!!, Func<T, TValue?> selector!!, IComparer<TValue> comparer!!) #elif NET5_0 || NETSTANDARD2_0 public static T MaxBy<T, TValue>(this IEnumerable<T> enumerable!!, Func<T, TValue?> selector!!, IComparer<TValue> comparer!!) #else #error Platform not supported #endif { var enumerator = enumerable.GetEnumerator(); try { if (!enumerator.MoveNext()) throw new ArgumentException("Collection is empty", nameof(enumerable)); var maxElem = enumerator.Current; var maxVal = selector(maxElem); while (enumerator.MoveNext()) { var currVal = selector(enumerator.Current); if (comparer.Compare(currVal, maxVal) > 0) { maxVal = currVal; maxElem = enumerator.Current; } } return maxElem; } finally { enumerator.Dispose(); } } #if NET6_0_OR_GREATER public static T Max<T>(IEnumerable<T> enumerable!!, IComparer<T> comparer!!) #elif NET5_0 || NETSTANDARD2_0 public static T Max<T>(this IEnumerable<T> enumerable!!, IComparer<T> comparer!!) #else #error Platform not supported #endif { var enumerator = enumerable.GetEnumerator(); try { if (!enumerator.MoveNext()) throw new ArgumentException("Collection is empty", nameof(enumerable)); var maxVal = enumerator.Current; while (enumerator.MoveNext()) { var currVal = enumerator.Current; if (comparer.Compare(currVal, maxVal) > 0) { maxVal = currVal; } } return maxVal; } finally { enumerator.Dispose(); } } #if NET6_0_OR_GREATER public static T MinBy<T, TValue>(IEnumerable<T> enumerable!!, Func<T, TValue> selector!!) where TValue : IComparable #elif NET5_0 || NETSTANDARD2_0 public static T MinBy<T, TValue>(this IEnumerable<T> enumerable!!, Func<T, TValue> selector!!) where TValue : IComparable #else #error Platform not supported #endif { var enumerator = enumerable.GetEnumerator(); try { if (!enumerator.MoveNext()) throw new ArgumentException("Collection is empty", nameof(enumerable)); var minElem = enumerator.Current; var minVal = selector(minElem); while (enumerator.MoveNext()) { var currVal = selector(enumerator.Current); if (currVal.CompareTo(minVal) < 0) { minVal = currVal; minElem = enumerator.Current; } } return minElem; } finally { enumerator.Dispose(); } } #if NET6_0_OR_GREATER public static T MinBy<T, TValue>(IEnumerable<T> enumerable!!, Func<T, TValue?> selector!!, IComparer<TValue> comparer!!) #elif NET5_0 || NETSTANDARD2_0 public static T MinBy<T, TValue>(this IEnumerable<T> enumerable!!, Func<T, TValue?> selector!!, IComparer<TValue> comparer!!) #else #error Platform not supported #endif { var enumerator = enumerable.GetEnumerator(); try { if (!enumerator.MoveNext()) throw new ArgumentException("Collection is empty", nameof(enumerable)); var minElem = enumerator.Current; var minVal = selector(minElem); while (enumerator.MoveNext()) { var currVal = selector(enumerator.Current); if (comparer.Compare(currVal, minVal) < 0) { minVal = currVal; minElem = enumerator.Current; } } return minElem; } finally { enumerator.Dispose(); } } #if NET6_0_OR_GREATER public static T Min<T>(IEnumerable<T> enumerable!!, IComparer<T> comparer!!) #elif NET5_0 || NETSTANDARD2_0 public static T Min<T>(this IEnumerable<T> enumerable!!, IComparer<T> comparer!!) #else #error Platform not supported #endif { var enumerator = enumerable.GetEnumerator(); try { if (!enumerator.MoveNext()) throw new ArgumentException("Collection is empty", nameof(enumerable)); var minVal = enumerator.Current; while (enumerator.MoveNext()) { var currVal = enumerator.Current; if (comparer.Compare(currVal, minVal) < 0) { minVal = currVal; } } return minVal; } finally { enumerator.Dispose(); } } public static TimeSpan Sum(this IEnumerable<TimeSpan> enumerable) { var result = TimeSpan.Zero; foreach (var item in enumerable) { result += item; } return result; } public static TimeSpan Average(this IEnumerable<TimeSpan> enumerable) { var result = 0L; var count = 0; foreach (var item in enumerable) { result += item.Ticks; count++; } return TimeSpan.FromTicks(result / count); } public static IEnumerable<T> ToOnlyEnumerable<T>(this IEnumerable<T> enumerable) { foreach (var item in enumerable) yield return item; } public static ReadOnlyCollection<T> ToReadOnlyCollection<T>(this IEnumerable<T> source!!) { return new ReadOnlyCollection<T>(source.ToList()); } public static ICollection<T> ToCollection<T>(this IEnumerable<T> sequence) { return sequence is ICollection<T> collection ? collection : sequence.ToList(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "MA0016:Prefer return collection abstraction instead of implementation", Justification = "Similar to Enumerable.ToList()")] public static async Task<List<T>> ToListAsync<T>(this Task<IEnumerable<T>> task) { var result = await task.ConfigureAwait(false); return result.ToList(); } }
// Copyright (c) 2016 Trevor Redfern // // This software is released under the MIT License. // http://opensource.org/licenses/mit-license.php namespace Tests.Characters { using System.Linq; using Xunit; using SilverNeedle.Characters; using SilverNeedle.Serialization; using SilverNeedle.Utility; public class CharacterStrategyTests { EntityGateway<CharacterStrategy> strategies; public CharacterStrategyTests() { var list = CharacterBuildYaml.ParseYaml().Load<CharacterStrategy>(); strategies = EntityGateway<CharacterStrategy>.LoadFromList(list); } [Fact] public void DefaultTargetLevelIsOne() { var strat = new CharacterStrategy(); Assert.Equal(1, strat.TargetLevel); } [Fact] public void LoadsWeightedTablesForRacesAndClasses() { var archer = strategies.Find("Archer"); Assert.Equal(10, archer.Races.All.First().MaximumValue); Assert.Equal("elf", archer.Races.All.First().Option); Assert.Equal(10, archer.Classes.All.First().MaximumValue); Assert.Equal("Fighter", archer.Classes.All.First().Option); } [Fact] public void StrategyProvidesGuidanceOnFavoringClassSkills() { var tank = strategies.Find("tank"); Assert.Equal(3.2f, tank.ClassSkillMultiplier); } [Fact] public void IgnoreCaseMatching() { var tank = strategies.Find("tank"); Assert.NotNull(tank); } [Fact] public void StrategyProvidesBaseForAllSkills() { var archer = strategies.Find("archer"); Assert.Equal(1, archer.BaseSkillWeight); } [Fact] public void StrategyProvidesSpecificationOnSkills() { var archer = strategies.Find("archer"); Assert.NotNull(archer.FavoredSkills); Assert.Equal("survival", archer.FavoredSkills.All.First().Option); Assert.Equal(20, archer.FavoredSkills.All.First().MaximumValue); } [Fact] public void StrategyProvidesRecommendationsOnFeats() { var tank = strategies.Find("tank"); var feats = tank.FavoredFeats.All; Assert.Equal("power attack", feats.First().Option); Assert.Equal(100, feats.First().MaximumValue); Assert.Equal(3, feats.Count()); } [Fact] public void StrategyFavorsSomeAttributesAheadOfOthers() { var tank = strategies.Find("tank"); var abilities = tank.FavoredAbilities.All; Assert.Equal(AbilityScoreTypes.Strength, abilities.First().Option); Assert.Equal(100, abilities.First().MaximumValue); Assert.Equal(6, abilities.Count()); } [Fact] public void StrategyProvidesDefaultsToAbilitiesNotSpecifiedOfOne() { var archer = strategies.Find("archer"); var abilities = archer.FavoredAbilities.All; Assert.Equal(AbilityScoreTypes.Strength, abilities.First().Option); Assert.Equal(AbilityScoreTypes.Charisma, abilities.Last().Option); Assert.Equal(1, abilities.First().MaximumValue); Assert.Equal(6, abilities.Last().MaximumValue); Assert.Equal(6, abilities.Count()); } [Fact] public void AnEmptyStrategySelectsAllAttributesEvenly() { var strategy = new CharacterStrategy(); Assert.Equal(6, strategy.FavoredAbilities.All.Count()); } [Fact] public void SpecifiesTheDesignerToUseCreatingCharacter() { var archer = strategies.Find("archer"); Assert.Equal("create-default", archer.Designer); } [Fact] public void DefaultAbilityScoreGeneratorToAverageAbilities() { var strategy = new CharacterStrategy(); Assert.Contains("AverageAbilityScore", strategy.AbilityScoreRoller); } [Fact] public void CanSpecifyDifferentAbilityScoreGeneratorsInStrategy() { var archer = strategies.Find("archer"); Assert.Contains("HeroicAbilityScore", archer.AbilityScoreRoller); } [Fact] public void CopyConstructorShouldCopyLanguageLists() { var strategyOne = new CharacterStrategy(); strategyOne.AddLanguageKnown("English"); strategyOne.AddLanguageChoice("French"); var copy = new CharacterStrategy(strategyOne); copy.AddLanguageKnown("German"); copy.AddLanguageChoice("Russian"); Assert.Equal(new string[] { "English" }, strategyOne.LanguagesKnown); Assert.Equal(new string[] { "French" }, strategyOne.LanguageChoices); } [Fact] public void AddNamedWeightedTable() { var strat = new CharacterStrategy(); strat.AddCustomValue("colors", "red", 10); Assert.Equal("red", strat.ChooseOption<string>("colors")); var copy = strat.Copy(); Assert.Equal("red", copy.ChooseOption<string>("colors")); } [Fact] public void CanGetAListOfAllCustomOptions() { var strat = new CharacterStrategy(); strat.AddCustomValue("table", "value-1", 1); strat.AddCustomValue("table", "value-2", 1); strat.AddCustomValue("table", "value-3", 1); Assert.Equal(3, strat.GetOptions<string>("table").Count()); Assert.Contains("value-1", strat.GetOptions<string>("table")); Assert.Contains("value-2", strat.GetOptions<string>("table")); } [Fact] public void CanSerializeAndDeserializeTheCharacterStrategy() { var archer = strategies.Find("archer"); var saved = new YamlObjectStore(); saved.Serialize(archer); var loaded = new CharacterStrategy(saved); Assert.Equal(archer.Name, loaded.Name); } private const string CharacterBuildYaml = @"--- - build: name: Archer ability-score-roller: SilverNeedle.Actions.CharacterGenerator.Abilities.HeroicAbilityScoreGenerator races: - name: elf weight: 10 - name: human weight: 12 classes: - name: Fighter weight: 10 - name: Ranger weight: 15 - name: Rogue weight: 5 classskillmultiplier: 2 baseskillweight: 1 skills: - name: survival weight: 20 - name: climb weight: 16 - name: perception weight: 16 feats: - name: point-blank shot weight: 20 - name: quick draw weight: 10 designer: create-default - build: name: Tank races: - name: halfling weight: 12 - name: half-orc weight: 10 classes: - name: Fighter weight: 10 - name: Paladin weight: 8 - name: Ranger weight: 6 - name: Monk weight: 6 classskillmultiplier: 3.2 baseskillweight: 1 skills: - name: survival weight: 20 - name: climb weight: 16 - name: perception weight: 16 feats: - name: power attack weight: 100 - name: cleave weight: 40 - name: shield focus weight: 10 abilities: - name: strength weight: 100 - name: dexterity weight: 50 designer: equip-adventurer "; } }
// 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; internal class TestApp { private static int test_0_0(int num, AA init, AA zero) { return init.q; } private static int test_0_1(int num, AA init, AA zero) { zero.q = num; return zero.q; } private static int test_0_2(int num, AA init, AA zero) { return init.q + zero.q; } private static int test_0_3(int num, AA init, AA zero) { return checked(init.q - zero.q); } private static int test_0_4(int num, AA init, AA zero) { zero.q += num; return zero.q; } private static int test_0_5(int num, AA init, AA zero) { zero.q += init.q; return zero.q; } private static int test_0_6(int num, AA init, AA zero) { if (init.q == num) return 100; else return zero.q; } private static int test_0_7(int num, AA init, AA zero) { return init.q < num + 1 ? 100 : -1; } private static int test_0_8(int num, AA init, AA zero) { return (init.q > zero.q ? 1 : 0) + 99; } private static int test_0_9(int num, AA init, AA zero) { return (init.q ^ zero.q) | num; } private static int test_0_10(int num, AA init, AA zero) { zero.q |= init.q; return zero.q & num; } private static int test_0_11(int num, AA init, AA zero) { return init.q >> zero.q; } private static int test_0_12(int num, AA init, AA zero) { return AA.a_init[init.q].q; } private static int test_0_13(int num, AA init, AA zero) { return AA.aa_init[num - 100, (init.q | 1) - 2, 1 + zero.q].q; } private static int test_0_14(int num, AA init, AA zero) { object bb = init.q; return (int)bb; } private static int test_0_15(int num, AA init, AA zero) { double dbl = init.q; return (int)dbl; } private static int test_0_16(int num, AA init, AA zero) { return AA.call_target(init.q); } private static int test_0_17(int num, AA init, AA zero) { return AA.call_target_ref(ref init.q); } private static int test_1_0(int num, ref AA r_init, ref AA r_zero) { return r_init.q; } private static int test_1_1(int num, ref AA r_init, ref AA r_zero) { r_zero.q = num; return r_zero.q; } private static int test_1_2(int num, ref AA r_init, ref AA r_zero) { return r_init.q + r_zero.q; } private static int test_1_3(int num, ref AA r_init, ref AA r_zero) { return checked(r_init.q - r_zero.q); } private static int test_1_4(int num, ref AA r_init, ref AA r_zero) { r_zero.q += num; return r_zero.q; } private static int test_1_5(int num, ref AA r_init, ref AA r_zero) { r_zero.q += r_init.q; return r_zero.q; } private static int test_1_6(int num, ref AA r_init, ref AA r_zero) { if (r_init.q == num) return 100; else return r_zero.q; } private static int test_1_7(int num, ref AA r_init, ref AA r_zero) { return r_init.q < num + 1 ? 100 : -1; } private static int test_1_8(int num, ref AA r_init, ref AA r_zero) { return (r_init.q > r_zero.q ? 1 : 0) + 99; } private static int test_1_9(int num, ref AA r_init, ref AA r_zero) { return (r_init.q ^ r_zero.q) | num; } private static int test_1_10(int num, ref AA r_init, ref AA r_zero) { r_zero.q |= r_init.q; return r_zero.q & num; } private static int test_1_11(int num, ref AA r_init, ref AA r_zero) { return r_init.q >> r_zero.q; } private static int test_1_12(int num, ref AA r_init, ref AA r_zero) { return AA.a_init[r_init.q].q; } private static int test_1_13(int num, ref AA r_init, ref AA r_zero) { return AA.aa_init[num - 100, (r_init.q | 1) - 2, 1 + r_zero.q].q; } private static int test_1_14(int num, ref AA r_init, ref AA r_zero) { object bb = r_init.q; return (int)bb; } private static int test_1_15(int num, ref AA r_init, ref AA r_zero) { double dbl = r_init.q; return (int)dbl; } private static int test_1_16(int num, ref AA r_init, ref AA r_zero) { return AA.call_target(r_init.q); } private static int test_1_17(int num, ref AA r_init, ref AA r_zero) { return AA.call_target_ref(ref r_init.q); } private static int test_2_0(int num) { return AA.a_init[num].q; } private static int test_2_1(int num) { AA.a_zero[num].q = num; return AA.a_zero[num].q; } private static int test_2_2(int num) { return AA.a_init[num].q + AA.a_zero[num].q; } private static int test_2_3(int num) { return checked(AA.a_init[num].q - AA.a_zero[num].q); } private static int test_2_4(int num) { AA.a_zero[num].q += num; return AA.a_zero[num].q; } private static int test_2_5(int num) { AA.a_zero[num].q += AA.a_init[num].q; return AA.a_zero[num].q; } private static int test_2_6(int num) { if (AA.a_init[num].q == num) return 100; else return AA.a_zero[num].q; } private static int test_2_7(int num) { return AA.a_init[num].q < num + 1 ? 100 : -1; } private static int test_2_8(int num) { return (AA.a_init[num].q > AA.a_zero[num].q ? 1 : 0) + 99; } private static int test_2_9(int num) { return (AA.a_init[num].q ^ AA.a_zero[num].q) | num; } private static int test_2_10(int num) { AA.a_zero[num].q |= AA.a_init[num].q; return AA.a_zero[num].q & num; } private static int test_2_11(int num) { return AA.a_init[num].q >> AA.a_zero[num].q; } private static int test_2_12(int num) { return AA.a_init[AA.a_init[num].q].q; } private static int test_2_13(int num) { return AA.aa_init[num - 100, (AA.a_init[num].q | 1) - 2, 1 + AA.a_zero[num].q].q; } private static int test_2_14(int num) { object bb = AA.a_init[num].q; return (int)bb; } private static int test_2_15(int num) { double dbl = AA.a_init[num].q; return (int)dbl; } private static int test_2_16(int num) { return AA.call_target(AA.a_init[num].q); } private static int test_2_17(int num) { return AA.call_target_ref(ref AA.a_init[num].q); } private static int test_3_0(int num) { return AA.aa_init[0, num - 1, num / 100].q; } private static int test_3_1(int num) { AA.aa_zero[0, num - 1, num / 100].q = num; return AA.aa_zero[0, num - 1, num / 100].q; } private static int test_3_2(int num) { return AA.aa_init[0, num - 1, num / 100].q + AA.aa_zero[0, num - 1, num / 100].q; } private static int test_3_3(int num) { return checked(AA.aa_init[0, num - 1, num / 100].q - AA.aa_zero[0, num - 1, num / 100].q); } private static int test_3_4(int num) { AA.aa_zero[0, num - 1, num / 100].q += num; return AA.aa_zero[0, num - 1, num / 100].q; } private static int test_3_5(int num) { AA.aa_zero[0, num - 1, num / 100].q += AA.aa_init[0, num - 1, num / 100].q; return AA.aa_zero[0, num - 1, num / 100].q; } private static int test_3_6(int num) { if (AA.aa_init[0, num - 1, num / 100].q == num) return 100; else return AA.aa_zero[0, num - 1, num / 100].q; } private static int test_3_7(int num) { return AA.aa_init[0, num - 1, num / 100].q < num + 1 ? 100 : -1; } private static int test_3_8(int num) { return (AA.aa_init[0, num - 1, num / 100].q > AA.aa_zero[0, num - 1, num / 100].q ? 1 : 0) + 99; } private static int test_3_9(int num) { return (AA.aa_init[0, num - 1, num / 100].q ^ AA.aa_zero[0, num - 1, num / 100].q) | num; } private static int test_3_10(int num) { AA.aa_zero[0, num - 1, num / 100].q |= AA.aa_init[0, num - 1, num / 100].q; return AA.aa_zero[0, num - 1, num / 100].q & num; } private static int test_3_11(int num) { return AA.aa_init[0, num - 1, num / 100].q >> AA.aa_zero[0, num - 1, num / 100].q; } private static int test_3_12(int num) { return AA.a_init[AA.aa_init[0, num - 1, num / 100].q].q; } private static int test_3_13(int num) { return AA.aa_init[num - 100, (AA.aa_init[0, num - 1, num / 100].q | 1) - 2, 1 + AA.aa_zero[0, num - 1, num / 100].q].q; } private static int test_3_14(int num) { object bb = AA.aa_init[0, num - 1, num / 100].q; return (int)bb; } private static int test_3_15(int num) { double dbl = AA.aa_init[0, num - 1, num / 100].q; return (int)dbl; } private static int test_3_16(int num) { return AA.call_target(AA.aa_init[0, num - 1, num / 100].q); } private static int test_3_17(int num) { return AA.call_target_ref(ref AA.aa_init[0, num - 1, num / 100].q); } private static int test_4_0(int num) { return BB.f_init.q; } private static int test_4_1(int num) { BB.f_zero.q = num; return BB.f_zero.q; } private static int test_4_2(int num) { return BB.f_init.q + BB.f_zero.q; } private static int test_4_3(int num) { return checked(BB.f_init.q - BB.f_zero.q); } private static int test_4_4(int num) { BB.f_zero.q += num; return BB.f_zero.q; } private static int test_4_5(int num) { BB.f_zero.q += BB.f_init.q; return BB.f_zero.q; } private static int test_4_6(int num) { if (BB.f_init.q == num) return 100; else return BB.f_zero.q; } private static int test_4_7(int num) { return BB.f_init.q < num + 1 ? 100 : -1; } private static int test_4_8(int num) { return (BB.f_init.q > BB.f_zero.q ? 1 : 0) + 99; } private static int test_4_9(int num) { return (BB.f_init.q ^ BB.f_zero.q) | num; } private static int test_4_10(int num) { BB.f_zero.q |= BB.f_init.q; return BB.f_zero.q & num; } private static int test_4_11(int num) { return BB.f_init.q >> BB.f_zero.q; } private static int test_4_12(int num) { return AA.a_init[BB.f_init.q].q; } private static int test_4_13(int num) { return AA.aa_init[num - 100, (BB.f_init.q | 1) - 2, 1 + BB.f_zero.q].q; } private static int test_4_14(int num) { object bb = BB.f_init.q; return (int)bb; } private static int test_4_15(int num) { double dbl = BB.f_init.q; return (int)dbl; } private static int test_4_16(int num) { return AA.call_target(BB.f_init.q); } private static int test_4_17(int num) { return AA.call_target_ref(ref BB.f_init.q); } private static int test_5_0(int num) { return ((AA)AA.b_init).q; } private static int test_6_0(int num, TypedReference tr_init) { return __refvalue(tr_init, AA).q; } private static unsafe int Main() { AA.reset(); if (test_0_0(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_0() failed."); return 101; } AA.verify_all(); AA.reset(); if (test_0_1(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_1() failed."); return 102; } AA.verify_all(); AA.reset(); if (test_0_2(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_2() failed."); return 103; } AA.verify_all(); AA.reset(); if (test_0_3(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_3() failed."); return 104; } AA.verify_all(); AA.reset(); if (test_0_4(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_4() failed."); return 105; } AA.verify_all(); AA.reset(); if (test_0_5(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_5() failed."); return 106; } AA.verify_all(); AA.reset(); if (test_0_6(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_6() failed."); return 107; } AA.verify_all(); AA.reset(); if (test_0_7(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_7() failed."); return 108; } AA.verify_all(); AA.reset(); if (test_0_8(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_8() failed."); return 109; } AA.verify_all(); AA.reset(); if (test_0_9(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_9() failed."); return 110; } AA.verify_all(); AA.reset(); if (test_0_10(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_10() failed."); return 111; } AA.verify_all(); AA.reset(); if (test_0_11(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_11() failed."); return 112; } AA.verify_all(); AA.reset(); if (test_0_12(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_12() failed."); return 113; } AA.verify_all(); AA.reset(); if (test_0_13(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_13() failed."); return 114; } AA.verify_all(); AA.reset(); if (test_0_14(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_14() failed."); return 115; } AA.verify_all(); AA.reset(); if (test_0_15(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_15() failed."); return 116; } AA.verify_all(); AA.reset(); if (test_0_16(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_16() failed."); return 117; } AA.verify_all(); AA.reset(); if (test_0_17(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_17() failed."); return 118; } AA.verify_all(); AA.reset(); if (test_1_0(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_0() failed."); return 119; } AA.verify_all(); AA.reset(); if (test_1_1(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_1() failed."); return 120; } AA.verify_all(); AA.reset(); if (test_1_2(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_2() failed."); return 121; } AA.verify_all(); AA.reset(); if (test_1_3(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_3() failed."); return 122; } AA.verify_all(); AA.reset(); if (test_1_4(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_4() failed."); return 123; } AA.verify_all(); AA.reset(); if (test_1_5(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_5() failed."); return 124; } AA.verify_all(); AA.reset(); if (test_1_6(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_6() failed."); return 125; } AA.verify_all(); AA.reset(); if (test_1_7(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_7() failed."); return 126; } AA.verify_all(); AA.reset(); if (test_1_8(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_8() failed."); return 127; } AA.verify_all(); AA.reset(); if (test_1_9(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_9() failed."); return 128; } AA.verify_all(); AA.reset(); if (test_1_10(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_10() failed."); return 129; } AA.verify_all(); AA.reset(); if (test_1_11(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_11() failed."); return 130; } AA.verify_all(); AA.reset(); if (test_1_12(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_12() failed."); return 131; } AA.verify_all(); AA.reset(); if (test_1_13(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_13() failed."); return 132; } AA.verify_all(); AA.reset(); if (test_1_14(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_14() failed."); return 133; } AA.verify_all(); AA.reset(); if (test_1_15(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_15() failed."); return 134; } AA.verify_all(); AA.reset(); if (test_1_16(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_16() failed."); return 135; } AA.verify_all(); AA.reset(); if (test_1_17(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_17() failed."); return 136; } AA.verify_all(); AA.reset(); if (test_2_0(100) != 100) { Console.WriteLine("test_2_0() failed."); return 137; } AA.verify_all(); AA.reset(); if (test_2_1(100) != 100) { Console.WriteLine("test_2_1() failed."); return 138; } AA.verify_all(); AA.reset(); if (test_2_2(100) != 100) { Console.WriteLine("test_2_2() failed."); return 139; } AA.verify_all(); AA.reset(); if (test_2_3(100) != 100) { Console.WriteLine("test_2_3() failed."); return 140; } AA.verify_all(); AA.reset(); if (test_2_4(100) != 100) { Console.WriteLine("test_2_4() failed."); return 141; } AA.verify_all(); AA.reset(); if (test_2_5(100) != 100) { Console.WriteLine("test_2_5() failed."); return 142; } AA.verify_all(); AA.reset(); if (test_2_6(100) != 100) { Console.WriteLine("test_2_6() failed."); return 143; } AA.verify_all(); AA.reset(); if (test_2_7(100) != 100) { Console.WriteLine("test_2_7() failed."); return 144; } AA.verify_all(); AA.reset(); if (test_2_8(100) != 100) { Console.WriteLine("test_2_8() failed."); return 145; } AA.verify_all(); AA.reset(); if (test_2_9(100) != 100) { Console.WriteLine("test_2_9() failed."); return 146; } AA.verify_all(); AA.reset(); if (test_2_10(100) != 100) { Console.WriteLine("test_2_10() failed."); return 147; } AA.verify_all(); AA.reset(); if (test_2_11(100) != 100) { Console.WriteLine("test_2_11() failed."); return 148; } AA.verify_all(); AA.reset(); if (test_2_12(100) != 100) { Console.WriteLine("test_2_12() failed."); return 149; } AA.verify_all(); AA.reset(); if (test_2_13(100) != 100) { Console.WriteLine("test_2_13() failed."); return 150; } AA.verify_all(); AA.reset(); if (test_2_14(100) != 100) { Console.WriteLine("test_2_14() failed."); return 151; } AA.verify_all(); AA.reset(); if (test_2_15(100) != 100) { Console.WriteLine("test_2_15() failed."); return 152; } AA.verify_all(); AA.reset(); if (test_2_16(100) != 100) { Console.WriteLine("test_2_16() failed."); return 153; } AA.verify_all(); AA.reset(); if (test_2_17(100) != 100) { Console.WriteLine("test_2_17() failed."); return 154; } AA.verify_all(); AA.reset(); if (test_3_0(100) != 100) { Console.WriteLine("test_3_0() failed."); return 155; } AA.verify_all(); AA.reset(); if (test_3_1(100) != 100) { Console.WriteLine("test_3_1() failed."); return 156; } AA.verify_all(); AA.reset(); if (test_3_2(100) != 100) { Console.WriteLine("test_3_2() failed."); return 157; } AA.verify_all(); AA.reset(); if (test_3_3(100) != 100) { Console.WriteLine("test_3_3() failed."); return 158; } AA.verify_all(); AA.reset(); if (test_3_4(100) != 100) { Console.WriteLine("test_3_4() failed."); return 159; } AA.verify_all(); AA.reset(); if (test_3_5(100) != 100) { Console.WriteLine("test_3_5() failed."); return 160; } AA.verify_all(); AA.reset(); if (test_3_6(100) != 100) { Console.WriteLine("test_3_6() failed."); return 161; } AA.verify_all(); AA.reset(); if (test_3_7(100) != 100) { Console.WriteLine("test_3_7() failed."); return 162; } AA.verify_all(); AA.reset(); if (test_3_8(100) != 100) { Console.WriteLine("test_3_8() failed."); return 163; } AA.verify_all(); AA.reset(); if (test_3_9(100) != 100) { Console.WriteLine("test_3_9() failed."); return 164; } AA.verify_all(); AA.reset(); if (test_3_10(100) != 100) { Console.WriteLine("test_3_10() failed."); return 165; } AA.verify_all(); AA.reset(); if (test_3_11(100) != 100) { Console.WriteLine("test_3_11() failed."); return 166; } AA.verify_all(); AA.reset(); if (test_3_12(100) != 100) { Console.WriteLine("test_3_12() failed."); return 167; } AA.verify_all(); AA.reset(); if (test_3_13(100) != 100) { Console.WriteLine("test_3_13() failed."); return 168; } AA.verify_all(); AA.reset(); if (test_3_14(100) != 100) { Console.WriteLine("test_3_14() failed."); return 169; } AA.verify_all(); AA.reset(); if (test_3_15(100) != 100) { Console.WriteLine("test_3_15() failed."); return 170; } AA.verify_all(); AA.reset(); if (test_3_16(100) != 100) { Console.WriteLine("test_3_16() failed."); return 171; } AA.verify_all(); AA.reset(); if (test_3_17(100) != 100) { Console.WriteLine("test_3_17() failed."); return 172; } AA.verify_all(); AA.reset(); if (test_4_0(100) != 100) { Console.WriteLine("test_4_0() failed."); return 173; } AA.verify_all(); AA.reset(); if (test_4_1(100) != 100) { Console.WriteLine("test_4_1() failed."); return 174; } AA.verify_all(); AA.reset(); if (test_4_2(100) != 100) { Console.WriteLine("test_4_2() failed."); return 175; } AA.verify_all(); AA.reset(); if (test_4_3(100) != 100) { Console.WriteLine("test_4_3() failed."); return 176; } AA.verify_all(); AA.reset(); if (test_4_4(100) != 100) { Console.WriteLine("test_4_4() failed."); return 177; } AA.verify_all(); AA.reset(); if (test_4_5(100) != 100) { Console.WriteLine("test_4_5() failed."); return 178; } AA.verify_all(); AA.reset(); if (test_4_6(100) != 100) { Console.WriteLine("test_4_6() failed."); return 179; } AA.verify_all(); AA.reset(); if (test_4_7(100) != 100) { Console.WriteLine("test_4_7() failed."); return 180; } AA.verify_all(); AA.reset(); if (test_4_8(100) != 100) { Console.WriteLine("test_4_8() failed."); return 181; } AA.verify_all(); AA.reset(); if (test_4_9(100) != 100) { Console.WriteLine("test_4_9() failed."); return 182; } AA.verify_all(); AA.reset(); if (test_4_10(100) != 100) { Console.WriteLine("test_4_10() failed."); return 183; } AA.verify_all(); AA.reset(); if (test_4_11(100) != 100) { Console.WriteLine("test_4_11() failed."); return 184; } AA.verify_all(); AA.reset(); if (test_4_12(100) != 100) { Console.WriteLine("test_4_12() failed."); return 185; } AA.verify_all(); AA.reset(); if (test_4_13(100) != 100) { Console.WriteLine("test_4_13() failed."); return 186; } AA.verify_all(); AA.reset(); if (test_4_14(100) != 100) { Console.WriteLine("test_4_14() failed."); return 187; } AA.verify_all(); AA.reset(); if (test_4_15(100) != 100) { Console.WriteLine("test_4_15() failed."); return 188; } AA.verify_all(); AA.reset(); if (test_4_16(100) != 100) { Console.WriteLine("test_4_16() failed."); return 189; } AA.verify_all(); AA.reset(); if (test_4_17(100) != 100) { Console.WriteLine("test_4_17() failed."); return 190; } AA.verify_all(); AA.reset(); if (test_5_0(100) != 100) { Console.WriteLine("test_5_0() failed."); return 191; } AA.verify_all(); AA.reset(); if (test_6_0(100, __makeref(AA._init)) != 100) { Console.WriteLine("test_6_0() failed."); return 192; } AA.verify_all(); Console.WriteLine("All tests passed."); return 100; } }
using System; using System.IO; using LibGit2Sharp.Tests.TestHelpers; using Xunit; using Xunit.Extensions; namespace LibGit2Sharp.Tests { public class StageFixture : BaseFixture { [Theory] [InlineData("1/branch_file.txt", FileStatus.Unaltered, true, FileStatus.Unaltered, true, 0)] [InlineData("README", FileStatus.Unaltered, true, FileStatus.Unaltered, true, 0)] [InlineData("deleted_unstaged_file.txt", FileStatus.Missing, true, FileStatus.Removed, false, -1)] [InlineData("modified_unstaged_file.txt", FileStatus.Modified, true, FileStatus.Staged, true, 0)] [InlineData("new_untracked_file.txt", FileStatus.Untracked, false, FileStatus.Added, true, 1)] [InlineData("modified_staged_file.txt", FileStatus.Staged, true, FileStatus.Staged, true, 0)] [InlineData("new_tracked_file.txt", FileStatus.Added, true, FileStatus.Added, true, 0)] public void CanStage(string relativePath, FileStatus currentStatus, bool doesCurrentlyExistInTheIndex, FileStatus expectedStatusOnceStaged, bool doesExistInTheIndexOnceStaged, int expectedIndexCountVariation) { string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { int count = repo.Index.Count; Assert.Equal(doesCurrentlyExistInTheIndex, (repo.Index[relativePath] != null)); Assert.Equal(currentStatus, repo.RetrieveStatus(relativePath)); repo.Stage(relativePath); Assert.Equal(count + expectedIndexCountVariation, repo.Index.Count); Assert.Equal(doesExistInTheIndexOnceStaged, (repo.Index[relativePath] != null)); Assert.Equal(expectedStatusOnceStaged, repo.RetrieveStatus(relativePath)); } } [Fact] public void CanStageTheUpdationOfAStagedFile() { string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { int count = repo.Index.Count; const string filename = "new_tracked_file.txt"; IndexEntry blob = repo.Index[filename]; Assert.Equal(FileStatus.Added, repo.RetrieveStatus(filename)); Touch(repo.Info.WorkingDirectory, filename, "brand new content"); Assert.Equal(FileStatus.Added | FileStatus.Modified, repo.RetrieveStatus(filename)); repo.Stage(filename); IndexEntry newBlob = repo.Index[filename]; Assert.Equal(count, repo.Index.Count); Assert.NotEqual(newBlob.Id, blob.Id); Assert.Equal(FileStatus.Added, repo.RetrieveStatus(filename)); } } [Theory] [InlineData("1/I-do-not-exist.txt", FileStatus.Nonexistent)] [InlineData("deleted_staged_file.txt", FileStatus.Removed)] public void StagingAnUnknownFileThrowsIfExplicitPath(string relativePath, FileStatus status) { var path = SandboxStandardTestRepoGitDir(); using (var repo = new Repository(path)) { Assert.Null(repo.Index[relativePath]); Assert.Equal(status, repo.RetrieveStatus(relativePath)); Assert.Throws<UnmatchedPathException>(() => repo.Stage(relativePath, new StageOptions { ExplicitPathsOptions = new ExplicitPathsOptions() })); } } [Theory] [InlineData("1/I-do-not-exist.txt", FileStatus.Nonexistent)] [InlineData("deleted_staged_file.txt", FileStatus.Removed)] public void CanStageAnUnknownFileWithLaxUnmatchedExplicitPathsValidation(string relativePath, FileStatus status) { var path = SandboxStandardTestRepoGitDir(); using (var repo = new Repository(path)) { Assert.Null(repo.Index[relativePath]); Assert.Equal(status, repo.RetrieveStatus(relativePath)); Assert.DoesNotThrow(() => repo.Stage(relativePath)); Assert.DoesNotThrow(() => repo.Stage(relativePath, new StageOptions { ExplicitPathsOptions = new ExplicitPathsOptions { ShouldFailOnUnmatchedPath = false } })); Assert.Equal(status, repo.RetrieveStatus(relativePath)); } } [Theory] [InlineData("1/I-do-not-exist.txt", FileStatus.Nonexistent)] [InlineData("deleted_staged_file.txt", FileStatus.Removed)] public void StagingAnUnknownFileWithLaxExplicitPathsValidationDoesntThrow(string relativePath, FileStatus status) { var path = SandboxStandardTestRepoGitDir(); using (var repo = new Repository(path)) { Assert.Null(repo.Index[relativePath]); Assert.Equal(status, repo.RetrieveStatus(relativePath)); repo.Stage(relativePath); repo.Stage(relativePath, new StageOptions { ExplicitPathsOptions = new ExplicitPathsOptions { ShouldFailOnUnmatchedPath = false } }); } } [Fact] public void CanStageTheRemovalOfAStagedFile() { string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { int count = repo.Index.Count; const string filename = "new_tracked_file.txt"; Assert.NotNull(repo.Index[filename]); Assert.Equal(FileStatus.Added, repo.RetrieveStatus(filename)); File.Delete(Path.Combine(repo.Info.WorkingDirectory, filename)); Assert.Equal(FileStatus.Added | FileStatus.Missing, repo.RetrieveStatus(filename)); repo.Stage(filename); Assert.Null(repo.Index[filename]); Assert.Equal(count - 1, repo.Index.Count); Assert.Equal(FileStatus.Nonexistent, repo.RetrieveStatus(filename)); } } [Theory] [InlineData("unit_test.txt")] [InlineData("!unit_test.txt")] [InlineData("!bang/unit_test.txt")] public void CanStageANewFileInAPersistentManner(string filename) { string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { Assert.Equal(FileStatus.Nonexistent, repo.RetrieveStatus(filename)); Assert.Null(repo.Index[filename]); Touch(repo.Info.WorkingDirectory, filename, "some contents"); Assert.Equal(FileStatus.Untracked, repo.RetrieveStatus(filename)); Assert.Null(repo.Index[filename]); repo.Stage(filename); Assert.NotNull(repo.Index[filename]); Assert.Equal(FileStatus.Added, repo.RetrieveStatus(filename)); } using (var repo = new Repository(path)) { Assert.NotNull(repo.Index[filename]); Assert.Equal(FileStatus.Added, repo.RetrieveStatus(filename)); } } [SkippableTheory] [InlineData(false)] [InlineData(true)] public void CanStageANewFileWithAFullPath(bool ignorecase) { // Skipping due to ignorecase issue in libgit2. // See: https://github.com/libgit2/libgit2/pull/1689. InconclusiveIf(() => ignorecase, "Skipping 'ignorecase = true' test due to ignorecase issue in libgit2."); //InconclusiveIf(() => IsFileSystemCaseSensitive && ignorecase, // "Skipping 'ignorecase = true' test on case-sensitive file system."); string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { repo.Config.Set("core.ignorecase", ignorecase); } using (var repo = new Repository(path)) { const string filename = "new_untracked_file.txt"; string fullPath = Path.Combine(repo.Info.WorkingDirectory, filename); Assert.True(File.Exists(fullPath)); AssertStage(null, repo, fullPath); AssertStage(ignorecase, repo, fullPath.ToUpperInvariant()); AssertStage(ignorecase, repo, fullPath.ToLowerInvariant()); } } private static void AssertStage(bool? ignorecase, IRepository repo, string path) { try { repo.Stage(path); Assert.Equal(FileStatus.Added, repo.RetrieveStatus(path)); repo.Reset(); Assert.Equal(FileStatus.Untracked, repo.RetrieveStatus(path)); } catch (ArgumentException) { Assert.False(ignorecase ?? true); } } [Fact] public void CanStageANewFileWithARelativePathContainingNativeDirectorySeparatorCharacters() { string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { int count = repo.Index.Count; string file = Path.Combine("Project", "a_file.txt"); Touch(repo.Info.WorkingDirectory, file, "With backward slash on Windows!"); repo.Stage(file); Assert.Equal(count + 1, repo.Index.Count); const string posixifiedPath = "Project/a_file.txt"; Assert.NotNull(repo.Index[posixifiedPath]); Assert.Equal(file, repo.Index[posixifiedPath].Path); } } [Fact] public void StagingANewFileWithAFullPathWhichEscapesOutOfTheWorkingDirThrows() { SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); string path = SandboxStandardTestRepo(); using (var repo = new Repository(path)) { string fullPath = Touch(scd.RootedDirectoryPath, "unit_test.txt", "some contents"); Assert.Throws<ArgumentException>(() => repo.Stage(fullPath)); } } [Fact] public void StagingFileWithBadParamsThrows() { var path = SandboxStandardTestRepoGitDir(); using (var repo = new Repository(path)) { Assert.Throws<ArgumentException>(() => repo.Stage(string.Empty)); Assert.Throws<ArgumentNullException>(() => repo.Stage((string)null)); Assert.Throws<ArgumentException>(() => repo.Stage(new string[] { })); Assert.Throws<ArgumentException>(() => repo.Stage(new string[] { null })); } } /* * $ git status -s * M 1/branch_file.txt * M README * M branch_file.txt * D deleted_staged_file.txt * D deleted_unstaged_file.txt * M modified_staged_file.txt * M modified_unstaged_file.txt * M new.txt * A new_tracked_file.txt * ?? new_untracked_file.txt * * By passing "*" to Stage, the following files will be added/removed/updated from the index: * - deleted_unstaged_file.txt : removed * - modified_unstaged_file.txt : updated * - new_untracked_file.txt : added */ [Theory] [InlineData("*u*", 0)] [InlineData("*", 0)] [InlineData("1/*", 0)] [InlineData("RE*", 0)] [InlineData("d*", -1)] [InlineData("*modified_unstaged*", 0)] [InlineData("new_*file.txt", 1)] public void CanStageWithPathspec(string relativePath, int expectedIndexCountVariation) { using (var repo = new Repository(SandboxStandardTestRepo())) { int count = repo.Index.Count; repo.Stage(relativePath); Assert.Equal(count + expectedIndexCountVariation, repo.Index.Count); } } [Fact] public void CanStageWithMultiplePathspecs() { using (var repo = new Repository(SandboxStandardTestRepo())) { int count = repo.Index.Count; repo.Stage(new string[] { "*", "u*" }); Assert.Equal(count, repo.Index.Count); // 1 added file, 1 deleted file, so same count } } [Theory] [InlineData("ignored_file.txt")] [InlineData("ignored_folder/file.txt")] public void CanIgnoreIgnoredPaths(string path) { using (var repo = new Repository(SandboxStandardTestRepo())) { Touch(repo.Info.WorkingDirectory, ".gitignore", "ignored_file.txt\nignored_folder/\n"); Touch(repo.Info.WorkingDirectory, path, "This file is ignored."); Assert.Equal(FileStatus.Ignored, repo.RetrieveStatus(path)); repo.Stage("*"); Assert.Equal(FileStatus.Ignored, repo.RetrieveStatus(path)); } } [Theory] [InlineData("ignored_file.txt")] [InlineData("ignored_folder/file.txt")] public void CanStageIgnoredPaths(string path) { using (var repo = new Repository(SandboxStandardTestRepo())) { Touch(repo.Info.WorkingDirectory, ".gitignore", "ignored_file.txt\nignored_folder/\n"); Touch(repo.Info.WorkingDirectory, path, "This file is ignored."); Assert.Equal(FileStatus.Ignored, repo.RetrieveStatus(path)); repo.Stage(path, new StageOptions { IncludeIgnored = true }); Assert.Equal(FileStatus.Added, repo.RetrieveStatus(path)); } } } }
/* 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 java.lang; using java.util; using stab.query; using cnatural.helpers; namespace stab.reflection { class ReflectionHelper { static String getObjectTypeSignature(TypeInfo type) { if (type.GenericArguments.any()) { var sb = new StringBuilder(); sb.append("L").append(type.FullName); sb.append("<"); foreach (var t in type.GenericArguments) { sb.append(t.Signature); } sb.append(">").append(";"); return sb.toString(); } else { return "L" + type.FullName + ";"; } } static String getClassSignature(TypeInfo type) { var sb = new StringBuilder(); appendFormalTypeParametersSignature(sb, type.GenericArguments); appendClassTypeSignature(sb, type.BaseType, type.BaseType.GenericArguments); foreach (var t in type.Interfaces) { appendClassTypeSignature(sb, t, t.GenericArguments); } return sb.toString(); } static String getMethodTypeSignature(MethodInfo method) { var sb = new StringBuilder(); appendFormalTypeParametersSignature(sb, method.GenericArguments); sb.append("("); foreach (var p in method.Parameters) { sb.append(p.Type.Signature); } sb.append(")").append(method.ReturnType.Signature); foreach (var t in method.Exceptions) { sb.append("^").append(t.Signature); } return sb.toString(); } private static void appendFormalTypeParametersSignature(StringBuilder sb, Iterable<TypeInfo> typeArguments) { if (typeArguments.any()) { sb.append("<"); foreach (var t in typeArguments) { sb.append(t.FullName); var first = true; if (t.GenericParameterBounds.any()) { foreach (var bound in t.GenericParameterBounds) { sb.append(":"); if (first) { first = false; if (!bound.IsObject) { appendClassTypeSignature(sb, bound, bound.GenericArguments); } else { sb.append("Ljava/lang/Object;"); } } else { appendClassTypeSignature(sb, bound, bound.GenericArguments); } } } else { sb.append(":"); sb.append("Ljava/lang/Object;"); } } sb.append(">"); } } private static void appendClassTypeSignature(StringBuilder sb, TypeInfo type, Iterable<TypeInfo> typeArguments) { sb.append("L").append(type.FullName); if (typeArguments.any()) { sb.append("<"); foreach (var t in typeArguments) { sb.append(t.Signature); } sb.append(">"); } sb.append(";"); } static String getObjectTypeDisplayName(TypeInfo type) { if (type.GenericArguments.any()) { var sb = new StringBuilder(); sb.append(type.FullName.replace('/', '.').replace('$', '.')); sb.append("<"); var first = true; foreach (var t in type.GenericArguments) { if (first) { first = false; } else { sb.append(", "); } sb.append(t.DisplayName); } sb.append(">"); return sb.toString(); } else { return type.FullName.replace('/', '.').replace('$', '.'); } } static void declareEnclosingGenericParameters(Scope<String, TypeInfo> genericsScope, TypeInfo type) { var genericArguments = new ArrayList<Iterable<TypeInfo>>(); var declaringType = type.DeclaringType; while (declaringType != null) { genericArguments.add(declaringType.GenericArguments); declaringType = declaringType.DeclaringType; } for (int i = genericArguments.size() - 1; i >= 0; --i) { foreach (var t in genericArguments[i]) { if (t.IsGenericParameter) { genericsScope.declareBinding(t.FullName, t); } } } } static void declareGenericTypeBindings(GenericParameterBindings genericsScope, Iterable<TypeInfo> keys, Iterable<TypeInfo> values) { if (keys.count() != values.count()) { throw new IllegalStateException(); } var it1 = keys.iterator(); var it2 = values.iterator(); while (it1.hasNext()) { var t1 = it1.next(); var t2 = it2.next(); if (t1.IsGenericParameter) { genericsScope.declareBinding(t1, t2); } } } static Iterable<TypeInfo> bindGenericParameters(Library typeSystem, GenericParameterBindings genericsScope, Iterable<TypeInfo> types) { return types.select(p => bindGenericParameters(typeSystem, genericsScope, p)).toList(); } static TypeInfo bindGenericParameters(Library typeSystem, GenericParameterBindings genericsScope, TypeInfo typeInfo) { if (genericsScope.hasBinding(typeInfo)) { return genericsScope.getBindingValue(typeInfo); } else if (typeInfo.IsArray) { return bindGenericParameters(typeSystem, genericsScope, typeInfo.ElementType).ArrayType; } else if (typeInfo.TypeKind == TypeKind.UpperBoundedWildcard) { return bindGenericParameters(typeSystem, genericsScope, typeInfo.WildcardBound).UpperBoundedWildcard; } else if (typeInfo.TypeKind == TypeKind.LowerBoundedWildcard) { return bindGenericParameters(typeSystem, genericsScope, typeInfo.WildcardBound).LowerBoundedWildcard; } else if (!typeInfo.IsClosed && typeInfo.GenericArguments.any()) { return typeSystem.getGenericType(typeInfo, bindGenericParameters(typeSystem, genericsScope, typeInfo.GenericArguments), genericsScope); } else if (typeInfo.IsGenericParameter && typeInfo.GenericParameterBounds.any()) { var param = new GenericParameterType(typeSystem, typeInfo.FullName, typeInfo); genericsScope.declareBinding(typeInfo, param); foreach (var t in typeInfo.GenericParameterBounds) { param.genericParameterBounds.add(bindGenericParameters(typeSystem, genericsScope, t)); } return param; } return typeInfo; } static TypeInfo getRawType(TypeInfo referenceType, TypeInfo type) { switch (type.TypeKind) { case GenericParameter: return type.GenericParameterBounds.firstOrDefault() ?? referenceType.getBaseClasses().lastOrDefault() ?? referenceType; case UnboundedWildcard: case LowerBoundedWildcard: return referenceType.getBaseClasses().lastOrDefault() ?? referenceType; case UpperBoundedWildcard: return type.WildcardBound; case Array: return getRawType(referenceType, type.ElementType).ArrayType; default: return (type.GenericArguments.any()) ? type.RawType : type; } } } class GenericParameterBindings { private HashMap<TypeInfo, TypeInfo> bindings; private GenericParameterBindings next; GenericParameterBindings(GenericParameterBindings next) { this.next = next; this.bindings = new HashMap<TypeInfo, TypeInfo>(); } void declareBinding(TypeInfo key, TypeInfo value) { this.bindings[key] = value; } bool hasBinding(TypeInfo key) { var b = this; do { if (b.bindings[key] != null) { return true; } } while ((b = b.next) != null); return false; } TypeInfo getBindingValue(TypeInfo key) { var b = this; do { var result = b.bindings[key]; if (result != null) { return result; } } while ((b = b.next) != null); throw new IllegalStateException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Text; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Encryption.RC2.Tests { using RC2 = System.Security.Cryptography.RC2; public static class RC2CipherTests { // These are the expected output of many decryptions. Changing these values requires re-generating test input. private static readonly string s_multiBlockString = new ASCIIEncoding().GetBytes( "This is a sentence that is longer than a block, it ensures that multi-block functions work.").ByteArrayToHex(); private static readonly string s_multiBlockString_8 = new ASCIIEncoding().GetBytes( "This is a sentence that is longer than a block,but exactly an even block multiplier of 8").ByteArrayToHex(); private static readonly string s_multiBlockStringPaddedZeros = "5468697320697320612073656E74656E63652074686174206973206C6F6E676572207468616E206120626C6F636B2C20" + "697420656E73757265732074686174206D756C74692D626C6F636B2066756E6374696F6E7320776F726B2E0000000000"; private static readonly string s_randomKey_64 = "87FF0737F868378F"; private static readonly string s_randomIv_64 = "E531E789E3E1BB6F"; public static IEnumerable<object[]> RC2TestData { get { // RFC 2268 test yield return new object[] { CipherMode.ECB, PaddingMode.None, "3000000000000000", null, "1000000000000001", null, "30649EDF9BE7D2C2" }; // RFC 2268 test yield return new object[] { CipherMode.ECB, PaddingMode.None, "FFFFFFFFFFFFFFFF", null, "FFFFFFFFFFFFFFFF", null, "278B27E42E2F0D49" }; // RFC 2268 test yield return new object[] { CipherMode.ECB, PaddingMode.None, "88bca90e90875a7f0f79c384627bafb2", null, "0000000000000000", null, "2269552ab0f85ca6" }; yield return new object[] { CipherMode.ECB, PaddingMode.None, s_randomKey_64, null, s_multiBlockString_8, null, "F6DF2E83811D6CB0C8A5830069D16F6A51C985D7003852539051FABC3C6EA7CF46BD3DBD5527003A13BC850E32BB598F" + "1AC96E96401EBBCDAEEF21D6C05B8DF2637B938CFDB8814B3CC47E30640BD0396B2AC6D7D9977499" }; yield return new object[] { CipherMode.ECB, PaddingMode.PKCS7, s_randomKey_64, null, s_multiBlockString, null, "F6DF2E83811D6CB0C8A5830069D16F6A51C985D7003852539051FABC3C6EA7CF46BD3DBD5527003A789B76CBE4D40A73" + "620F04ED9F0AA1AEC7FEC90E7934F69E0568F6DF1F38B2198821D0A771D68A3F8220C8822E387721AEB21E183555CE07" }; yield return new object[] { CipherMode.ECB, PaddingMode.Zeros, s_randomKey_64, null, s_multiBlockString, s_multiBlockStringPaddedZeros, "F6DF2E83811D6CB0C8A5830069D16F6A51C985D7003852539051FABC3C6EA7CF46BD3DBD5527003A789B76CBE4D40A73" + "620F04ED9F0AA1AEC7FEC90E7934F69E0568F6DF1F38B2198821D0A771D68A3F8220C8822E387721C669B2B62A6BF492" }; yield return new object[] { CipherMode.CBC, PaddingMode.None, s_randomKey_64, s_randomIv_64, s_multiBlockString_8, null, "85B5D998F35ECD98DB886798170F64BA2DBA4FE902791CDE900EEB0B35728FEE35FB6CADC41DF67F6056044F15B5C7ED" + "4FAB086053D7DC458C206145AE9655F1590C590FBDE76365FA488CADBCDA67B325A35E7CCBC1B9A1" }; yield return new object[] { CipherMode.CBC, PaddingMode.PKCS7, s_randomKey_64, s_randomIv_64, s_multiBlockString, null, "85B5D998F35ECD98DB886798170F64BA2DBA4FE902791CDE900EEB0B35728FEE35FB6CADC41DF67FBB691B45D92B876A" + "13FD18229E5ACB797D21D7B257520910360E00FEECDE3433FDC6F15233AE6B5CAC01289AC8B57A9A6B5DA734C2E7E733" }; yield return new object[] { CipherMode.CBC, PaddingMode.Zeros, s_randomKey_64, s_randomIv_64, s_multiBlockString, s_multiBlockStringPaddedZeros, "85B5D998F35ECD98DB886798170F64BA2DBA4FE902791CDE900EEB0B35728FEE35FB6CADC41DF67FBB691B45D92B876A" + "13FD18229E5ACB797D21D7B257520910360E00FEECDE3433FDC6F15233AE6B5CAC01289AC8B57A9A6A1BB012ED20DADA" }; } } [Theory, MemberData(nameof(RC2TestData))] public static void RC2RoundTrip(CipherMode cipherMode, PaddingMode paddingMode, string key, string iv, string textHex, string expectedDecrypted, string expectedEncrypted) { byte[] expectedDecryptedBytes = expectedDecrypted == null ? textHex.HexToByteArray() : expectedDecrypted.HexToByteArray(); byte[] expectedEncryptedBytes = expectedEncrypted.HexToByteArray(); byte[] keyBytes = key.HexToByteArray(); using (RC2 alg = RC2Factory.Create()) { alg.Key = keyBytes; alg.Padding = paddingMode; alg.Mode = cipherMode; if (iv != null) alg.IV = iv.HexToByteArray(); byte[] cipher = alg.Encrypt(textHex.HexToByteArray()); Assert.Equal<byte>(expectedEncryptedBytes, cipher); byte[] decrypted = alg.Decrypt(cipher); Assert.Equal<byte>(expectedDecryptedBytes, decrypted); } } [Fact] public static void RC2ReuseEncryptorDecryptor() { using (RC2 alg = RC2Factory.Create()) { alg.Key = s_randomKey_64.HexToByteArray(); alg.IV = s_randomIv_64.HexToByteArray(); alg.Padding = PaddingMode.PKCS7; alg.Mode = CipherMode.CBC; using (ICryptoTransform encryptor = alg.CreateEncryptor()) using (ICryptoTransform decryptor = alg.CreateDecryptor()) { for (int i = 0; i < 2; i++) { byte[] plainText1 = s_multiBlockString.HexToByteArray(); byte[] cipher1 = encryptor.Transform(plainText1); byte[] expectedCipher1 = ( "85B5D998F35ECD98DB886798170F64BA2DBA4FE902791CDE900EEB0B35728FEE35FB6CADC41DF67FBB691B45D92B876A" + "13FD18229E5ACB797D21D7B257520910360E00FEECDE3433FDC6F15233AE6B5CAC01289AC8B57A9A6B5DA734C2E7E733").HexToByteArray(); Assert.Equal<byte>(expectedCipher1, cipher1); byte[] decrypted1 = decryptor.Transform(cipher1); byte[] expectedDecrypted1 = s_multiBlockString.HexToByteArray(); Assert.Equal<byte>(expectedDecrypted1, decrypted1); byte[] plainText2 = s_multiBlockString_8.HexToByteArray(); byte[] cipher2 = encryptor.Transform(plainText2); byte[] expectedCipher2 = ( "85B5D998F35ECD98DB886798170F64BA2DBA4FE902791CDE900EEB0B35728FEE35FB6CADC41DF67F6056044F15B5C7ED" + "4FAB086053D7DC458C206145AE9655F1590C590FBDE76365FA488CADBCDA67B325A35E7CCBC1B9A15E5EBE2879C7AEC2").HexToByteArray(); Assert.Equal<byte>(expectedCipher2, cipher2); byte[] decrypted2 = decryptor.Transform(cipher2); byte[] expectedDecrypted2 = s_multiBlockString_8.HexToByteArray(); Assert.Equal<byte>(expectedDecrypted2, decrypted2); } } } } [Fact] public static void RC2ExplicitEncryptorDecryptor_WithIV() { using (RC2 alg = RC2Factory.Create()) { alg.Padding = PaddingMode.PKCS7; alg.Mode = CipherMode.CBC; using (ICryptoTransform encryptor = alg.CreateEncryptor(s_randomKey_64.HexToByteArray(), s_randomIv_64.HexToByteArray())) { byte[] plainText1 = s_multiBlockString.HexToByteArray(); byte[] cipher1 = encryptor.Transform(plainText1); byte[] expectedCipher1 = ( "85B5D998F35ECD98DB886798170F64BA2DBA4FE902791CDE900EEB0B35728FEE35FB6CADC41DF67FBB691B45D92B876A" + "13FD18229E5ACB797D21D7B257520910360E00FEECDE3433FDC6F15233AE6B5CAC01289AC8B57A9A6B5DA734C2E7E733").HexToByteArray(); Assert.Equal<byte>(expectedCipher1, cipher1); } } } [Fact] public static void RC2ExplicitEncryptorDecryptor_NoIV() { using (RC2 alg = RC2Factory.Create()) { alg.Padding = PaddingMode.PKCS7; alg.Mode = CipherMode.ECB; using (ICryptoTransform encryptor = alg.CreateEncryptor(s_randomKey_64.HexToByteArray(), null)) { byte[] plainText1 = s_multiBlockString.HexToByteArray(); byte[] cipher1 = encryptor.Transform(plainText1); byte[] expectedCipher1 = ( "F6DF2E83811D6CB0C8A5830069D16F6A51C985D7003852539051FABC3C6EA7CF46BD3DBD5527003A789B76CBE4D40A73" + "620F04ED9F0AA1AEC7FEC90E7934F69E0568F6DF1F38B2198821D0A771D68A3F8220C8822E387721AEB21E183555CE07").HexToByteArray(); Assert.Equal<byte>(expectedCipher1, cipher1); } } } } }
// 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 Xunit; namespace System.Linq.Expressions.Tests { public static class NonLiftedComparisonEqualNullableTests { #region Test methods [Fact] public static void CheckNonLiftedComparisonEqualNullableBoolTest() { bool?[] values = new bool?[] { null, true, false }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonEqualNullableBool(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonEqualNullableByteTest() { byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonEqualNullableByte(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonEqualNullableCharTest() { char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonEqualNullableChar(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonEqualNullableDecimalTest() { decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonEqualNullableDecimal(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonEqualNullableDoubleTest() { double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonEqualNullableDouble(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonEqualNullableFloatTest() { float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonEqualNullableFloat(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonEqualNullableIntTest() { int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonEqualNullableInt(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonEqualNullableLongTest() { long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonEqualNullableLong(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonEqualNullableSByteTest() { sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonEqualNullableSByte(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonEqualNullableShortTest() { short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonEqualNullableShort(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonEqualNullableUIntTest() { uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonEqualNullableUInt(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonEqualNullableULongTest() { ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonEqualNullableULong(values[i], values[j]); } } } [Fact] public static void CheckNonLiftedComparisonEqualNullableUShortTest() { ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonEqualNullableUShort(values[i], values[j]); } } } #endregion #region Test verifiers private static void VerifyComparisonEqualNullableBool(bool? a, bool? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(bool?)), Expression.Constant(b, typeof(bool?)), false, null)); Func<bool> f = e.Compile(); bool expected = a == b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonEqualNullableByte(byte? a, byte? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(byte?)), false, null)); Func<bool> f = e.Compile(); bool expected = a == b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonEqualNullableChar(char? a, char? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(char?)), Expression.Constant(b, typeof(char?)), false, null)); Func<bool> f = e.Compile(); bool expected = a == b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonEqualNullableDecimal(decimal? a, decimal? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?)), false, null)); Func<bool> f = e.Compile(); bool expected = a == b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonEqualNullableDouble(double? a, double? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?)), false, null)); Func<bool> f = e.Compile(); bool expected = a == b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonEqualNullableFloat(float? a, float? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?)), false, null)); Func<bool> f = e.Compile(); bool expected = a == b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonEqualNullableInt(int? a, int? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?)), false, null)); Func<bool> f = e.Compile(); bool expected = a == b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonEqualNullableLong(long? a, long? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?)), false, null)); Func<bool> f = e.Compile(); bool expected = a == b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonEqualNullableSByte(sbyte? a, sbyte? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(sbyte?)), false, null)); Func<bool> f = e.Compile(); bool expected = a == b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonEqualNullableShort(short? a, short? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?)), false, null)); Func<bool> f = e.Compile(); bool expected = a == b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonEqualNullableUInt(uint? a, uint? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?)), false, null)); Func<bool> f = e.Compile(); bool expected = a == b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonEqualNullableULong(ulong? a, ulong? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?)), false, null)); Func<bool> f = e.Compile(); bool expected = a == b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonEqualNullableUShort(ushort? a, ushort? b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.Equal( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?)), false, null)); Func<bool> f = e.Compile(); bool expected = a == b; bool result = f(); Assert.Equal(expected, result); } #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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.AccessControl; using System.Security.Principal; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; namespace System.IO.Pipes { /// <summary> /// Named pipe server /// </summary> public sealed partial class NamedPipeServerStream : PipeStream { private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, HandleInheritability inheritability) { Create(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, null, inheritability, 0); } // This overload is used in Mono to implement public constructors. private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, PipeSecurity pipeSecurity, HandleInheritability inheritability, PipeAccessRights additionalAccessRights) { Debug.Assert(pipeName != null && pipeName.Length != 0, "fullPipeName is null or empty"); Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction"); Debug.Assert(inBufferSize >= 0, "inBufferSize is negative"); Debug.Assert(outBufferSize >= 0, "outBufferSize is negative"); Debug.Assert((maxNumberOfServerInstances >= 1 && maxNumberOfServerInstances <= 254) || (maxNumberOfServerInstances == MaxAllowedServerInstances), "maxNumberOfServerInstances is invalid"); Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range"); string fullPipeName = Path.GetFullPath(@"\\.\pipe\" + pipeName); // Make sure the pipe name isn't one of our reserved names for anonymous pipes. if (string.Equals(fullPipeName, @"\\.\pipe\anonymous", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved); } if (IsCurrentUserOnly) { Debug.Assert(pipeSecurity == null); using (WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent()) { SecurityIdentifier identifier = currentIdentity.Owner; // Grant full control to the owner so multiple servers can be opened. // Full control is the default per MSDN docs for CreateNamedPipe. PipeAccessRule rule = new PipeAccessRule(identifier, PipeAccessRights.FullControl, AccessControlType.Allow); pipeSecurity = new PipeSecurity(); pipeSecurity.AddAccessRule(rule); pipeSecurity.SetOwner(identifier); } // PipeOptions.CurrentUserOnly is special since it doesn't match directly to a corresponding Win32 valid flag. // Remove it, while keeping others untouched since historically this has been used as a way to pass flags to CreateNamedPipe // that were not defined in the enumeration. options &= ~PipeOptions.CurrentUserOnly; } int openMode = ((int)direction) | (maxNumberOfServerInstances == 1 ? Interop.Kernel32.FileOperations.FILE_FLAG_FIRST_PIPE_INSTANCE : 0) | (int)options | (int)additionalAccessRights; // We automatically set the ReadMode to match the TransmissionMode. int pipeModes = (int)transmissionMode << 2 | (int)transmissionMode << 1; // Convert -1 to 255 to match win32 (we asserted that it is between -1 and 254). if (maxNumberOfServerInstances == MaxAllowedServerInstances) { maxNumberOfServerInstances = 255; } var pinningHandle = new GCHandle(); try { Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability, pipeSecurity, ref pinningHandle); SafePipeHandle handle = Interop.Kernel32.CreateNamedPipe(fullPipeName, openMode, pipeModes, maxNumberOfServerInstances, outBufferSize, inBufferSize, 0, ref secAttrs); if (handle.IsInvalid) { throw Win32Marshal.GetExceptionForLastWin32Error(); } InitializeHandle(handle, false, (options & PipeOptions.Asynchronous) != 0); } finally { if (pinningHandle.IsAllocated) { pinningHandle.Free(); } } } // This will wait until the client calls Connect(). If we return from this method, we guarantee that // the client has returned from its Connect call. The client may have done so before this method // was called (but not before this server is been created, or, if we were servicing another client, // not before we called Disconnect), in which case, there may be some buffer already in the pipe waiting // for us to read. See NamedPipeClientStream.Connect for more information. [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] public void WaitForConnection() { CheckConnectOperationsServerWithHandle(); if (IsAsync) { WaitForConnectionCoreAsync(CancellationToken.None).GetAwaiter().GetResult(); } else { if (!Interop.Kernel32.ConnectNamedPipe(InternalHandle, IntPtr.Zero)) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_PIPE_CONNECTED) { throw Win32Marshal.GetExceptionForWin32Error(errorCode); } // pipe already connected if (errorCode == Interop.Errors.ERROR_PIPE_CONNECTED && State == PipeState.Connected) { throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected); } // If we reach here then a connection has been established. This can happen if a client // connects in the interval between the call to CreateNamedPipe and the call to ConnectNamedPipe. // In this situation, there is still a good connection between client and server, even though // ConnectNamedPipe returns zero. } State = PipeState.Connected; } } public Task WaitForConnectionAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } if (!IsAsync) { return Task.Factory.StartNew(s => ((NamedPipeServerStream)s).WaitForConnection(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } return WaitForConnectionCoreAsync(cancellationToken); } public void Disconnect() { CheckDisconnectOperations(); // Disconnect the pipe. if (!Interop.Kernel32.DisconnectNamedPipe(InternalHandle)) { throw Win32Marshal.GetExceptionForLastWin32Error(); } State = PipeState.Disconnected; } // Gets the username of the connected client. Note that we will not have access to the client's // username until it has written at least once to the pipe (and has set its impersonationLevel // argument appropriately). public unsafe string GetImpersonationUserName() { CheckWriteOperations(); const int UserNameMaxLength = Interop.Kernel32.CREDUI_MAX_USERNAME_LENGTH + 1; char* userName = stackalloc char[UserNameMaxLength]; // ~1K if (!Interop.Kernel32.GetNamedPipeHandleState(InternalHandle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, userName, UserNameMaxLength)) { throw WinIOError(Marshal.GetLastWin32Error()); } return new string(userName); } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- // This method calls a delegate while impersonating the client. Note that we will not have // access to the client's security token until it has written at least once to the pipe // (and has set its impersonationLevel argument appropriately). public void RunAsClient(PipeStreamImpersonationWorker impersonationWorker) { CheckWriteOperations(); ExecuteHelper execHelper = new ExecuteHelper(impersonationWorker, InternalHandle); RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(tryCode, cleanupCode, execHelper); // now handle win32 impersonate/revert specific errors by throwing corresponding exceptions if (execHelper._impersonateErrorCode != 0) { throw WinIOError(execHelper._impersonateErrorCode); } else if (execHelper._revertImpersonateErrorCode != 0) { throw WinIOError(execHelper._revertImpersonateErrorCode); } } // the following are needed for CER private static RuntimeHelpers.TryCode tryCode = new RuntimeHelpers.TryCode(ImpersonateAndTryCode); private static RuntimeHelpers.CleanupCode cleanupCode = new RuntimeHelpers.CleanupCode(RevertImpersonationOnBackout); private static void ImpersonateAndTryCode(object helper) { ExecuteHelper execHelper = (ExecuteHelper)helper; RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { if (Interop.Advapi32.ImpersonateNamedPipeClient(execHelper._handle)) { execHelper._mustRevert = true; } else { execHelper._impersonateErrorCode = Marshal.GetLastWin32Error(); } } if (execHelper._mustRevert) { // impersonate passed so run user code execHelper._userCode(); } } private static void RevertImpersonationOnBackout(object helper, bool exceptionThrown) { ExecuteHelper execHelper = (ExecuteHelper)helper; if (execHelper._mustRevert) { if (!Interop.Advapi32.RevertToSelf()) { execHelper._revertImpersonateErrorCode = Marshal.GetLastWin32Error(); } } } internal class ExecuteHelper { internal PipeStreamImpersonationWorker _userCode; internal SafePipeHandle _handle; internal bool _mustRevert; internal int _impersonateErrorCode; internal int _revertImpersonateErrorCode; internal ExecuteHelper(PipeStreamImpersonationWorker userCode, SafePipeHandle handle) { _userCode = userCode; _handle = handle; } } // Async version of WaitForConnection. See the comments above for more info. private unsafe Task WaitForConnectionCoreAsync(CancellationToken cancellationToken) { CheckConnectOperationsServerWithHandle(); if (!IsAsync) { throw new InvalidOperationException(SR.InvalidOperation_PipeNotAsync); } var completionSource = new ConnectionCompletionSource(this); if (!Interop.Kernel32.ConnectNamedPipe(InternalHandle, completionSource.Overlapped)) { int errorCode = Marshal.GetLastWin32Error(); switch (errorCode) { case Interop.Errors.ERROR_IO_PENDING: break; // If we are here then the pipe is already connected, or there was an error // so we should unpin and free the overlapped. case Interop.Errors.ERROR_PIPE_CONNECTED: // IOCompletitionCallback will not be called because we completed synchronously. completionSource.ReleaseResources(); if (State == PipeState.Connected) { throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected); } completionSource.SetCompletedSynchronously(); // We return a cached task instead of TaskCompletionSource's Task allowing the GC to collect it. return Task.CompletedTask; default: completionSource.ReleaseResources(); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } // If we are here then connection is pending. completionSource.RegisterForCancellation(cancellationToken); return completionSource.Task; } private void CheckConnectOperationsServerWithHandle() { if (InternalHandle == null) { throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet); } CheckConnectOperationsServer(); } } }