context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Unzip class for .NET 3.5 Client Profile or Mono 2.10 // Written by Alexey Yakovlev <yallie@yandex.ru> // https://github.com/yallie/unzip using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; namespace LiskSharp.Tests.Internals { /// <summary> /// Unzip helper class. /// </summary> internal class Unzip : IDisposable { /// <summary> /// Zip archive entry. /// </summary> public class Entry { /// <summary> /// Gets or sets the name of a file or a directory. /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets the comment. /// </summary> public string Comment { get; set; } /// <summary> /// Gets or sets the CRC32. /// </summary> public uint Crc32 { get; set; } /// <summary> /// Gets or sets the compressed size of the file. /// </summary> public int CompressedSize { get; set; } /// <summary> /// Gets or sets the original size of the file. /// </summary> public int OriginalSize { get; set; } /// <summary> /// Gets or sets a value indicating whether this <see cref="Entry" /> is deflated. /// </summary> public bool Deflated { get; set; } /// <summary> /// Gets a value indicating whether this <see cref="Entry" /> is a directory. /// </summary> public bool IsDirectory { get { return Name.EndsWith("/"); } } /// <summary> /// Gets or sets the timestamp. /// </summary> public DateTime Timestamp { get; set; } /// <summary> /// Gets a value indicating whether this <see cref="Entry" /> is a file. /// </summary> public bool IsFile { get { return !IsDirectory; } } [EditorBrowsable(EditorBrowsableState.Never)] public int HeaderOffset { get; set; } [EditorBrowsable(EditorBrowsableState.Never)] public int DataOffset { get; set; } } /// <summary> /// CRC32 calculation helper. /// </summary> public class Crc32Calculator { private static readonly uint[] Crc32Table = { 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d, }; private uint crcValue = 0xffffffff; public uint Crc32 { get { return crcValue ^ 0xffffffff; } } public void UpdateWithBlock(byte[] buffer, int numberOfBytes) { for (var i = 0; i < numberOfBytes; i++) { crcValue = (crcValue >> 8) ^ Crc32Table[buffer[i] ^ crcValue & 0xff]; } } } /// <summary> /// Provides data for the ExtractProgress event. /// </summary> public class FileProgressEventArgs : ProgressChangedEventArgs { /// <summary> /// Initializes a new instance of the <see cref="FileProgressEventArgs"/> class. /// </summary> /// <param name="currentFile">The current file.</param> /// <param name="totalFiles">The total files.</param> /// <param name="fileName">Name of the file.</param> public FileProgressEventArgs(int currentFile, int totalFiles, string fileName) : base(totalFiles != 0 ? currentFile * 100 / totalFiles : 100, fileName) { CurrentFile = currentFile; TotalFiles = totalFiles; FileName = fileName; } /// <summary> /// Gets the current file. /// </summary> public int CurrentFile { get; private set; } /// <summary> /// Gets the total files. /// </summary> public int TotalFiles { get; private set; } /// <summary> /// Gets the name of the file. /// </summary> public string FileName { get; private set; } } private const int EntrySignature = 0x02014B50; private const int FileSignature = 0x04034b50; private const int DirectorySignature = 0x06054B50; private const int BufferSize = 16 * 1024; /// <summary> /// Occurs when a file or a directory is extracted from an archive. /// </summary> public event EventHandler<FileProgressEventArgs> ExtractProgress; /// <summary> /// Initializes a new instance of the <see cref="Unzip" /> class. /// </summary> /// <param name="fileName">Name of the file.</param> public Unzip(string fileName) : this(File.OpenRead(fileName)) { } /// <summary> /// Initializes a new instance of the <see cref="Unzip" /> class. /// </summary> /// <param name="stream">The stream.</param> public Unzip(Stream stream) { Stream = stream; Reader = new BinaryReader(Stream); } private Stream Stream { get; set; } private BinaryReader Reader { get; set; } /// <summary> /// Performs application-defined tasks associated with /// freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { if (Stream != null) { Stream.Dispose(); Stream = null; } if (Reader != null) { Reader.Close(); Reader = null; } } /// <summary> /// Extracts the contents of the zip file to the given directory. /// </summary> /// <param name="directoryName">Name of the directory.</param> public void ExtractToDirectory(string directoryName) { for (int index = 0; index < Entries.Length; index++) { var entry = Entries[index]; // create target directory for the file var fileName = Path.Combine(directoryName, entry.Name); var dirName = Path.GetDirectoryName(fileName); Directory.CreateDirectory(dirName); // save file if it is not only a directory if (!entry.IsDirectory) { Extract(entry.Name, fileName); } var extractProgress = ExtractProgress; if (extractProgress != null) { extractProgress(this, new FileProgressEventArgs(index + 1, Entries.Length, entry.Name)); } } } /// <summary> /// Extracts the specified file to the specified name. /// </summary> /// <param name="fileName">Name of the file in zip archive.</param> /// <param name="outputFileName">Name of the output file.</param> public void Extract(string fileName, string outputFileName) { var entry = GetEntry(fileName); using (var outStream = File.Create(outputFileName)) { Extract(entry, outStream); } var fileInfo = new FileInfo(outputFileName); if (fileInfo.Length != entry.OriginalSize) { throw new InvalidDataException(string.Format( "Corrupted archive: {0} has an uncompressed size {1} which does not match its expected size {2}", outputFileName, fileInfo.Length, entry.OriginalSize)); } File.SetLastWriteTime(outputFileName, entry.Timestamp); } private Entry GetEntry(string fileName) { fileName = fileName.Replace("\\", "/").Trim().TrimStart('/'); var entry = Entries.FirstOrDefault(e => e.Name == fileName); if (entry == null) { throw new FileNotFoundException("File not found in the archive: " + fileName); } return entry; } /// <summary> /// Extracts the specified file to the output <see cref="Stream"/>. /// </summary> /// <param name="fileName">Name of the file in zip archive.</param> /// <param name="outputStream">The output stream.</param> public void Extract(string fileName, Stream outputStream) { Extract(GetEntry(fileName), outputStream); } /// <summary> /// Extracts the specified entry. /// </summary> /// <param name="entry">Zip file entry to extract.</param> /// <param name="outputStream">The stream to write the data to.</param> /// <exception cref="System.InvalidOperationException"> is thrown when the file header signature doesn't match.</exception> public void Extract(Entry entry, Stream outputStream) { // check file signature Stream.Seek(entry.HeaderOffset, SeekOrigin.Begin); if (Reader.ReadInt32() != FileSignature) { throw new InvalidDataException("File signature doesn't match."); } // move to file data Stream.Seek(entry.DataOffset, SeekOrigin.Begin); var inputStream = Stream; if (entry.Deflated) { inputStream = new DeflateStream(Stream, CompressionMode.Decompress, true); } // allocate buffer, prepare for CRC32 calculation var count = entry.OriginalSize; var bufferSize = Math.Min(BufferSize, entry.OriginalSize); var buffer = new byte[bufferSize]; var crc32Calculator = new Crc32Calculator(); while (count > 0) { // decompress data var read = inputStream.Read(buffer, 0, bufferSize); if (read == 0) { break; } crc32Calculator.UpdateWithBlock(buffer, read); // copy to the output stream outputStream.Write(buffer, 0, read); count -= read; } if (crc32Calculator.Crc32 != entry.Crc32) { throw new InvalidDataException(string.Format( "Corrupted archive: CRC32 doesn't match on file {0}: expected {1:x8}, got {2:x8}.", entry.Name, entry.Crc32, crc32Calculator.Crc32)); } } /// <summary> /// Gets the file names. /// </summary> public IEnumerable<string> FileNames { get { return Entries.Select(e => e.Name).Where(f => !f.EndsWith("/")).OrderBy(f => f); } } private Entry[] entries; /// <summary> /// Gets zip file entries. /// </summary> public Entry[] Entries { get { if (entries == null) { entries = ReadZipEntries().ToArray(); } return entries; } } private IEnumerable<Entry> ReadZipEntries() { if (Stream.Length < 22) { yield break; } Stream.Seek(-22, SeekOrigin.End); // find directory signature while (Reader.ReadInt32() != DirectorySignature) { if (Stream.Position <= 5) { yield break; } // move 1 byte back Stream.Seek(-5, SeekOrigin.Current); } // read directory properties Stream.Seek(6, SeekOrigin.Current); var entries = Reader.ReadUInt16(); var difSize = Reader.ReadInt32(); var dirOffset = Reader.ReadUInt32(); Stream.Seek(dirOffset, SeekOrigin.Begin); // read directory entries for (int i = 0; i < entries; i++) { if (Reader.ReadInt32() != EntrySignature) { continue; } // read file properties // TODO: Replace with a proper class to make this method a lot shorter. Reader.ReadInt32(); bool utf8 = (Reader.ReadInt16() & 0x0800) != 0; short method = Reader.ReadInt16(); int timestamp = Reader.ReadInt32(); uint crc32 = Reader.ReadUInt32(); int compressedSize = Reader.ReadInt32(); int fileSize = Reader.ReadInt32(); short fileNameSize = Reader.ReadInt16(); short extraSize = Reader.ReadInt16(); short commentSize = Reader.ReadInt16(); int headerOffset = Reader.ReadInt32(); Reader.ReadInt32(); int fileHeaderOffset = Reader.ReadInt32(); var fileNameBytes = Reader.ReadBytes(fileNameSize); Stream.Seek(extraSize, SeekOrigin.Current); var fileCommentBytes = Reader.ReadBytes(commentSize); var fileDataOffset = CalculateFileDataOffset(fileHeaderOffset); // decode zip file entry var encoder = utf8 ? Encoding.UTF8 : Encoding.Default; yield return new Entry { Name = encoder.GetString(fileNameBytes), Comment = encoder.GetString(fileCommentBytes), Crc32 = crc32, CompressedSize = compressedSize, OriginalSize = fileSize, HeaderOffset = fileHeaderOffset, DataOffset = fileDataOffset, Deflated = method == 8, Timestamp = ConvertToDateTime(timestamp) }; } } private int CalculateFileDataOffset(int fileHeaderOffset) { var position = Stream.Position; Stream.Seek(fileHeaderOffset + 26, SeekOrigin.Begin); var fileNameSize = Reader.ReadInt16(); var extraSize = Reader.ReadInt16(); var fileOffset = (int)Stream.Position + fileNameSize + extraSize; Stream.Seek(position, SeekOrigin.Begin); return fileOffset; } /// <summary> /// Converts DOS timestamp to a <see cref="DateTime"/> instance. /// </summary> /// <param name="dosTimestamp">The dos timestamp.</param> /// <returns>The <see cref="DateTime"/> instance.</returns> public static DateTime ConvertToDateTime(int dosTimestamp) { return new DateTime((dosTimestamp >> 25) + 1980, (dosTimestamp >> 21) & 15, (dosTimestamp >> 16) & 31, (dosTimestamp >> 11) & 31, (dosTimestamp >> 5) & 63, (dosTimestamp & 31) * 2); } } }
using System; using NBitcoin.BouncyCastle.Asn1.X509; namespace NBitcoin.BouncyCastle.Asn1.Cms { public class AuthenticatedData : Asn1Encodable { private DerInteger version; private OriginatorInfo originatorInfo; private Asn1Set recipientInfos; private AlgorithmIdentifier macAlgorithm; private AlgorithmIdentifier digestAlgorithm; private ContentInfo encapsulatedContentInfo; private Asn1Set authAttrs; private Asn1OctetString mac; private Asn1Set unauthAttrs; public AuthenticatedData( OriginatorInfo originatorInfo, Asn1Set recipientInfos, AlgorithmIdentifier macAlgorithm, AlgorithmIdentifier digestAlgorithm, ContentInfo encapsulatedContent, Asn1Set authAttrs, Asn1OctetString mac, Asn1Set unauthAttrs) { if (digestAlgorithm != null || authAttrs != null) { if (digestAlgorithm == null || authAttrs == null) { throw new ArgumentException("digestAlgorithm and authAttrs must be set together"); } } version = new DerInteger(CalculateVersion(originatorInfo)); this.originatorInfo = originatorInfo; this.macAlgorithm = macAlgorithm; this.digestAlgorithm = digestAlgorithm; this.recipientInfos = recipientInfos; this.encapsulatedContentInfo = encapsulatedContent; this.authAttrs = authAttrs; this.mac = mac; this.unauthAttrs = unauthAttrs; } private AuthenticatedData( Asn1Sequence seq) { int index = 0; version = (DerInteger)seq[index++]; Asn1Encodable tmp = seq[index++]; if (tmp is Asn1TaggedObject) { originatorInfo = OriginatorInfo.GetInstance((Asn1TaggedObject)tmp, false); tmp = seq[index++]; } recipientInfos = Asn1Set.GetInstance(tmp); macAlgorithm = AlgorithmIdentifier.GetInstance(seq[index++]); tmp = seq[index++]; if (tmp is Asn1TaggedObject) { digestAlgorithm = AlgorithmIdentifier.GetInstance((Asn1TaggedObject)tmp, false); tmp = seq[index++]; } encapsulatedContentInfo = ContentInfo.GetInstance(tmp); tmp = seq[index++]; if (tmp is Asn1TaggedObject) { authAttrs = Asn1Set.GetInstance((Asn1TaggedObject)tmp, false); tmp = seq[index++]; } mac = Asn1OctetString.GetInstance(tmp); if (seq.Count > index) { unauthAttrs = Asn1Set.GetInstance((Asn1TaggedObject)seq[index], false); } } /** * return an AuthenticatedData object from a tagged object. * * @param obj the tagged object holding the object we want. * @param isExplicit true if the object is meant to be explicitly * tagged false otherwise. * @throws ArgumentException if the object held by the * tagged object cannot be converted. */ public static AuthenticatedData GetInstance( Asn1TaggedObject obj, bool isExplicit) { return GetInstance(Asn1Sequence.GetInstance(obj, isExplicit)); } /** * return an AuthenticatedData object from the given object. * * @param obj the object we want converted. * @throws ArgumentException if the object cannot be converted. */ public static AuthenticatedData GetInstance( object obj) { if (obj == null || obj is AuthenticatedData) { return (AuthenticatedData)obj; } if (obj is Asn1Sequence) { return new AuthenticatedData((Asn1Sequence)obj); } throw new ArgumentException("Invalid AuthenticatedData: " + obj.GetType().Name); } public DerInteger Version { get { return version; } } public OriginatorInfo OriginatorInfo { get { return originatorInfo; } } public Asn1Set RecipientInfos { get { return recipientInfos; } } public AlgorithmIdentifier MacAlgorithm { get { return macAlgorithm; } } public AlgorithmIdentifier DigestAlgorithm { get { return digestAlgorithm; } } public ContentInfo EncapsulatedContentInfo { get { return encapsulatedContentInfo; } } public Asn1Set AuthAttrs { get { return authAttrs; } } public Asn1OctetString Mac { get { return mac; } } public Asn1Set UnauthAttrs { get { return unauthAttrs; } } /** * Produce an object suitable for an Asn1OutputStream. * <pre> * AuthenticatedData ::= SEQUENCE { * version CMSVersion, * originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL, * recipientInfos RecipientInfos, * macAlgorithm MessageAuthenticationCodeAlgorithm, * digestAlgorithm [1] DigestAlgorithmIdentifier OPTIONAL, * encapContentInfo EncapsulatedContentInfo, * authAttrs [2] IMPLICIT AuthAttributes OPTIONAL, * mac MessageAuthenticationCode, * unauthAttrs [3] IMPLICIT UnauthAttributes OPTIONAL } * * AuthAttributes ::= SET SIZE (1..MAX) OF Attribute * * UnauthAttributes ::= SET SIZE (1..MAX) OF Attribute * * MessageAuthenticationCode ::= OCTET STRING * </pre> */ public override Asn1Object ToAsn1Object() { Asn1EncodableVector v = new Asn1EncodableVector(version); if (originatorInfo != null) { v.Add(new DerTaggedObject(false, 0, originatorInfo)); } v.Add(recipientInfos, macAlgorithm); if (digestAlgorithm != null) { v.Add(new DerTaggedObject(false, 1, digestAlgorithm)); } v.Add(encapsulatedContentInfo); if (authAttrs != null) { v.Add(new DerTaggedObject(false, 2, authAttrs)); } v.Add(mac); if (unauthAttrs != null) { v.Add(new DerTaggedObject(false, 3, unauthAttrs)); } return new BerSequence(v); } public static int CalculateVersion(OriginatorInfo origInfo) { if (origInfo == null) return 0; int ver = 0; foreach (object obj in origInfo.Certificates) { if (obj is Asn1TaggedObject) { Asn1TaggedObject tag = (Asn1TaggedObject)obj; if (tag.TagNo == 2) { ver = 1; } else if (tag.TagNo == 3) { ver = 3; break; } } } foreach (object obj in origInfo.Crls) { if (obj is Asn1TaggedObject) { Asn1TaggedObject tag = (Asn1TaggedObject)obj; if (tag.TagNo == 1) { ver = 3; break; } } } return ver; } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; using PRI.Messaging.Patterns.Analyzer.Utility; namespace PRI.Messaging.Patterns.Analyzer { public static class CodeAnalysisExtensions { public static CatchClauseSyntax GetFirstCatchClauseByType(this TryStatementSyntax parentTryStatement, SemanticModel semanticModel, Type exceptionType, CancellationToken cancellationToken = default(CancellationToken)) { foreach (var e in parentTryStatement.Catches) { var errorType = semanticModel.GetTypeInfo(e.Declaration.Type, cancellationToken).Type as INamedTypeSymbol; if (errorType == null) { continue; } var fullName = errorType.ToDisplayString(SymbolDisplayFormat); if (exceptionType.FullName.Contains(fullName)) { return e; } } return null; } private static readonly SymbolDisplayFormat SymbolDisplayFormat = new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces); public static string ToDisplayString(this TypeSyntax typeSyntax, SemanticModel model, SymbolDisplayFormat symbolDisplayFormat, CancellationToken cancellationToken = default(CancellationToken)) { var namedTypeSymbol = (INamedTypeSymbol) model.GetTypeInfo(typeSyntax, cancellationToken).Type; return namedTypeSymbol.ToDisplayString(symbolDisplayFormat); } public static string ToDisplayString(this TypeSyntax typeSyntax, SemanticModel model, CancellationToken cancellationToken = default(CancellationToken)) { return typeSyntax.ToDisplayString(model, SymbolDisplayFormat, cancellationToken); } /// <summary> /// Generates the type syntax. /// </summary> public static TypeSyntax AsTypeSyntax(this Type type, SyntaxGenerator generator, params ITypeSymbol[] typeParams) { var typeInfo = type.GetTypeInfo(); if (!typeInfo.IsGenericType) { throw new ArgumentException(nameof(type)); } string name = type.Name.Replace('+', '.'); if (type.IsConstructedGenericType) { name = type.GetGenericTypeDefinition().Name.Replace('+', '.'); } // Get the C# representation of the generic type minus its type arguments. name = name.Substring(0, name.IndexOf("`", StringComparison.Ordinal)); // Generate the name of the generic type. return SyntaxFactory.GenericName(SyntaxFactory.Identifier(name)).WithTypeArgumentList( SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeParams.Select(generator.TypeExpression) .Cast<TypeSyntax>()))); } public static SyntaxNode GetAncestorStatement(this SyntaxNode givenNode) { if (givenNode == null) { throw new ArgumentNullException(nameof(givenNode)); } var node = givenNode.Parent; while (node != null && !(node is StatementSyntax)) { node = node.Parent; } return node; } public static SyntaxNode GetAncestorStatement(this SyntaxToken token) { if (token.Kind() == SyntaxKind.None) { throw new ArgumentNullException(nameof(token)); } var node = token.Parent; while (node != null && !(node is StatementSyntax)) { node = node.Parent; } return node; } public static T ReplaceNodes<T>(this T root, IReadOnlyList<SyntaxNode> oldNodes, SyntaxNode newNode) where T : SyntaxNode { if (oldNodes == null) { throw new ArgumentNullException(nameof(oldNodes)); } if (newNode == null) { throw new ArgumentNullException(nameof(newNode)); } if (oldNodes.Count == 0) { throw new ArgumentException(nameof(oldNodes)); } var newRoot = root.TrackNodes(oldNodes); var first = newRoot.GetCurrentNode(oldNodes[0]); newRoot = newRoot.ReplaceNode(first, newNode); var toRemove = oldNodes.Skip(1).Select(newRoot.GetCurrentNode); newRoot = newRoot.RemoveNodes(toRemove, SyntaxRemoveOptions.KeepNoTrivia); return newRoot; } public static TextSpan GetSpanOfAssignmentDependenciesInSpan(this MemberDeclarationSyntax containingMethod, TextSpan textSpan, SemanticModel model, CancellationToken cancellationToken = default(CancellationToken)) { var resultSpan = textSpan; List<SyntaxNode> dependentAssignments = new List<SyntaxNode>(); var tokenKeyComparer = Comparer<int>.Default; do { SyntaxNode[] assignments = containingMethod.DescendantNodes(resultSpan) .Where(e => (e is AssignmentExpressionSyntax || e is EqualsValueClauseSyntax) && !dependentAssignments.Contains(e)).ToArray(); if (!assignments.Any()) // no newly found assignments, done { break; } dependentAssignments.AddRange(assignments); IEnumerable<ISymbol> symbolsAssigned = dependentAssignments.Select(e => GetAssignmentSymbol(e, model, cancellationToken)); SortedSet<SyntaxToken> references = new SortedSet<SyntaxToken>(Comparer<SyntaxToken>.Create((token, syntaxToken) => tokenKeyComparer.Compare( token.SpanStart, syntaxToken.SpanStart))); foreach (ISymbol symbol in symbolsAssigned) { var symbolReferences = GetSymbolReferences(containingMethod, symbol) .Where(e => e.SpanStart >= textSpan.Start); references.UnionWith(symbolReferences); } resultSpan = GetBoundingSpan(references); } while (true); return resultSpan; } public static TextSpan GetSpanOfAssignmentDependenciesAndDeclarationsInSpan(this MemberDeclarationSyntax containingMethod, TextSpan textSpan, SemanticModel model, CancellationToken cancellationToken = default(CancellationToken)) { var resultSpan = textSpan; List<SyntaxNode> dependentAssignments = new List<SyntaxNode>(); var tokenKeyComparer = Comparer<int>.Default; do { SyntaxNode[] assignments = containingMethod.DescendantNodes(resultSpan) .Where(e => (e is AssignmentExpressionSyntax || e is EqualsValueClauseSyntax) && !dependentAssignments.Contains(e)).ToArray(); if (!assignments.Any()) // no newly found assignments, done { break; } dependentAssignments.AddRange(assignments); IEnumerable<ISymbol> symbolsAssigned = dependentAssignments.Select(e => GetAssignmentSymbol(e, model, cancellationToken)); SortedSet<SyntaxToken> references = new SortedSet<SyntaxToken>(Comparer<SyntaxToken>.Create((token, syntaxToken) => tokenKeyComparer.Compare( token.SpanStart, syntaxToken.SpanStart))); foreach (ISymbol symbol in symbolsAssigned) { var symbolReferences = GetSymbolReferences(containingMethod, symbol); references.UnionWith(symbolReferences); } resultSpan = GetBoundingSpan(references); } while (true); return resultSpan; } public static string GetSpanText(this Location location) { if (location == null) { throw new ArgumentNullException(nameof(location)); } if (location == Location.None || location.SourceTree == null || location.SourceSpan.IsEmpty) { throw new ArgumentException(nameof(location)); } return location.SourceTree.ToString().Substring(location.SourceSpan.Start, location.SourceSpan.Length); } public static TextSpan GetBoundingSpan(this IEnumerable<SyntaxToken> symbolReferences) { var locations = symbolReferences .Select(token => token.GetAncestorStatement().GetLocation()) // ancestor statement or entire line? .OrderBy(e => e.SourceSpan.Start); return GetBoundingSpan(locations); } public static TextSpan GetBoundingSpan(this IOrderedEnumerable<Location> locations) { return new TextSpan(locations.First().SourceSpan.Start, locations.Last().SourceSpan.End - locations.First().SourceSpan.Start + 1); } public static IEnumerable<SyntaxToken> GetSymbolReferences(this MemberDeclarationSyntax containingMethod, ISymbol symbol) { return containingMethod .DescendantTokens() .Where(e => e.Kind() == SyntaxKind.IdentifierToken && e.ValueText == symbol.Name); } public static MemberDeclarationSyntax GetContainingMemberDeclaration(this SyntaxNode invocationParent) { var parentMethod = invocationParent; while (parentMethod != null && !(parentMethod is MemberDeclarationSyntax)) { parentMethod = parentMethod.Parent; } var containingMethod = parentMethod as MemberDeclarationSyntax; if(containingMethod == null) { throw new InvalidOperationException(); } return containingMethod; } public static ISymbol GetAssignmentSymbol(this SyntaxNode parent, SemanticModel model, CancellationToken cancellationToken = default(CancellationToken)) { while (true) { var localDeclaration = parent as LocalDeclarationStatementSyntax; if (localDeclaration != null) { parent = localDeclaration.Declaration.Variables.First().Initializer; continue; } var memberAccess = parent as MemberAccessExpressionSyntax; if (memberAccess != null) { parent = parent.Parent.Parent; continue; } var awaitExpression = parent as AwaitExpressionSyntax; if (awaitExpression != null) { parent = parent.Parent; continue; } var simpleAssignment = parent as AssignmentExpressionSyntax; ISymbol symbol = null; if (simpleAssignment != null) { ExpressionSyntax variable = simpleAssignment.Left; symbol = model.GetSymbolInfo(variable, cancellationToken).Symbol; } else { var equalsValueClause = parent as EqualsValueClauseSyntax; var variableDeclarator = equalsValueClause?.Parent as VariableDeclaratorSyntax; if (variableDeclarator != null) { symbol = model.GetDeclaredSymbol(variableDeclarator, cancellationToken); } } return symbol; } } public static SyntaxToken GetAssignmentToken(this SyntaxNode parent) { while (true) { var localDeclaration = parent as LocalDeclarationStatementSyntax; if (localDeclaration != null) { return localDeclaration.Declaration.Variables.First().Identifier; } var memberAccess = parent as MemberAccessExpressionSyntax; if (memberAccess != null) { parent = parent.Parent.Parent; continue; } var awaitExpression = parent as AwaitExpressionSyntax; if (awaitExpression != null) { parent = parent.Parent; continue; } var simpleAssignment = parent as AssignmentExpressionSyntax; if (simpleAssignment != null) { // TODO: support AssignmentExpressionSyntax in GetAssignmentToken var xxx = simpleAssignment.Left; throw new NotImplementedException(); } else { var equalsValueClause = parent as EqualsValueClauseSyntax; var variableDeclarator = equalsValueClause?.Parent as VariableDeclaratorSyntax; return variableDeclarator?.Identifier ?? default(SyntaxToken); } } } public static SyntaxNode TryCatchSafe(this SyntaxNode subjectStatement, Dictionary<string, TypeSyntax> exceptionArgumentsInfo, Func<IdentifierNameSyntax, SyntaxList<StatementSyntax>> generateCatchStatement, SyntaxNode root, SemanticModel model, CancellationToken cancellationToken = default(CancellationToken)) { return TryCatchFinallySafe(subjectStatement, exceptionArgumentsInfo, generateCatchStatement, root, model, default(FinallyClauseSyntax), cancellationToken); } public static SyntaxNode TryCatchFinallySafe(this SyntaxNode subjectStatement, Dictionary<string, TypeSyntax> exceptionArgumentsInfo, Func<IdentifierNameSyntax, SyntaxList<StatementSyntax>> generateCatchStatement, SyntaxNode root, SemanticModel model, FinallyClauseSyntax finallyClauseSyntax, CancellationToken cancellationToken = default(CancellationToken)) { var containingMethod = subjectStatement.GetContainingMemberDeclaration(); var tryTextSpan = containingMethod.GetSpanOfAssignmentDependenciesInSpan( subjectStatement.FullSpan, model, cancellationToken); var tryBlockStatements = containingMethod.SyntaxTree .GetRoot(cancellationToken).DescendantNodes() .Where(x => tryTextSpan.Contains(x.Span)) .OfType<StatementSyntax>().ToArray(); var catchClauses = exceptionArgumentsInfo.Select(i => { var exceptionArgumentIdentifierName = SyntaxFactory.IdentifierName(i.Key); return SyntaxFactory.CatchClause() .WithDeclaration( SyntaxFactory.CatchDeclaration(i.Value) .WithIdentifier(exceptionArgumentIdentifierName.Identifier)) .WithBlock(SyntaxFactory.Block(generateCatchStatement(exceptionArgumentIdentifierName)) ); }); var tryStatement = SyntaxFactory.TryStatement( SyntaxFactory.Block(SyntaxFactory.List(tryBlockStatements)), SyntaxFactory.List(catchClauses), finallyClauseSyntax) .WithAdditionalAnnotations(Formatter.Annotation); var newMethod = containingMethod.ReplaceNodes(tryBlockStatements.ToImmutableList(), tryStatement); var compilationUnitSyntax = (CompilationUnitSyntax) root.ReplaceNode(containingMethod, newMethod); var usings = compilationUnitSyntax.Usings; if (!usings.Any(e => e.Name.ToString().Equals(typeof(Task).Namespace))) { var usingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(typeof(Task).Namespace)); compilationUnitSyntax = compilationUnitSyntax.AddUsings(usingDirective); } if (!usings.Any(e => e.Name.ToString().Equals(typeof(Debug).Namespace))) { var usingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(typeof(Debug).Namespace)); compilationUnitSyntax = compilationUnitSyntax.AddUsings(usingDirective); } return compilationUnitSyntax; } public static TypeSyntax ToTypeSyntax(this INamedTypeSymbol namedTypeSymbol, SyntaxGenerator generator) { if(namedTypeSymbol.IsGenericType) { return SyntaxFactory.GenericName(namedTypeSymbol.Name) .WithTypeArgumentList( SyntaxFactory.TypeArgumentList( SyntaxFactory.SeparatedList( namedTypeSymbol.ConstructedFrom.TypeArguments .Select(e => (TypeSyntax) generator.TypeExpression(e))))); } return SyntaxFactory.ParseTypeName(namedTypeSymbol.Name); } public static IEnumerable<TypeParameterConstraintSyntax> GetTypeParameterConstraints( this ITypeParameterSymbol typeParameterSymbol, SyntaxGenerator generator) { foreach (var type in typeParameterSymbol.ConstraintTypes) yield return SyntaxFactory.TypeConstraint((TypeSyntax) generator.TypeExpression(type)); if (typeParameterSymbol.HasConstructorConstraint) { yield return SyntaxFactory.ConstructorConstraint(); } if (typeParameterSymbol.HasReferenceTypeConstraint) { yield return SyntaxFactory.ClassOrStructConstraint(SyntaxKind.ClassConstraint); } if (typeParameterSymbol.HasValueTypeConstraint) { yield return SyntaxFactory.ClassOrStructConstraint(SyntaxKind.StructConstraint); } } public static MethodDeclarationSyntax WithoutAsync(this MethodDeclarationSyntax method) { var genericName = method.ReturnType as GenericNameSyntax; // if not generic type is either void or Task, in either case switch to void. method = method.WithReturnType(genericName != null ? genericName.TypeArgumentList.Arguments[0] : SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.VoidKeyword))); return method.WithModifiers( method.Modifiers.Remove( method.Modifiers.Single(e => e.IsKind(SyntaxKind.AsyncKeyword)))); } public static bool IsGenericOfType(this SyntaxNode node, Type type, SemanticModel semanticModel) { if (node == null) { throw new ArgumentNullException(nameof(node)); } if (type == null) { throw new ArgumentNullException(nameof(type)); } if (semanticModel == null) { throw new ArgumentNullException(nameof(semanticModel)); } if (!(node is TypeArgumentListSyntax)) { return false; } SyntaxNode genericNameSyntax = null; if (node.Parent is GenericNameSyntax) { genericNameSyntax = node.Parent; } else if (node.Parent.Parent is GenericNameSyntax) { genericNameSyntax = node.Parent.Parent; } var simpleBaseTypeSyntax = genericNameSyntax?.Parent as SimpleBaseTypeSyntax; if (simpleBaseTypeSyntax == null || !(genericNameSyntax.Parent.Parent is BaseListSyntax)) { return false; } var containingGeneric = simpleBaseTypeSyntax.Type as GenericNameSyntax; return containingGeneric != null && containingGeneric.IsConstructedGenericOf(type, semanticModel); } public static bool IsTypeArgumentToMethod(this SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken, IEnumerable<MethodInfo> methodInfos) { if (methodInfos == null) { return false; } if (!(node is TypeArgumentListSyntax)) { return false; } if (!(node.Parent.Parent is MemberAccessExpressionSyntax)) { return false; } if (!(node.Parent is GenericNameSyntax)) { return false; } var methodInfoArray = methodInfos as MethodInfo[] ?? methodInfos.ToArray(); if (methodInfoArray.All(e => e.Name != ((GenericNameSyntax) node.Parent).Identifier.Text)) { return false; } return methodInfoArray.Any( methodInfo => ((InvocationExpressionSyntax) node.Parent.Parent.Parent).ArgumentList.Arguments[0].Expression.IsArgumentToMethod( semanticModel, cancellationToken, methodInfo)); } public static bool IsArgumentToMethod(this SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken, IEnumerable<MethodInfo> methodInfos) { return methodInfos.Any(methodInfo => node.IsArgumentToMethod(semanticModel, cancellationToken, methodInfo)); } public static bool IsArgumentToMethod(this SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken, MethodInfo methodInfo) { if (!(node is ObjectCreationExpressionSyntax) && !(node is IdentifierNameSyntax) && !(node is ArgumentSyntax)) { return false; } var argument = node as ArgumentSyntax ?? node.Parent as ArgumentSyntax; var argumentList = argument?.Parent as ArgumentListSyntax; var invocationExpression = argumentList?.Parent as InvocationExpressionSyntax; if (invocationExpression == null) { return false; } return invocationExpression.IsInvocationOfMethod( methodInfo, semanticModel, cancellationToken); } public static bool IsImplementationOf(this IMethodSymbol methodSymbol, MethodInfo methodInfo) { return methodSymbol.ContainingType.ImplementsInterface(methodInfo.DeclaringType) && methodSymbol.Parameters.Length == methodInfo.GetParameters().Length && methodSymbol.Name == methodInfo.Name; } public static IEnumerable<AssignmentExpressionSyntax> Assignments(this MethodDeclarationSyntax methodDeclaration) { return methodDeclaration .Body .DescendantNodes() .OfType<AssignmentExpressionSyntax>(); ; } public static IEnumerable<InvocationExpressionSyntax> Invocations(this MethodDeclarationSyntax methodDeclaration) { return methodDeclaration .Body .Statements .OfType<ExpressionStatementSyntax>() .Where(e => e.Expression.Kind() == SyntaxKind.InvocationExpression) .Select(e => (InvocationExpressionSyntax) e.Expression); } public static bool Invokes(this MethodDeclarationSyntax methodDeclaration, MethodInfo methodInfo, SemanticModel semanticModel, CancellationToken cancellationToken) { return methodDeclaration.Invocations() .Any(e => e.IsInvocationOfMethod(methodInfo, semanticModel, cancellationToken)); } public static bool IsCommandMessageType(this INamedTypeSymbol symbol) { return symbol != null && symbol.Name.StartsWith(Utilities.CommandMessageClassSuffix, StringComparison.Ordinal); } public static SimpleNameSyntax MemberName(this InvocationExpressionSyntax node) { var memberAccessExpression = node.Expression as MemberAccessExpressionSyntax; if (memberAccessExpression != null) { return memberAccessExpression.Name; } var memberBindingExpression = node.Expression as MemberBindingExpressionSyntax; if (memberBindingExpression != null) { return memberBindingExpression.Name; } return default(SimpleNameSyntax); } private static bool IsInvocationImpl(InvocationExpressionSyntax node, SemanticModel semanticModel, Func<SimpleNameSyntax, SemanticModel, CancellationToken, bool> predicate, CancellationToken cancellationToken) { var name = MemberName(node); return name != null && predicate(name, semanticModel, cancellationToken); } public static bool IsInvocationOfMethod(this InvocationExpressionSyntax invocationExpression, IEnumerable<MethodInfo> methodInfos, SemanticModel semanticModel, CancellationToken cancellationToken) { return methodInfos.Any(m => invocationExpression.IsInvocationOfMethod(m, semanticModel, cancellationToken)); } public static bool IsInvocationOfMethod(this InvocationExpressionSyntax invocationExpression, MethodInfo methodInfo, SemanticModel semanticModel, CancellationToken cancellationToken) { return IsInvocationImpl(invocationExpression, semanticModel, (name, model, c) => Utilities.IsMember(name, methodInfo, model, c), cancellationToken); } public static bool IsInvocationOfPublish(this InvocationExpressionSyntax node, SemanticModel semanticModel, CancellationToken cancellationToken) { return IsInvocationImpl(node, semanticModel, Utilities.IsPublish, cancellationToken); } public static bool IsInvocationOfSend(this InvocationExpressionSyntax node, SemanticModel semanticModel, CancellationToken cancellationToken) { return IsInvocationImpl(node, semanticModel, Utilities.IsSend, cancellationToken); } public static bool IsInvocationOfHandle(this InvocationExpressionSyntax node, SemanticModel semanticModel, CancellationToken cancellationToken) { return IsInvocationImpl(node, semanticModel, Utilities.IsHandle, cancellationToken); } public static bool IsConstructedGenericOf(this GenericNameSyntax typeSyntax, Type type, SemanticModel semanticModel) { var symbolInfo = semanticModel.GetSymbolInfo(typeSyntax); var typeSymbol = symbolInfo.Symbol as ITypeSymbol; if (typeSymbol != null) { return typeSymbol.IsOfType(type); } return false; } public static string GetFullNamespaceName(this INamespaceSymbol @namespace) { return @namespace.ToString(); } public static SyntaxToken GetIdentifier(this MemberDeclarationSyntax memberDeclarationSyntax) { var method = memberDeclarationSyntax as MethodDeclarationSyntax; if (method != null) return method.Identifier; var @delegate = memberDeclarationSyntax as DelegateDeclarationSyntax; if (@delegate != null) return @delegate.Identifier; var type = memberDeclarationSyntax as TypeDeclarationSyntax; if (type != null) return type.Identifier; var constructor = memberDeclarationSyntax as ConstructorDeclarationSyntax; if (constructor != null) return constructor.Identifier; var enumMember = memberDeclarationSyntax as EnumMemberDeclarationSyntax; if (enumMember != null) return enumMember.Identifier; return default(SyntaxToken); } public static Document ReplaceNode(this Document document, SyntaxNode original, SyntaxNode replacement, out SyntaxNode root, out SemanticModel model) { var currentRoot = document.GetSyntaxRootAsync().Result; var newRoot = currentRoot.ReplaceNode(original, replacement); var newDocument = document.WithSyntaxRoot(newRoot); root = newDocument.GetSyntaxRootAsync().Result; model = newDocument.GetSemanticModelAsync().Result; return newDocument; } public static bool ImplementsInterface(this ITypeSymbol typeSymbol, Type type) { if (!type.GetTypeInfo().IsInterface) { throw new ArgumentException("Type is not an interface", nameof(typeSymbol)); } if (typeSymbol.Interfaces.Concat(new[] {typeSymbol}) .Any(e => e.IsOfType(type))) { return true; } return typeSymbol.AllInterfaces.Concat(new[] {typeSymbol}) .Any(e => e.IsOfType(type)); } public static bool ImplementsInterface<TInterface>(this ITypeSymbol typeSymbol) { return ImplementsInterface(typeSymbol, typeof(TInterface)); } public static bool IsOfType<T>(this ITypeSymbol typeSymbol) { return IsOfType(typeSymbol, typeof(T)); } public static bool IsOfType(this ITypeSymbol typeSymbol, Type type) { if (type.GetTypeInfo().IsGenericTypeDefinition) { return $"{typeSymbol.ContainingNamespace}.{typeSymbol.OriginalDefinition.MetadataName}, {typeSymbol.ContainingAssembly.Identity}" == type.AssemblyQualifiedName; } return typeSymbol.ToString() == type.FullName && $"{typeSymbol}, {typeSymbol.ContainingAssembly.Identity}" == type.AssemblyQualifiedName; } #if SUPPORT_MP0100 /// <summary> /// Create a new MethodDeclaration that returns Task or Task{T} and has async modifier. /// </summary> /// <param name="originalMethod"></param> /// <param name="method"></param> /// <param name="model"></param> /// <returns></returns> public static MethodDeclarationSyntax WithAsync(this MethodDeclarationSyntax originalMethod, MethodDeclarationSyntax method, SemanticModel model) { if (!originalMethod.ReturnType.ToDisplayString(model).StartsWith($"{typeof(Task)}", StringComparison.Ordinal)) { var returnType = method.ReturnType.ToString(); method = method. WithReturnType(SyntaxFactory.ParseTypeName( returnType == "void" ? "Task" : $"Task<{returnType}>") .WithTrailingTrivia(originalMethod.ReturnType.GetTrailingTrivia()) ); } return method .WithModifiers(method.Modifiers.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword))) .WithAdditionalAnnotations(Formatter.Annotation); } public static MethodDeclarationSyntax GetContainingMethodDeclaration(SyntaxNode invocation) { return invocation.Ancestors().OfType<MethodDeclarationSyntax>().FirstOrDefault(); } #endif } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Xml; using Orleans.MultiCluster; using Orleans.Runtime.Configuration; using Orleans.Runtime.MembershipService; using Orleans.Runtime.MultiClusterNetwork; using Orleans.Versions; using Orleans.Versions.Compatibility; using Orleans.Versions.Selector; namespace Orleans.Runtime.Management { /// <summary> /// Implementation class for the Orleans management grain. /// </summary> [OneInstancePerCluster] internal class ManagementGrain : Grain, IManagementGrain { private readonly GlobalConfiguration globalConfig; private readonly IMultiClusterOracle multiClusterOracle; private readonly IInternalGrainFactory internalGrainFactory; private readonly ISiloStatusOracle siloStatusOracle; private readonly MembershipTableFactory membershipTableFactory; private readonly GrainTypeManager grainTypeManager; private readonly IVersionStore versionStore; private Logger logger; public ManagementGrain( GlobalConfiguration globalConfig, IMultiClusterOracle multiClusterOracle, IInternalGrainFactory internalGrainFactory, ISiloStatusOracle siloStatusOracle, MembershipTableFactory membershipTableFactory, GrainTypeManager grainTypeManager, IVersionStore versionStore) { this.globalConfig = globalConfig; this.multiClusterOracle = multiClusterOracle; this.internalGrainFactory = internalGrainFactory; this.siloStatusOracle = siloStatusOracle; this.membershipTableFactory = membershipTableFactory; this.grainTypeManager = grainTypeManager; this.versionStore = versionStore; } public override Task OnActivateAsync() { logger = LogManager.GetLogger("ManagementGrain", LoggerType.Runtime); return Task.CompletedTask; } public async Task<Dictionary<SiloAddress, SiloStatus>> GetHosts(bool onlyActive = false) { // If the status oracle isn't MembershipOracle, then it is assumed that it does not use IMembershipTable. // In that event, return the approximate silo statuses from the status oracle. if (!(this.siloStatusOracle is MembershipOracle)) return this.siloStatusOracle.GetApproximateSiloStatuses(onlyActive); // Explicitly read the membership table and return the results. var table = await GetMembershipTable(); var members = await table.ReadAll(); var results = onlyActive ? members.Members.Where(item => item.Item1.Status == SiloStatus.Active) : members.Members; return results.ToDictionary(item => item.Item1.SiloAddress, item => item.Item1.Status); } public async Task<MembershipEntry[]> GetDetailedHosts(bool onlyActive = false) { logger.Info("GetDetailedHosts onlyActive={0}", onlyActive); var mTable = await GetMembershipTable(); var table = await mTable.ReadAll(); if (onlyActive) { return table.Members .Where(item => item.Item1.Status == SiloStatus.Active) .Select(x => x.Item1) .ToArray(); } return table.Members .Select(x => x.Item1) .ToArray(); } public Task SetSystemLogLevel(SiloAddress[] siloAddresses, int traceLevel) { var silos = GetSiloAddresses(siloAddresses); logger.Info("SetSystemTraceLevel={1} {0}", Utils.EnumerableToString(silos), traceLevel); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).SetSystemLogLevel(traceLevel)); return Task.WhenAll(actionPromises); } public Task SetAppLogLevel(SiloAddress[] siloAddresses, int traceLevel) { var silos = GetSiloAddresses(siloAddresses); logger.Info("SetAppTraceLevel={1} {0}", Utils.EnumerableToString(silos), traceLevel); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).SetAppLogLevel(traceLevel)); return Task.WhenAll(actionPromises); } public Task SetLogLevel(SiloAddress[] siloAddresses, string logName, int traceLevel) { var silos = GetSiloAddresses(siloAddresses); logger.Info("SetLogLevel[{1}]={2} {0}", Utils.EnumerableToString(silos), logName, traceLevel); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).SetLogLevel(logName, traceLevel)); return Task.WhenAll(actionPromises); } public Task ForceGarbageCollection(SiloAddress[] siloAddresses) { var silos = GetSiloAddresses(siloAddresses); logger.Info("Forcing garbage collection on {0}", Utils.EnumerableToString(silos)); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).ForceGarbageCollection()); return Task.WhenAll(actionPromises); } public Task ForceActivationCollection(SiloAddress[] siloAddresses, TimeSpan ageLimit) { var silos = GetSiloAddresses(siloAddresses); return Task.WhenAll(GetSiloAddresses(silos).Select(s => GetSiloControlReference(s).ForceActivationCollection(ageLimit))); } public async Task ForceActivationCollection(TimeSpan ageLimit) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); SiloAddress[] silos = hosts.Keys.ToArray(); await ForceActivationCollection(silos, ageLimit); } public Task ForceRuntimeStatisticsCollection(SiloAddress[] siloAddresses) { var silos = GetSiloAddresses(siloAddresses); logger.Info("Forcing runtime statistics collection on {0}", Utils.EnumerableToString(silos)); List<Task> actionPromises = PerformPerSiloAction( silos, s => GetSiloControlReference(s).ForceRuntimeStatisticsCollection()); return Task.WhenAll(actionPromises); } public Task<SiloRuntimeStatistics[]> GetRuntimeStatistics(SiloAddress[] siloAddresses) { var silos = GetSiloAddresses(siloAddresses); if (logger.IsVerbose) logger.Verbose("GetRuntimeStatistics on {0}", Utils.EnumerableToString(silos)); var promises = new List<Task<SiloRuntimeStatistics>>(); foreach (SiloAddress siloAddress in silos) promises.Add(GetSiloControlReference(siloAddress).GetRuntimeStatistics()); return Task.WhenAll(promises); } public async Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics(SiloAddress[] hostsIds) { var all = GetSiloAddresses(hostsIds).Select(s => GetSiloControlReference(s).GetSimpleGrainStatistics()).ToList(); await Task.WhenAll(all); return all.SelectMany(s => s.Result).ToArray(); } public async Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics() { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); SiloAddress[] silos = hosts.Keys.ToArray(); return await GetSimpleGrainStatistics(silos); } public async Task<DetailedGrainStatistic[]> GetDetailedGrainStatistics(string[] types = null, SiloAddress[] hostsIds = null) { if (hostsIds == null) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); hostsIds = hosts.Keys.ToArray(); } var all = GetSiloAddresses(hostsIds).Select(s => GetSiloControlReference(s).GetDetailedGrainStatistics(types)).ToList(); await Task.WhenAll(all); return all.SelectMany(s => s.Result).ToArray(); } public async Task<int> GetGrainActivationCount(GrainReference grainReference) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); List<SiloAddress> hostsIds = hosts.Keys.ToList(); var tasks = new List<Task<DetailedGrainReport>>(); foreach (var silo in hostsIds) tasks.Add(GetSiloControlReference(silo).GetDetailedGrainReport(grainReference.GrainId)); await Task.WhenAll(tasks); return tasks.Select(s => s.Result).Select(r => r.LocalActivations.Count).Sum(); } public async Task UpdateConfiguration(SiloAddress[] hostIds, Dictionary<string, string> configuration, Dictionary<string, string> tracing) { var global = new[] { "Globals/", "/Globals/", "OrleansConfiguration/Globals/", "/OrleansConfiguration/Globals/" }; if (hostIds != null && configuration.Keys.Any(k => global.Any(k.StartsWith))) throw new ArgumentException("Must update global configuration settings on all silos"); var silos = GetSiloAddresses(hostIds); if (silos.Length == 0) return; var document = XPathValuesToXml(configuration); if (tracing != null) { AddXPathValue(document, new[] { "OrleansConfiguration", "Defaults", "Tracing" }, null); var parent = document["OrleansConfiguration"]["Defaults"]["Tracing"]; foreach (var trace in tracing) { var child = document.CreateElement("TraceLevelOverride"); child.SetAttribute("LogPrefix", trace.Key); child.SetAttribute("TraceLevel", trace.Value); parent.AppendChild(child); } } using(var sw = new StringWriter()) { using(var xw = XmlWriter.Create(sw)) { document.WriteTo(xw); xw.Flush(); var xml = sw.ToString(); // do first one, then all the rest to avoid spamming all the silos in case of a parameter error await GetSiloControlReference(silos[0]).UpdateConfiguration(xml); await Task.WhenAll(silos.Skip(1).Select(s => GetSiloControlReference(s).UpdateConfiguration(xml))); } } } public async Task UpdateStreamProviders(SiloAddress[] hostIds, IDictionary<string, ProviderCategoryConfiguration> streamProviderConfigurations) { SiloAddress[] silos = GetSiloAddresses(hostIds); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).UpdateStreamProviders(streamProviderConfigurations)); await Task.WhenAll(actionPromises); } public async Task<string[]> GetActiveGrainTypes(SiloAddress[] hostsIds=null) { if (hostsIds == null) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); SiloAddress[] silos = hosts.Keys.ToArray(); } var all = GetSiloAddresses(hostsIds).Select(s => GetSiloControlReference(s).GetGrainTypeList()).ToArray(); await Task.WhenAll(all); return all.SelectMany(s => s.Result).Distinct().ToArray(); } public async Task SetCompatibilityStrategy(CompatibilityStrategy strategy) { await SetStrategy( store => store.SetCompatibilityStrategy(strategy), siloControl => siloControl.SetCompatibilityStrategy(strategy)); } public async Task SetSelectorStrategy(VersionSelectorStrategy strategy) { await SetStrategy( store => store.SetSelectorStrategy(strategy), siloControl => siloControl.SetSelectorStrategy(strategy)); } public async Task SetCompatibilityStrategy(int interfaceId, CompatibilityStrategy strategy) { CheckIfIsExistingInterface(interfaceId); await SetStrategy( store => store.SetCompatibilityStrategy(interfaceId, strategy), siloControl => siloControl.SetCompatibilityStrategy(interfaceId, strategy)); } public async Task SetSelectorStrategy(int interfaceId, VersionSelectorStrategy strategy) { CheckIfIsExistingInterface(interfaceId); await SetStrategy( store => store.SetSelectorStrategy(interfaceId, strategy), siloControl => siloControl.SetSelectorStrategy(interfaceId, strategy)); } public async Task<int> GetTotalActivationCount() { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); List<SiloAddress> silos = hosts.Keys.ToList(); var tasks = new List<Task<int>>(); foreach (var silo in silos) tasks.Add(GetSiloControlReference(silo).GetActivationCount()); await Task.WhenAll(tasks); int sum = 0; foreach (Task<int> task in tasks) sum += task.Result; return sum; } public Task<object[]> SendControlCommandToProvider(string providerTypeFullName, string providerName, int command, object arg) { return ExecutePerSiloCall(isc => isc.SendControlCommandToProvider(providerTypeFullName, providerName, command, arg), String.Format("SendControlCommandToProvider of type {0} and name {1} command {2}.", providerTypeFullName, providerName, command)); } private void CheckIfIsExistingInterface(int interfaceId) { Type unused; var interfaceMap = this.grainTypeManager.ClusterGrainInterfaceMap; if (!interfaceMap.TryGetServiceInterface(interfaceId, out unused)) { throw new ArgumentException($"Interface code '{interfaceId} not found", nameof(interfaceId)); } } private async Task SetStrategy(Func<IVersionStore, Task> storeFunc, Func<ISiloControl, Task> applyFunc) { await storeFunc(versionStore); var silos = GetSiloAddresses(null); var actionPromises = PerformPerSiloAction( silos, s => applyFunc(GetSiloControlReference(s))); try { await Task.WhenAll(actionPromises); } catch (Exception) { // ignored: silos that failed to set the new strategy will reload it from the storage // in the future. } } private async Task<object[]> ExecutePerSiloCall(Func<ISiloControl, Task<object>> action, string actionToLog) { var silos = await GetHosts(true); if(logger.IsVerbose) { logger.Verbose("Executing {0} against {1}", actionToLog, Utils.EnumerableToString(silos.Keys)); } var actionPromises = new List<Task<object>>(); foreach (SiloAddress siloAddress in silos.Keys.ToArray()) actionPromises.Add(action(GetSiloControlReference(siloAddress))); return await Task.WhenAll(actionPromises); } private Task<IMembershipTable> GetMembershipTable() { if (!(this.siloStatusOracle is MembershipOracle)) throw new InvalidOperationException("The current membership oracle does not support detailed silo status reporting."); return this.membershipTableFactory.GetMembershipTable(); } private SiloAddress[] GetSiloAddresses(SiloAddress[] silos) { if (silos != null && silos.Length > 0) return silos; return this.siloStatusOracle .GetApproximateSiloStatuses(true).Select(s => s.Key).ToArray(); } /// <summary> /// Perform an action for each silo. /// </summary> /// <remarks> /// Because SiloControl contains a reference to a system target, each method call using that reference /// will get routed either locally or remotely to the appropriate silo instance auto-magically. /// </remarks> /// <param name="siloAddresses">List of silos to perform the action for</param> /// <param name="perSiloAction">The action functiona to be performed for each silo</param> /// <returns>Array containing one Task for each silo the action was performed for</returns> private List<Task> PerformPerSiloAction(SiloAddress[] siloAddresses, Func<SiloAddress, Task> perSiloAction) { var requestsToSilos = new List<Task>(); foreach (SiloAddress siloAddress in siloAddresses) requestsToSilos.Add( perSiloAction(siloAddress) ); return requestsToSilos; } private static XmlDocument XPathValuesToXml(Dictionary<string,string> values) { var doc = new XmlDocument(); if (values == null) return doc; foreach (var p in values) { var path = p.Key.Split('/').ToList(); if (path[0] == "") path.RemoveAt(0); if (path[0] != "OrleansConfiguration") path.Insert(0, "OrleansConfiguration"); if (!path[path.Count - 1].StartsWith("@")) throw new ArgumentException("XPath " + p.Key + " must end with @attribute"); AddXPathValue(doc, path, p.Value); } return doc; } private static void AddXPathValue(XmlNode xml, IEnumerable<string> path, string value) { if (path == null) return; var first = path.FirstOrDefault(); if (first == null) return; if (first.StartsWith("@")) { first = first.Substring(1); if (path.Count() != 1) throw new ArgumentException("Attribute " + first + " must be last in path"); var e = xml as XmlElement; if (e == null) throw new ArgumentException("Attribute " + first + " must be on XML element"); e.SetAttribute(first, value); return; } foreach (var child in xml.ChildNodes) { var e = child as XmlElement; if (e != null && e.LocalName == first) { AddXPathValue(e, path.Skip(1), value); return; } } var empty = (xml as XmlDocument ?? xml.OwnerDocument).CreateElement(first); xml.AppendChild(empty); AddXPathValue(empty, path.Skip(1), value); } private ISiloControl GetSiloControlReference(SiloAddress silo) { return this.internalGrainFactory.GetSystemTarget<ISiloControl>(Constants.SiloControlId, silo); } #region MultiCluster private IMultiClusterOracle GetMultiClusterOracle() { if (!this.globalConfig.HasMultiClusterNetwork) throw new OrleansException("No multicluster network configured"); return this.multiClusterOracle; } public Task<List<IMultiClusterGatewayInfo>> GetMultiClusterGateways() { return Task.FromResult(GetMultiClusterOracle().GetGateways().Cast<IMultiClusterGatewayInfo>().ToList()); } public Task<MultiClusterConfiguration> GetMultiClusterConfiguration() { return Task.FromResult(GetMultiClusterOracle().GetMultiClusterConfiguration()); } public async Task<MultiClusterConfiguration> InjectMultiClusterConfiguration(IEnumerable<string> clusters, string comment = "", bool checkForLaggingSilosFirst = true) { var multiClusterOracle = GetMultiClusterOracle(); var configuration = new MultiClusterConfiguration(DateTime.UtcNow, clusters.ToList(), comment); if (!MultiClusterConfiguration.OlderThan(multiClusterOracle.GetMultiClusterConfiguration(), configuration)) throw new OrleansException("Could not inject multi-cluster configuration: current configuration is newer than clock"); if (checkForLaggingSilosFirst) { try { var laggingSilos = await multiClusterOracle.FindLaggingSilos(multiClusterOracle.GetMultiClusterConfiguration()); if (laggingSilos.Count > 0) { var msg = string.Format("Found unstable silos {0}", string.Join(",", laggingSilos)); throw new OrleansException(msg); } } catch (Exception e) { throw new OrleansException("Could not inject multi-cluster configuration: stability check failed", e); } } await multiClusterOracle.InjectMultiClusterConfiguration(configuration); return configuration; } public Task<List<SiloAddress>> FindLaggingSilos() { var multiClusterOracle = GetMultiClusterOracle(); var expected = multiClusterOracle.GetMultiClusterConfiguration(); return multiClusterOracle.FindLaggingSilos(expected); } #endregion } }
/* * Copyright (c) 2007, Second Life Reverse Engineering Team * 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 Second Life Reverse Engineering Team 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; namespace libsecondlife { public class CoordinateFrame { public static readonly LLVector3 X_AXIS = new LLVector3(1f, 0f, 0f); public static readonly LLVector3 Y_AXIS = new LLVector3(0f, 1f, 0f); public static readonly LLVector3 Z_AXIS = new LLVector3(0f, 0f, 1f); /// <summary>Origin position of this coordinate frame</summary> public LLVector3 Origin { get { return origin; } set { if (!value.IsFinite()) throw new ArgumentException("Non-finite in CoordinateFrame.Origin assignment"); origin = value; } } /// <summary>X axis of this coordinate frame, or Forward/At in Second Life terms</summary> public LLVector3 XAxis { get { return xAxis; } set { if (!value.IsFinite()) throw new ArgumentException("Non-finite in CoordinateFrame.XAxis assignment"); xAxis = value; } } /// <summary>Y axis of this coordinate frame, or Left in Second Life terms</summary> public LLVector3 YAxis { get { return yAxis; } set { if (!value.IsFinite()) throw new ArgumentException("Non-finite in CoordinateFrame.YAxis assignment"); yAxis = value; } } /// <summary>Z axis of this coordinate frame, or Up in Second Life terms</summary> public LLVector3 ZAxis { get { return zAxis; } set { if (!value.IsFinite()) throw new ArgumentException("Non-finite in CoordinateFrame.ZAxis assignment"); zAxis = value; } } protected LLVector3 origin; protected LLVector3 xAxis; protected LLVector3 yAxis; protected LLVector3 zAxis; #region Constructors public CoordinateFrame(LLVector3 origin) { this.origin = origin; xAxis = X_AXIS; yAxis = Y_AXIS; zAxis = Z_AXIS; if (!this.origin.IsFinite()) throw new ArgumentException("Non-finite in CoordinateFrame constructor"); } public CoordinateFrame(LLVector3 origin, LLVector3 direction) { this.origin = origin; LookDirection(direction); if (!IsFinite()) throw new ArgumentException("Non-finite in CoordinateFrame constructor"); } public CoordinateFrame(LLVector3 origin, LLVector3 xAxis, LLVector3 yAxis, LLVector3 zAxis) { this.origin = origin; this.xAxis = xAxis; this.yAxis = yAxis; this.zAxis = zAxis; if (!IsFinite()) throw new ArgumentException("Non-finite in CoordinateFrame constructor"); } public CoordinateFrame(LLVector3 origin, LLMatrix3 rotation) { this.origin = origin; xAxis = rotation[0]; yAxis = rotation[1]; zAxis = rotation[2]; if (!IsFinite()) throw new ArgumentException("Non-finite in CoordinateFrame constructor"); } public CoordinateFrame(LLVector3 origin, LLQuaternion rotation) { LLMatrix3 m = new LLMatrix3(rotation); this.origin = origin; xAxis = m[0]; yAxis = m[1]; zAxis = m[2]; if (!IsFinite()) throw new ArgumentException("Non-finite in CoordinateFrame constructor"); } #endregion Constructors #region Public Methods public void ResetAxes() { xAxis = X_AXIS; yAxis = Y_AXIS; zAxis = Z_AXIS; } public void Rotate(float angle, LLVector3 rotationAxis) { LLQuaternion q = new LLQuaternion(angle, rotationAxis); Rotate(q); } public void Rotate(LLQuaternion q) { LLMatrix3 m = new LLMatrix3(q); Rotate(m); } public void Rotate(LLMatrix3 m) { xAxis = LLVector3.Rot(xAxis, m); yAxis = LLVector3.Rot(yAxis, m); Orthonormalize(); if (!IsFinite()) throw new Exception("Non-finite in CoordinateFrame.Rotate()"); } public void Roll(float angle) { LLQuaternion q = new LLQuaternion(angle, xAxis); LLMatrix3 m = new LLMatrix3(q); Rotate(m); if (!yAxis.IsFinite() || !zAxis.IsFinite()) throw new Exception("Non-finite in CoordinateFrame.Roll()"); } public void Pitch(float angle) { LLQuaternion q = new LLQuaternion(angle, yAxis); LLMatrix3 m = new LLMatrix3(q); Rotate(m); if (!xAxis.IsFinite() || !zAxis.IsFinite()) throw new Exception("Non-finite in CoordinateFrame.Pitch()"); } public void Yaw(float angle) { LLQuaternion q = new LLQuaternion(angle, zAxis); LLMatrix3 m = new LLMatrix3(q); Rotate(m); if (!xAxis.IsFinite() || !yAxis.IsFinite()) throw new Exception("Non-finite in CoordinateFrame.Yaw()"); } public void LookDirection(LLVector3 at) { LookDirection(at, Z_AXIS); } /// <summary> /// /// </summary> /// <param name="at">Looking direction, must be a normalized vector</param> /// <param name="upDirection">Up direction, must be a normalized vector</param> public void LookDirection(LLVector3 at, LLVector3 upDirection) { // The two parameters cannot be parallel LLVector3 left = LLVector3.Cross(upDirection, at); if (left == LLVector3.Zero) { // Prevent left from being zero at.X += 0.01f; at = LLVector3.Norm(at); left = LLVector3.Cross(upDirection, at); } left = LLVector3.Norm(left); xAxis = at; yAxis = left; zAxis = LLVector3.Cross(at, left); } /// <summary> /// Align the coordinate frame X and Y axis with a given rotation /// around the Z axis in radians /// </summary> /// <param name="heading">Absolute rotation around the Z axis in /// radians</param> public void LookDirection(double heading) { yAxis.X = (float)Math.Cos(heading); yAxis.Y = (float)Math.Sin(heading); xAxis.X = (float)-Math.Sin(heading); xAxis.Y = (float)Math.Cos(heading); } public void LookAt(LLVector3 origin, LLVector3 target) { LookAt(origin, target, new LLVector3(0f, 0f, 1f)); } public void LookAt(LLVector3 origin, LLVector3 target, LLVector3 upDirection) { this.origin = origin; LLVector3 at = new LLVector3(target - origin); at = LLVector3.Norm(at); LookDirection(at, upDirection); } #endregion Public Methods protected bool IsFinite() { if (xAxis.IsFinite() && yAxis.IsFinite() && zAxis.IsFinite()) return true; else return false; } protected void Orthonormalize() { // Make sure the axis are orthagonal and normalized xAxis = LLVector3.Norm(xAxis); yAxis -= xAxis * (xAxis * yAxis); yAxis = LLVector3.Norm(yAxis); zAxis = LLVector3.Cross(xAxis, yAxis); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: bgs/low/pb/client/rpc_config.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 Bgs.Protocol.Config { /// <summary>Holder for reflection information generated from bgs/low/pb/client/rpc_config.proto</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class RpcConfigReflection { #region Descriptor /// <summary>File descriptor for bgs/low/pb/client/rpc_config.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static RpcConfigReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiJiZ3MvbG93L3BiL2NsaWVudC9ycGNfY29uZmlnLnByb3RvEhNiZ3MucHJv", "dG9jb2wuY29uZmlnIvwCCg9SUENNZXRob2RDb25maWcSGAoMc2VydmljZV9u", "YW1lGAEgASgJQgIYARIXCgttZXRob2RfbmFtZRgCIAEoCUICGAESFwoPZml4", "ZWRfY2FsbF9jb3N0GAMgASgNEhkKEWZpeGVkX3BhY2tldF9zaXplGAQgASgN", "EhsKE3ZhcmlhYmxlX211bHRpcGxpZXIYBSABKAISEgoKbXVsdGlwbGllchgG", "IAEoAhIYChByYXRlX2xpbWl0X2NvdW50GAcgASgNEhoKEnJhdGVfbGltaXRf", "c2Vjb25kcxgIIAEoDRIXCg9tYXhfcGFja2V0X3NpemUYCSABKA0SGAoQbWF4", "X2VuY29kZWRfc2l6ZRgKIAEoDRIPCgd0aW1lb3V0GAsgASgCEhMKC2NhcF9i", "YWxhbmNlGAwgASgNEhkKEWluY29tZV9wZXJfc2Vjb25kGA0gASgCEhQKDHNl", "cnZpY2VfaGFzaBgOIAEoDRIRCgltZXRob2RfaWQYDyABKA0ipwEKDlJQQ01l", "dGVyQ29uZmlnEjQKBm1ldGhvZBgBIAMoCzIkLmJncy5wcm90b2NvbC5jb25m", "aWcuUlBDTWV0aG9kQ29uZmlnEhkKEWluY29tZV9wZXJfc2Vjb25kGAIgASgN", "EhcKD2luaXRpYWxfYmFsYW5jZRgDIAEoDRITCgtjYXBfYmFsYW5jZRgEIAEo", "DRIWCg5zdGFydHVwX3BlcmlvZBgFIAEoAiJJCg1Qcm90b2NvbEFsaWFzEhsK", "E3NlcnZlcl9zZXJ2aWNlX25hbWUYASABKAkSGwoTY2xpZW50X3NlcnZpY2Vf", "bmFtZRgCIAEoCSJMCg5TZXJ2aWNlQWxpYXNlcxI6Cg5wcm90b2NvbF9hbGlh", "cxgBIAMoCzIiLmJncy5wcm90b2NvbC5jb25maWcuUHJvdG9jb2xBbGlhc0IC", "SAJiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.Config.RPCMethodConfig), global::Bgs.Protocol.Config.RPCMethodConfig.Parser, new[]{ "ServiceName", "MethodName", "FixedCallCost", "FixedPacketSize", "VariableMultiplier", "Multiplier", "RateLimitCount", "RateLimitSeconds", "MaxPacketSize", "MaxEncodedSize", "Timeout", "CapBalance", "IncomePerSecond", "ServiceHash", "MethodId" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.Config.RPCMeterConfig), global::Bgs.Protocol.Config.RPCMeterConfig.Parser, new[]{ "Method", "IncomePerSecond", "InitialBalance", "CapBalance", "StartupPeriod" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.Config.ProtocolAlias), global::Bgs.Protocol.Config.ProtocolAlias.Parser, new[]{ "ServerServiceName", "ClientServiceName" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.Config.ServiceAliases), global::Bgs.Protocol.Config.ServiceAliases.Parser, new[]{ "ProtocolAlias" }, null, null, null) })); } #endregion } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class RPCMethodConfig : pb::IMessage<RPCMethodConfig> { private static readonly pb::MessageParser<RPCMethodConfig> _parser = new pb::MessageParser<RPCMethodConfig>(() => new RPCMethodConfig()); public static pb::MessageParser<RPCMethodConfig> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Bgs.Protocol.Config.RpcConfigReflection.Descriptor.MessageTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public RPCMethodConfig() { OnConstruction(); } partial void OnConstruction(); public RPCMethodConfig(RPCMethodConfig other) : this() { serviceName_ = other.serviceName_; methodName_ = other.methodName_; fixedCallCost_ = other.fixedCallCost_; fixedPacketSize_ = other.fixedPacketSize_; variableMultiplier_ = other.variableMultiplier_; multiplier_ = other.multiplier_; rateLimitCount_ = other.rateLimitCount_; rateLimitSeconds_ = other.rateLimitSeconds_; maxPacketSize_ = other.maxPacketSize_; maxEncodedSize_ = other.maxEncodedSize_; timeout_ = other.timeout_; capBalance_ = other.capBalance_; incomePerSecond_ = other.incomePerSecond_; serviceHash_ = other.serviceHash_; methodId_ = other.methodId_; } public RPCMethodConfig Clone() { return new RPCMethodConfig(this); } /// <summary>Field number for the "service_name" field.</summary> public const int ServiceNameFieldNumber = 1; private string serviceName_ = ""; [global::System.ObsoleteAttribute()] public string ServiceName { get { return serviceName_; } set { serviceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "method_name" field.</summary> public const int MethodNameFieldNumber = 2; private string methodName_ = ""; [global::System.ObsoleteAttribute()] public string MethodName { get { return methodName_; } set { methodName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "fixed_call_cost" field.</summary> public const int FixedCallCostFieldNumber = 3; private uint fixedCallCost_; public uint FixedCallCost { get { return fixedCallCost_; } set { fixedCallCost_ = value; } } /// <summary>Field number for the "fixed_packet_size" field.</summary> public const int FixedPacketSizeFieldNumber = 4; private uint fixedPacketSize_; public uint FixedPacketSize { get { return fixedPacketSize_; } set { fixedPacketSize_ = value; } } /// <summary>Field number for the "variable_multiplier" field.</summary> public const int VariableMultiplierFieldNumber = 5; private float variableMultiplier_; public float VariableMultiplier { get { return variableMultiplier_; } set { variableMultiplier_ = value; } } /// <summary>Field number for the "multiplier" field.</summary> public const int MultiplierFieldNumber = 6; private float multiplier_; public float Multiplier { get { return multiplier_; } set { multiplier_ = value; } } /// <summary>Field number for the "rate_limit_count" field.</summary> public const int RateLimitCountFieldNumber = 7; private uint rateLimitCount_; public uint RateLimitCount { get { return rateLimitCount_; } set { rateLimitCount_ = value; } } /// <summary>Field number for the "rate_limit_seconds" field.</summary> public const int RateLimitSecondsFieldNumber = 8; private uint rateLimitSeconds_; public uint RateLimitSeconds { get { return rateLimitSeconds_; } set { rateLimitSeconds_ = value; } } /// <summary>Field number for the "max_packet_size" field.</summary> public const int MaxPacketSizeFieldNumber = 9; private uint maxPacketSize_; public uint MaxPacketSize { get { return maxPacketSize_; } set { maxPacketSize_ = value; } } /// <summary>Field number for the "max_encoded_size" field.</summary> public const int MaxEncodedSizeFieldNumber = 10; private uint maxEncodedSize_; public uint MaxEncodedSize { get { return maxEncodedSize_; } set { maxEncodedSize_ = value; } } /// <summary>Field number for the "timeout" field.</summary> public const int TimeoutFieldNumber = 11; private float timeout_; public float Timeout { get { return timeout_; } set { timeout_ = value; } } /// <summary>Field number for the "cap_balance" field.</summary> public const int CapBalanceFieldNumber = 12; private uint capBalance_; public uint CapBalance { get { return capBalance_; } set { capBalance_ = value; } } /// <summary>Field number for the "income_per_second" field.</summary> public const int IncomePerSecondFieldNumber = 13; private float incomePerSecond_; public float IncomePerSecond { get { return incomePerSecond_; } set { incomePerSecond_ = value; } } /// <summary>Field number for the "service_hash" field.</summary> public const int ServiceHashFieldNumber = 14; private uint serviceHash_; public uint ServiceHash { get { return serviceHash_; } set { serviceHash_ = value; } } /// <summary>Field number for the "method_id" field.</summary> public const int MethodIdFieldNumber = 15; private uint methodId_; public uint MethodId { get { return methodId_; } set { methodId_ = value; } } public override bool Equals(object other) { return Equals(other as RPCMethodConfig); } public bool Equals(RPCMethodConfig other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ServiceName != other.ServiceName) return false; if (MethodName != other.MethodName) return false; if (FixedCallCost != other.FixedCallCost) return false; if (FixedPacketSize != other.FixedPacketSize) return false; if (VariableMultiplier != other.VariableMultiplier) return false; if (Multiplier != other.Multiplier) return false; if (RateLimitCount != other.RateLimitCount) return false; if (RateLimitSeconds != other.RateLimitSeconds) return false; if (MaxPacketSize != other.MaxPacketSize) return false; if (MaxEncodedSize != other.MaxEncodedSize) return false; if (Timeout != other.Timeout) return false; if (CapBalance != other.CapBalance) return false; if (IncomePerSecond != other.IncomePerSecond) return false; if (ServiceHash != other.ServiceHash) return false; if (MethodId != other.MethodId) return false; return true; } public override int GetHashCode() { int hash = 1; if (ServiceName.Length != 0) hash ^= ServiceName.GetHashCode(); if (MethodName.Length != 0) hash ^= MethodName.GetHashCode(); if (FixedCallCost != 0) hash ^= FixedCallCost.GetHashCode(); if (FixedPacketSize != 0) hash ^= FixedPacketSize.GetHashCode(); if (VariableMultiplier != 0F) hash ^= VariableMultiplier.GetHashCode(); if (Multiplier != 0F) hash ^= Multiplier.GetHashCode(); if (RateLimitCount != 0) hash ^= RateLimitCount.GetHashCode(); if (RateLimitSeconds != 0) hash ^= RateLimitSeconds.GetHashCode(); if (MaxPacketSize != 0) hash ^= MaxPacketSize.GetHashCode(); if (MaxEncodedSize != 0) hash ^= MaxEncodedSize.GetHashCode(); if (Timeout != 0F) hash ^= Timeout.GetHashCode(); if (CapBalance != 0) hash ^= CapBalance.GetHashCode(); if (IncomePerSecond != 0F) hash ^= IncomePerSecond.GetHashCode(); if (ServiceHash != 0) hash ^= ServiceHash.GetHashCode(); if (MethodId != 0) hash ^= MethodId.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (ServiceName.Length != 0) { output.WriteRawTag(10); output.WriteString(ServiceName); } if (MethodName.Length != 0) { output.WriteRawTag(18); output.WriteString(MethodName); } if (FixedCallCost != 0) { output.WriteRawTag(24); output.WriteUInt32(FixedCallCost); } if (FixedPacketSize != 0) { output.WriteRawTag(32); output.WriteUInt32(FixedPacketSize); } if (VariableMultiplier != 0F) { output.WriteRawTag(45); output.WriteFloat(VariableMultiplier); } if (Multiplier != 0F) { output.WriteRawTag(53); output.WriteFloat(Multiplier); } if (RateLimitCount != 0) { output.WriteRawTag(56); output.WriteUInt32(RateLimitCount); } if (RateLimitSeconds != 0) { output.WriteRawTag(64); output.WriteUInt32(RateLimitSeconds); } if (MaxPacketSize != 0) { output.WriteRawTag(72); output.WriteUInt32(MaxPacketSize); } if (MaxEncodedSize != 0) { output.WriteRawTag(80); output.WriteUInt32(MaxEncodedSize); } if (Timeout != 0F) { output.WriteRawTag(93); output.WriteFloat(Timeout); } if (CapBalance != 0) { output.WriteRawTag(96); output.WriteUInt32(CapBalance); } if (IncomePerSecond != 0F) { output.WriteRawTag(109); output.WriteFloat(IncomePerSecond); } if (ServiceHash != 0) { output.WriteRawTag(112); output.WriteUInt32(ServiceHash); } if (MethodId != 0) { output.WriteRawTag(120); output.WriteUInt32(MethodId); } } public int CalculateSize() { int size = 0; if (ServiceName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ServiceName); } if (MethodName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(MethodName); } if (FixedCallCost != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(FixedCallCost); } if (FixedPacketSize != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(FixedPacketSize); } if (VariableMultiplier != 0F) { size += 1 + 4; } if (Multiplier != 0F) { size += 1 + 4; } if (RateLimitCount != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(RateLimitCount); } if (RateLimitSeconds != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(RateLimitSeconds); } if (MaxPacketSize != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(MaxPacketSize); } if (MaxEncodedSize != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(MaxEncodedSize); } if (Timeout != 0F) { size += 1 + 4; } if (CapBalance != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(CapBalance); } if (IncomePerSecond != 0F) { size += 1 + 4; } if (ServiceHash != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(ServiceHash); } if (MethodId != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(MethodId); } return size; } public void MergeFrom(RPCMethodConfig other) { if (other == null) { return; } if (other.ServiceName.Length != 0) { ServiceName = other.ServiceName; } if (other.MethodName.Length != 0) { MethodName = other.MethodName; } if (other.FixedCallCost != 0) { FixedCallCost = other.FixedCallCost; } if (other.FixedPacketSize != 0) { FixedPacketSize = other.FixedPacketSize; } if (other.VariableMultiplier != 0F) { VariableMultiplier = other.VariableMultiplier; } if (other.Multiplier != 0F) { Multiplier = other.Multiplier; } if (other.RateLimitCount != 0) { RateLimitCount = other.RateLimitCount; } if (other.RateLimitSeconds != 0) { RateLimitSeconds = other.RateLimitSeconds; } if (other.MaxPacketSize != 0) { MaxPacketSize = other.MaxPacketSize; } if (other.MaxEncodedSize != 0) { MaxEncodedSize = other.MaxEncodedSize; } if (other.Timeout != 0F) { Timeout = other.Timeout; } if (other.CapBalance != 0) { CapBalance = other.CapBalance; } if (other.IncomePerSecond != 0F) { IncomePerSecond = other.IncomePerSecond; } if (other.ServiceHash != 0) { ServiceHash = other.ServiceHash; } if (other.MethodId != 0) { MethodId = other.MethodId; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { ServiceName = input.ReadString(); break; } case 18: { MethodName = input.ReadString(); break; } case 24: { FixedCallCost = input.ReadUInt32(); break; } case 32: { FixedPacketSize = input.ReadUInt32(); break; } case 45: { VariableMultiplier = input.ReadFloat(); break; } case 53: { Multiplier = input.ReadFloat(); break; } case 56: { RateLimitCount = input.ReadUInt32(); break; } case 64: { RateLimitSeconds = input.ReadUInt32(); break; } case 72: { MaxPacketSize = input.ReadUInt32(); break; } case 80: { MaxEncodedSize = input.ReadUInt32(); break; } case 93: { Timeout = input.ReadFloat(); break; } case 96: { CapBalance = input.ReadUInt32(); break; } case 109: { IncomePerSecond = input.ReadFloat(); break; } case 112: { ServiceHash = input.ReadUInt32(); break; } case 120: { MethodId = input.ReadUInt32(); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class RPCMeterConfig : pb::IMessage<RPCMeterConfig> { private static readonly pb::MessageParser<RPCMeterConfig> _parser = new pb::MessageParser<RPCMeterConfig>(() => new RPCMeterConfig()); public static pb::MessageParser<RPCMeterConfig> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Bgs.Protocol.Config.RpcConfigReflection.Descriptor.MessageTypes[1]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public RPCMeterConfig() { OnConstruction(); } partial void OnConstruction(); public RPCMeterConfig(RPCMeterConfig other) : this() { method_ = other.method_.Clone(); incomePerSecond_ = other.incomePerSecond_; initialBalance_ = other.initialBalance_; capBalance_ = other.capBalance_; startupPeriod_ = other.startupPeriod_; } public RPCMeterConfig Clone() { return new RPCMeterConfig(this); } /// <summary>Field number for the "method" field.</summary> public const int MethodFieldNumber = 1; private static readonly pb::FieldCodec<global::Bgs.Protocol.Config.RPCMethodConfig> _repeated_method_codec = pb::FieldCodec.ForMessage(10, global::Bgs.Protocol.Config.RPCMethodConfig.Parser); private readonly pbc::RepeatedField<global::Bgs.Protocol.Config.RPCMethodConfig> method_ = new pbc::RepeatedField<global::Bgs.Protocol.Config.RPCMethodConfig>(); public pbc::RepeatedField<global::Bgs.Protocol.Config.RPCMethodConfig> Method { get { return method_; } } /// <summary>Field number for the "income_per_second" field.</summary> public const int IncomePerSecondFieldNumber = 2; private uint incomePerSecond_; public uint IncomePerSecond { get { return incomePerSecond_; } set { incomePerSecond_ = value; } } /// <summary>Field number for the "initial_balance" field.</summary> public const int InitialBalanceFieldNumber = 3; private uint initialBalance_; public uint InitialBalance { get { return initialBalance_; } set { initialBalance_ = value; } } /// <summary>Field number for the "cap_balance" field.</summary> public const int CapBalanceFieldNumber = 4; private uint capBalance_; public uint CapBalance { get { return capBalance_; } set { capBalance_ = value; } } /// <summary>Field number for the "startup_period" field.</summary> public const int StartupPeriodFieldNumber = 5; private float startupPeriod_; public float StartupPeriod { get { return startupPeriod_; } set { startupPeriod_ = value; } } public override bool Equals(object other) { return Equals(other as RPCMeterConfig); } public bool Equals(RPCMeterConfig other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!method_.Equals(other.method_)) return false; if (IncomePerSecond != other.IncomePerSecond) return false; if (InitialBalance != other.InitialBalance) return false; if (CapBalance != other.CapBalance) return false; if (StartupPeriod != other.StartupPeriod) return false; return true; } public override int GetHashCode() { int hash = 1; hash ^= method_.GetHashCode(); if (IncomePerSecond != 0) hash ^= IncomePerSecond.GetHashCode(); if (InitialBalance != 0) hash ^= InitialBalance.GetHashCode(); if (CapBalance != 0) hash ^= CapBalance.GetHashCode(); if (StartupPeriod != 0F) hash ^= StartupPeriod.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { method_.WriteTo(output, _repeated_method_codec); if (IncomePerSecond != 0) { output.WriteRawTag(16); output.WriteUInt32(IncomePerSecond); } if (InitialBalance != 0) { output.WriteRawTag(24); output.WriteUInt32(InitialBalance); } if (CapBalance != 0) { output.WriteRawTag(32); output.WriteUInt32(CapBalance); } if (StartupPeriod != 0F) { output.WriteRawTag(45); output.WriteFloat(StartupPeriod); } } public int CalculateSize() { int size = 0; size += method_.CalculateSize(_repeated_method_codec); if (IncomePerSecond != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(IncomePerSecond); } if (InitialBalance != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(InitialBalance); } if (CapBalance != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(CapBalance); } if (StartupPeriod != 0F) { size += 1 + 4; } return size; } public void MergeFrom(RPCMeterConfig other) { if (other == null) { return; } method_.Add(other.method_); if (other.IncomePerSecond != 0) { IncomePerSecond = other.IncomePerSecond; } if (other.InitialBalance != 0) { InitialBalance = other.InitialBalance; } if (other.CapBalance != 0) { CapBalance = other.CapBalance; } if (other.StartupPeriod != 0F) { StartupPeriod = other.StartupPeriod; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { method_.AddEntriesFrom(input, _repeated_method_codec); break; } case 16: { IncomePerSecond = input.ReadUInt32(); break; } case 24: { InitialBalance = input.ReadUInt32(); break; } case 32: { CapBalance = input.ReadUInt32(); break; } case 45: { StartupPeriod = input.ReadFloat(); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class ProtocolAlias : pb::IMessage<ProtocolAlias> { private static readonly pb::MessageParser<ProtocolAlias> _parser = new pb::MessageParser<ProtocolAlias>(() => new ProtocolAlias()); public static pb::MessageParser<ProtocolAlias> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Bgs.Protocol.Config.RpcConfigReflection.Descriptor.MessageTypes[2]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public ProtocolAlias() { OnConstruction(); } partial void OnConstruction(); public ProtocolAlias(ProtocolAlias other) : this() { serverServiceName_ = other.serverServiceName_; clientServiceName_ = other.clientServiceName_; } public ProtocolAlias Clone() { return new ProtocolAlias(this); } /// <summary>Field number for the "server_service_name" field.</summary> public const int ServerServiceNameFieldNumber = 1; private string serverServiceName_ = ""; public string ServerServiceName { get { return serverServiceName_; } set { serverServiceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "client_service_name" field.</summary> public const int ClientServiceNameFieldNumber = 2; private string clientServiceName_ = ""; public string ClientServiceName { get { return clientServiceName_; } set { clientServiceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } public override bool Equals(object other) { return Equals(other as ProtocolAlias); } public bool Equals(ProtocolAlias other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ServerServiceName != other.ServerServiceName) return false; if (ClientServiceName != other.ClientServiceName) return false; return true; } public override int GetHashCode() { int hash = 1; hash ^= ServerServiceName.GetHashCode(); hash ^= ClientServiceName.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { { output.WriteRawTag(10); output.WriteString(ServerServiceName); } { output.WriteRawTag(18); output.WriteString(ClientServiceName); } } public int CalculateSize() { int size = 0; { size += 1 + pb::CodedOutputStream.ComputeStringSize(ServerServiceName); } { size += 1 + pb::CodedOutputStream.ComputeStringSize(ClientServiceName); } return size; } public void MergeFrom(ProtocolAlias other) { if (other == null) { return; } if (other.ServerServiceName.Length != 0) { ServerServiceName = other.ServerServiceName; } if (other.ClientServiceName.Length != 0) { ClientServiceName = other.ClientServiceName; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { ServerServiceName = input.ReadString(); break; } case 18: { ClientServiceName = input.ReadString(); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class ServiceAliases : pb::IMessage<ServiceAliases> { private static readonly pb::MessageParser<ServiceAliases> _parser = new pb::MessageParser<ServiceAliases>(() => new ServiceAliases()); public static pb::MessageParser<ServiceAliases> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Bgs.Protocol.Config.RpcConfigReflection.Descriptor.MessageTypes[3]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public ServiceAliases() { OnConstruction(); } partial void OnConstruction(); public ServiceAliases(ServiceAliases other) : this() { protocolAlias_ = other.protocolAlias_.Clone(); } public ServiceAliases Clone() { return new ServiceAliases(this); } /// <summary>Field number for the "protocol_alias" field.</summary> public const int ProtocolAliasFieldNumber = 1; private static readonly pb::FieldCodec<global::Bgs.Protocol.Config.ProtocolAlias> _repeated_protocolAlias_codec = pb::FieldCodec.ForMessage(10, global::Bgs.Protocol.Config.ProtocolAlias.Parser); private readonly pbc::RepeatedField<global::Bgs.Protocol.Config.ProtocolAlias> protocolAlias_ = new pbc::RepeatedField<global::Bgs.Protocol.Config.ProtocolAlias>(); public pbc::RepeatedField<global::Bgs.Protocol.Config.ProtocolAlias> ProtocolAlias { get { return protocolAlias_; } } public override bool Equals(object other) { return Equals(other as ServiceAliases); } public bool Equals(ServiceAliases other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!protocolAlias_.Equals(other.protocolAlias_)) return false; return true; } public override int GetHashCode() { int hash = 1; hash ^= protocolAlias_.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { protocolAlias_.WriteTo(output, _repeated_protocolAlias_codec); } public int CalculateSize() { int size = 0; size += protocolAlias_.CalculateSize(_repeated_protocolAlias_codec); return size; } public void MergeFrom(ServiceAliases other) { if (other == null) { return; } protocolAlias_.Add(other.protocolAlias_); } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { protocolAlias_.AddEntriesFrom(input, _repeated_protocolAlias_codec); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.IO; using System.Linq; using System.Windows.Forms; using NetGore.IO; using NetGore.World; namespace NetGore.Editor { /// <summary> /// Contains helper methods for file opening and saving dialogs for differnet editor file types. All file dialogs /// should be created from this class if possible. /// </summary> public static class FileDialogs { /// <summary> /// Gets the results from a generic open file dialog. /// </summary> /// <typeparam name="T">The Type of content to load.</typeparam> /// <param name="contentType">The name of the content type being handled.</param> /// <param name="fileFilterSuffix">The suffix of the files to filter.</param> /// <param name="initialDirectory">The initial directory.</param> /// <param name="loadHandler">Delegate describing how to load the type.</param> /// <param name="loadedContent">When the method returns a non-null value, and the <paramref name="loadHandler"/> /// is not null, contains the loaded content.</param> /// <returns>The path to the selected file, or null if invalid or canceled.</returns> static string GenericOpenFile<T>(string contentType, string fileFilterSuffix, string initialDirectory, Func<string, T> loadHandler, out T loadedContent) where T : class { string filePath; loadedContent = null; if (!Directory.Exists(initialDirectory)) Directory.CreateDirectory(initialDirectory); try { // Create the dialog and get the result using (var ofd = new OpenFileDialog()) { ofd.CheckPathExists = true; ofd.CheckFileExists = true; ofd.AutoUpgradeEnabled = true; ofd.AddExtension = true; ofd.Multiselect = false; ofd.RestoreDirectory = true; ofd.Title = "Open " + contentType; ofd.Filter = string.Format("{0} (*{1})|*{1}", contentType, fileFilterSuffix); ofd.InitialDirectory = initialDirectory; var ofdResult = ofd.ShowDialog(); if (ofdResult != DialogResult.OK) return null; filePath = ofd.FileName; } if (filePath == null) return null; if (!IsFileFromDirectory(initialDirectory, filePath, true)) return null; // Can only check if the content loaded correctly if we are told how to load it if (loadHandler != null) { // Ensure the content is valid try { loadedContent = loadHandler(filePath); } catch (Exception ex) { HandleError(string.Format("Unable to load the {0} from the selected file.", fileFilterSuffix), true, ex); return null; } if (loadedContent == null) { HandleError(string.Format("Unable to load the {0} from the selected file.", fileFilterSuffix), true); return null; } } } catch (Exception ex) { HandleUnhandledException(contentType, true, ex); return null; } return filePath; } static string GenericSaveFile(string contentType, string initialDirectory, string fileFilterSuffix) { if (!Directory.Exists(initialDirectory)) Directory.CreateDirectory(initialDirectory); string filePath; try { using (var sfd = new SaveFileDialog()) { sfd.CheckPathExists = true; sfd.CheckFileExists = false; sfd.AutoUpgradeEnabled = true; sfd.AddExtension = true; sfd.CreatePrompt = false; sfd.DefaultExt = fileFilterSuffix; sfd.InitialDirectory = initialDirectory; sfd.OverwritePrompt = true; sfd.RestoreDirectory = true; sfd.ValidateNames = true; sfd.Filter = string.Format("{0} (*{1})|*{1}", contentType, fileFilterSuffix); sfd.Title = "Save " + contentType; var sfdResult = sfd.ShowDialog(); if (sfdResult != DialogResult.OK) return null; filePath = sfd.FileName; } if (filePath == null) return null; if (!IsFileFromDirectory(initialDirectory, filePath, false)) return null; } catch (Exception ex) { HandleUnhandledException(contentType, false, ex); return null; } return filePath; } /// <summary> /// Handles an error made from one of this class's methods. /// </summary> /// <param name="message">The error message.</param> /// <param name="wasLoadError">True if the error was from loading; false if from saving.</param> /// <param name="innerException">The inner exception, or null if none.</param> static void HandleError(string message, bool wasLoadError, Exception innerException = null) { var caption = string.Format("File {0} error", wasLoadError ? "load" : "save"); if (wasLoadError) message = "Failed to load file - " + message; else message = "Failed to save file - " + message; if (innerException != null) message = string.Format("{0}:{1}{1}{2}", message, Environment.NewLine, innerException); MessageBox.Show(message, caption, MessageBoxButtons.OK); } /// <summary> /// Handles an unhandled <see cref="Exception"/> thrown from one of this class's methods. /// </summary> /// <param name="contentType">The name of the content type being handled.</param> /// <param name="wasLoadError">True if it was a load error; false if a save error.</param> /// <param name="innerException">The inner exception.</param> static void HandleUnhandledException(string contentType, bool wasLoadError, Exception innerException) { var msg = string.Format("Failed to {0} {1}:{2}{2}{3}", wasLoadError ? "load" : "save", contentType, Environment.NewLine, innerException); MessageBox.Show(msg, "Unhandled I/O error", MessageBoxButtons.OK); } static bool IsFileFromDirectory(string dir, string file, bool wasLoadError) { if (file.Length <= dir.Length || !file.StartsWith(dir, StringComparison.OrdinalIgnoreCase)) { HandleError( "The selected file was from an invalid directory. Files must be selected from the initial directory.", wasLoadError); return false; } return true; } public static bool TryOpenMap(Func<string, IMap> createMap, out string filePath, out IMap map) { filePath = null; map = null; try { filePath = GenericOpenFile("Map", EngineSettings.DataFileSuffix, ContentPaths.Dev.Maps, createMap, out map); if (filePath == null) return false; } catch (Exception ex) { HandleUnhandledException("Map", true, ex); return false; } return true; } } }
using System; using Android.OS; using Android.App; using Android.Views; using Android.Widget; using System.Net.Http; using System.Threading.Tasks; using Microsoft.WindowsAzure.MobileServices; using Shared; namespace xamarinpcl { [Activity (MainLauncher = true, Icon="@drawable/ic_launcher", Label="@string/app_name", Theme="@style/AppTheme")] public class ToDoActivity : Activity { //Mobile Service Client reference private MobileServiceClient client; //Mobile Service Table used to access data private IMobileServiceTable<ToDoItem> toDoTable; //Adapter to sync the items list with the view private ToDoItemAdapter adapter; //EditText containing the "New ToDo" text private EditText textNewToDo; //Progress spinner to use for table operations private ProgressBar progressBar; protected override async void OnCreate (Bundle bundle) { base.OnCreate (bundle); // Set our view from the "main" layout resource SetContentView (Resource.Layout.Activity_To_Do); progressBar = FindViewById<ProgressBar> (Resource.Id.loadingProgressBar); // Initialize the progress bar progressBar.Visibility = ViewStates.Gone; // Create ProgressFilter to handle busy state var progressHandler = new ProgressHandler (); progressHandler.BusyStateChange += (busy) => { if (progressBar != null) progressBar.Visibility = busy ? ViewStates.Visible : ViewStates.Gone; }; try { CurrentPlatform.Init (); // Create the Mobile Service Client instance, using the provided // Mobile Service URL and key client = Common.MobileService; // Get the Mobile Service Table instance to use toDoTable = client.GetTable <ToDoItem> (); textNewToDo = FindViewById<EditText> (Resource.Id.textNewToDo); // Create an adapter to bind the items with the view adapter = new ToDoItemAdapter (this, Resource.Layout.Row_List_To_Do); var listViewToDo = FindViewById<ListView> (Resource.Id.listViewToDo); listViewToDo.Adapter = adapter; // Load the items from the Mobile Service await RefreshItemsFromTableAsync (); } catch (Java.Net.MalformedURLException) { CreateAndShowDialog (new Exception ("There was an error creating the Mobile Service. Verify the URL"), "Error"); } catch (Exception e) { CreateAndShowDialog (e, "Error"); } } //Initializes the activity menu public override bool OnCreateOptionsMenu (IMenu menu) { MenuInflater.Inflate (Resource.Menu.activity_main, menu); return true; } //Select an option from the menu public override bool OnOptionsItemSelected (IMenuItem item) { if (item.ItemId == Resource.Id.menu_refresh) { OnRefreshItemsSelected (); } return true; } // Called when the refresh menu opion is selected async void OnRefreshItemsSelected () { await RefreshItemsFromTableAsync (); } //Refresh the list with the items in the Mobile Service Table async Task RefreshItemsFromTableAsync () { try { // Get the items that weren't marked as completed and add them in the // adapter var list = await Common.GetIncompleteItems().ToListAsync (); adapter.Clear (); foreach (ToDoItem current in list) adapter.Add (current); } catch (Exception e) { CreateAndShowDialog (e, "Error"); } } public async Task CheckItem (ToDoItem item) { if (client == null) { return; } // Set the item as completed and update it in the table item.Complete = true; try { await toDoTable.UpdateAsync (item); if (item.Complete) adapter.Remove (item); } catch (Exception e) { CreateAndShowDialog (e, "Error"); } } [Java.Interop.Export()] public async void AddItem (View view) { if (client == null || string.IsNullOrWhiteSpace (textNewToDo.Text)) { return; } // Create a new item var item = new ToDoItem { Text = textNewToDo.Text, Complete = false }; try { // Insert the new item await toDoTable.InsertAsync (item); if (!item.Complete) { adapter.Add (item); } } catch (Exception e) { CreateAndShowDialog (e, "Error"); } textNewToDo.Text = ""; } void CreateAndShowDialog (Exception exception, String title) { CreateAndShowDialog (exception.Message, title); } void CreateAndShowDialog (string message, string title) { AlertDialog.Builder builder = new AlertDialog.Builder (this); builder.SetMessage (message); builder.SetTitle (title); builder.Create ().Show (); } class ProgressHandler : DelegatingHandler { int busyCount = 0; public event Action<bool> BusyStateChange; #region implemented abstract members of HttpMessageHandler protected override async Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { //assumes always executes on UI thread if (busyCount++ == 0 && BusyStateChange != null) BusyStateChange (true); var response = await base.SendAsync (request, cancellationToken); // assumes always executes on UI thread if (--busyCount == 0 && BusyStateChange != null) BusyStateChange (false); return response; } #endregion } } }
#region License /* * WebHeaderCollection.cs * * This code is derived from WebHeaderCollection.cs (System.Net) of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2003 Ximian, Inc. (http://www.ximian.com) * Copyright (c) 2007 Novell, Inc. (http://www.novell.com) * Copyright (c) 2012-2015 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Authors /* * Authors: * - Lawrence Pit <loz@cable.a2000.nl> * - Gonzalo Paniagua Javier <gonzalo@ximian.com> * - Miguel de Icaza <miguel@novell.com> */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security.Permissions; using System.Text; namespace WebSocketSharp.Net { /// <summary> /// Provides a collection of the HTTP headers associated with a request or /// response. /// </summary> [Serializable] [ComVisible (true)] public class WebHeaderCollection : NameValueCollection, ISerializable { #region Private Fields private static readonly Dictionary<string, HttpHeaderInfo> _headers; private bool _internallyUsed; private HttpHeaderType _state; #endregion #region Static Constructor static WebHeaderCollection () { _headers = new Dictionary<string, HttpHeaderInfo> ( StringComparer.InvariantCultureIgnoreCase ) { { "Accept", new HttpHeaderInfo ( "Accept", HttpHeaderType.Request | HttpHeaderType.Restricted | HttpHeaderType.MultiValue ) }, { "AcceptCharset", new HttpHeaderInfo ( "Accept-Charset", HttpHeaderType.Request | HttpHeaderType.MultiValue ) }, { "AcceptEncoding", new HttpHeaderInfo ( "Accept-Encoding", HttpHeaderType.Request | HttpHeaderType.MultiValue ) }, { "AcceptLanguage", new HttpHeaderInfo ( "Accept-Language", HttpHeaderType.Request | HttpHeaderType.MultiValue ) }, { "AcceptRanges", new HttpHeaderInfo ( "Accept-Ranges", HttpHeaderType.Response | HttpHeaderType.MultiValue ) }, { "Age", new HttpHeaderInfo ( "Age", HttpHeaderType.Response ) }, { "Allow", new HttpHeaderInfo ( "Allow", HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue ) }, { "Authorization", new HttpHeaderInfo ( "Authorization", HttpHeaderType.Request | HttpHeaderType.MultiValue ) }, { "CacheControl", new HttpHeaderInfo ( "Cache-Control", HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue ) }, { "Connection", new HttpHeaderInfo ( "Connection", HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted | HttpHeaderType.MultiValue ) }, { "ContentEncoding", new HttpHeaderInfo ( "Content-Encoding", HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue ) }, { "ContentLanguage", new HttpHeaderInfo ( "Content-Language", HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue ) }, { "ContentLength", new HttpHeaderInfo ( "Content-Length", HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted ) }, { "ContentLocation", new HttpHeaderInfo ( "Content-Location", HttpHeaderType.Request | HttpHeaderType.Response ) }, { "ContentMd5", new HttpHeaderInfo ( "Content-MD5", HttpHeaderType.Request | HttpHeaderType.Response ) }, { "ContentRange", new HttpHeaderInfo ( "Content-Range", HttpHeaderType.Request | HttpHeaderType.Response ) }, { "ContentType", new HttpHeaderInfo ( "Content-Type", HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted ) }, { "Cookie", new HttpHeaderInfo ( "Cookie", HttpHeaderType.Request ) }, { "Cookie2", new HttpHeaderInfo ( "Cookie2", HttpHeaderType.Request ) }, { "Date", new HttpHeaderInfo ( "Date", HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted ) }, { "Expect", new HttpHeaderInfo ( "Expect", HttpHeaderType.Request | HttpHeaderType.Restricted | HttpHeaderType.MultiValue ) }, { "Expires", new HttpHeaderInfo ( "Expires", HttpHeaderType.Request | HttpHeaderType.Response ) }, { "ETag", new HttpHeaderInfo ( "ETag", HttpHeaderType.Response ) }, { "From", new HttpHeaderInfo ( "From", HttpHeaderType.Request ) }, { "Host", new HttpHeaderInfo ( "Host", HttpHeaderType.Request | HttpHeaderType.Restricted ) }, { "IfMatch", new HttpHeaderInfo ( "If-Match", HttpHeaderType.Request | HttpHeaderType.MultiValue ) }, { "IfModifiedSince", new HttpHeaderInfo ( "If-Modified-Since", HttpHeaderType.Request | HttpHeaderType.Restricted ) }, { "IfNoneMatch", new HttpHeaderInfo ( "If-None-Match", HttpHeaderType.Request | HttpHeaderType.MultiValue ) }, { "IfRange", new HttpHeaderInfo ( "If-Range", HttpHeaderType.Request ) }, { "IfUnmodifiedSince", new HttpHeaderInfo ( "If-Unmodified-Since", HttpHeaderType.Request ) }, { "KeepAlive", new HttpHeaderInfo ( "Keep-Alive", HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue ) }, { "LastModified", new HttpHeaderInfo ( "Last-Modified", HttpHeaderType.Request | HttpHeaderType.Response ) }, { "Location", new HttpHeaderInfo ( "Location", HttpHeaderType.Response ) }, { "MaxForwards", new HttpHeaderInfo ( "Max-Forwards", HttpHeaderType.Request ) }, { "Pragma", new HttpHeaderInfo ( "Pragma", HttpHeaderType.Request | HttpHeaderType.Response ) }, { "ProxyAuthenticate", new HttpHeaderInfo ( "Proxy-Authenticate", HttpHeaderType.Response | HttpHeaderType.MultiValue ) }, { "ProxyAuthorization", new HttpHeaderInfo ( "Proxy-Authorization", HttpHeaderType.Request ) }, { "ProxyConnection", new HttpHeaderInfo ( "Proxy-Connection", HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted ) }, { "Public", new HttpHeaderInfo ( "Public", HttpHeaderType.Response | HttpHeaderType.MultiValue ) }, { "Range", new HttpHeaderInfo ( "Range", HttpHeaderType.Request | HttpHeaderType.Restricted | HttpHeaderType.MultiValue ) }, { "Referer", new HttpHeaderInfo ( "Referer", HttpHeaderType.Request | HttpHeaderType.Restricted ) }, { "RetryAfter", new HttpHeaderInfo ( "Retry-After", HttpHeaderType.Response ) }, { "SecWebSocketAccept", new HttpHeaderInfo ( "Sec-WebSocket-Accept", HttpHeaderType.Response | HttpHeaderType.Restricted ) }, { "SecWebSocketExtensions", new HttpHeaderInfo ( "Sec-WebSocket-Extensions", HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted | HttpHeaderType.MultiValueInRequest ) }, { "SecWebSocketKey", new HttpHeaderInfo ( "Sec-WebSocket-Key", HttpHeaderType.Request | HttpHeaderType.Restricted ) }, { "SecWebSocketProtocol", new HttpHeaderInfo ( "Sec-WebSocket-Protocol", HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValueInRequest ) }, { "SecWebSocketVersion", new HttpHeaderInfo ( "Sec-WebSocket-Version", HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted | HttpHeaderType.MultiValueInResponse ) }, { "Server", new HttpHeaderInfo ( "Server", HttpHeaderType.Response ) }, { "SetCookie", new HttpHeaderInfo ( "Set-Cookie", HttpHeaderType.Response | HttpHeaderType.MultiValue ) }, { "SetCookie2", new HttpHeaderInfo ( "Set-Cookie2", HttpHeaderType.Response | HttpHeaderType.MultiValue ) }, { "Te", new HttpHeaderInfo ( "TE", HttpHeaderType.Request ) }, { "Trailer", new HttpHeaderInfo ( "Trailer", HttpHeaderType.Request | HttpHeaderType.Response ) }, { "TransferEncoding", new HttpHeaderInfo ( "Transfer-Encoding", HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted | HttpHeaderType.MultiValue ) }, { "Translate", new HttpHeaderInfo ( "Translate", HttpHeaderType.Request ) }, { "Upgrade", new HttpHeaderInfo ( "Upgrade", HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue ) }, { "UserAgent", new HttpHeaderInfo ( "User-Agent", HttpHeaderType.Request | HttpHeaderType.Restricted ) }, { "Vary", new HttpHeaderInfo ( "Vary", HttpHeaderType.Response | HttpHeaderType.MultiValue ) }, { "Via", new HttpHeaderInfo ( "Via", HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue ) }, { "Warning", new HttpHeaderInfo ( "Warning", HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue ) }, { "WwwAuthenticate", new HttpHeaderInfo ( "WWW-Authenticate", HttpHeaderType.Response | HttpHeaderType.Restricted | HttpHeaderType.MultiValue ) } }; } #endregion #region Internal Constructors internal WebHeaderCollection (HttpHeaderType state, bool internallyUsed) { _state = state; _internallyUsed = internallyUsed; } #endregion #region Protected Constructors /// <summary> /// Initializes a new instance of the <see cref="WebHeaderCollection"/> class /// from the specified instances of the <see cref="SerializationInfo"/> and /// <see cref="StreamingContext"/> classes. /// </summary> /// <param name="serializationInfo"> /// A <see cref="SerializationInfo"/> that contains the serialized /// object data. /// </param> /// <param name="streamingContext"> /// A <see cref="StreamingContext"/> that specifies the source for /// the deserialization. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="serializationInfo"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// An element with the specified name is not found in /// <paramref name="serializationInfo"/>. /// </exception> protected WebHeaderCollection ( SerializationInfo serializationInfo, StreamingContext streamingContext ) { if (serializationInfo == null) throw new ArgumentNullException ("serializationInfo"); try { _internallyUsed = serializationInfo.GetBoolean ("InternallyUsed"); _state = (HttpHeaderType) serializationInfo.GetInt32 ("State"); var cnt = serializationInfo.GetInt32 ("Count"); for (var i = 0; i < cnt; i++) { base.Add ( serializationInfo.GetString (i.ToString ()), serializationInfo.GetString ((cnt + i).ToString ()) ); } } catch (SerializationException ex) { throw new ArgumentException (ex.Message, "serializationInfo", ex); } } #endregion #region Public Constructors /// <summary> /// Initializes a new instance of the <see cref="WebHeaderCollection"/> /// class. /// </summary> public WebHeaderCollection () { } #endregion #region Internal Properties internal HttpHeaderType State { get { return _state; } } #endregion #region Public Properties /// <summary> /// Gets all header names in the collection. /// </summary> /// <value> /// An array of <see cref="string"/> that contains all header names in the collection. /// </value> public override string[] AllKeys { get { return base.AllKeys; } } /// <summary> /// Gets the number of headers in the collection. /// </summary> /// <value> /// An <see cref="int"/> that represents the number of headers in the collection. /// </value> public override int Count { get { return base.Count; } } /// <summary> /// Gets or sets the specified request <paramref name="header"/> in the collection. /// </summary> /// <value> /// A <see cref="string"/> that represents the value of the request <paramref name="header"/>. /// </value> /// <param name="header"> /// One of the <see cref="HttpRequestHeader"/> enum values, represents /// the request header to get or set. /// </param> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="header"/> is a restricted header. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="value"/> contains invalid characters. /// </para> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The length of <paramref name="value"/> is greater than 65,535 characters. /// </exception> /// <exception cref="InvalidOperationException"> /// The current <see cref="WebHeaderCollection"/> instance doesn't allow /// the request <paramref name="header"/>. /// </exception> public string this[HttpRequestHeader header] { get { return Get (Convert (header)); } set { Add (header, value); } } /// <summary> /// Gets or sets the specified response <paramref name="header"/> in the collection. /// </summary> /// <value> /// A <see cref="string"/> that represents the value of the response <paramref name="header"/>. /// </value> /// <param name="header"> /// One of the <see cref="HttpResponseHeader"/> enum values, represents /// the response header to get or set. /// </param> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="header"/> is a restricted header. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="value"/> contains invalid characters. /// </para> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The length of <paramref name="value"/> is greater than 65,535 characters. /// </exception> /// <exception cref="InvalidOperationException"> /// The current <see cref="WebHeaderCollection"/> instance doesn't allow /// the response <paramref name="header"/>. /// </exception> public string this[HttpResponseHeader header] { get { return Get (Convert (header)); } set { Add (header, value); } } /// <summary> /// Gets a collection of header names in the collection. /// </summary> /// <value> /// A <see cref="NameObjectCollectionBase.KeysCollection"/> that contains /// all header names in the collection. /// </value> public override NameObjectCollectionBase.KeysCollection Keys { get { return base.Keys; } } #endregion #region Private Methods private void add (string name, string value, bool ignoreRestricted) { var act = ignoreRestricted ? (Action <string, string>) addWithoutCheckingNameAndRestricted : addWithoutCheckingName; doWithCheckingState (act, checkName (name), value, true); } private void addWithoutCheckingName (string name, string value) { doWithoutCheckingName (base.Add, name, value); } private void addWithoutCheckingNameAndRestricted (string name, string value) { base.Add (name, checkValue (value)); } private static int checkColonSeparated (string header) { var idx = header.IndexOf (':'); if (idx == -1) throw new ArgumentException ("No colon could be found.", "header"); return idx; } private static HttpHeaderType checkHeaderType (string name) { var info = getHeaderInfo (name); return info == null ? HttpHeaderType.Unspecified : info.IsRequest && !info.IsResponse ? HttpHeaderType.Request : !info.IsRequest && info.IsResponse ? HttpHeaderType.Response : HttpHeaderType.Unspecified; } private static string checkName (string name) { if (name == null) throw new ArgumentNullException ("name"); if (name.Length == 0) throw new ArgumentException ("An empty string.", "name"); name = name.Trim (); if (name.Length == 0) throw new ArgumentException ("A string of spaces.", "name"); if (!IsHeaderName (name)) { var msg = "It contains an invalid character."; throw new ArgumentException (msg, "name"); } return name; } private void checkRestricted (string name) { if (!_internallyUsed && isRestricted (name, true)) throw new ArgumentException ("This header must be modified with the appropiate property."); } private void checkState (bool response) { if (_state == HttpHeaderType.Unspecified) return; if (response && _state == HttpHeaderType.Request) throw new InvalidOperationException ( "This collection has already been used to store the request headers."); if (!response && _state == HttpHeaderType.Response) throw new InvalidOperationException ( "This collection has already been used to store the response headers."); } private static string checkValue (string value) { if (value == null || value.Length == 0) return String.Empty; value = value.Trim (); if (value.Length > 65535) throw new ArgumentOutOfRangeException ("value", "Greater than 65,535 characters."); if (!IsHeaderValue (value)) throw new ArgumentException ("Contains invalid characters.", "value"); return value; } private static string convert (string key) { HttpHeaderInfo info; return _headers.TryGetValue (key, out info) ? info.Name : String.Empty; } private void doWithCheckingState ( Action <string, string> action, string name, string value, bool setState) { var type = checkHeaderType (name); if (type == HttpHeaderType.Request) doWithCheckingState (action, name, value, false, setState); else if (type == HttpHeaderType.Response) doWithCheckingState (action, name, value, true, setState); else action (name, value); } private void doWithCheckingState ( Action <string, string> action, string name, string value, bool response, bool setState) { checkState (response); action (name, value); if (setState && _state == HttpHeaderType.Unspecified) _state = response ? HttpHeaderType.Response : HttpHeaderType.Request; } private void doWithoutCheckingName (Action <string, string> action, string name, string value) { checkRestricted (name); action (name, checkValue (value)); } private static HttpHeaderInfo getHeaderInfo (string name) { foreach (var info in _headers.Values) if (info.Name.Equals (name, StringComparison.InvariantCultureIgnoreCase)) return info; return null; } private static bool isRestricted (string name, bool response) { var info = getHeaderInfo (name); return info != null && info.IsRestricted (response); } private void removeWithoutCheckingName (string name, string unuse) { checkRestricted (name); base.Remove (name); } private void setWithoutCheckingName (string name, string value) { doWithoutCheckingName (base.Set, name, value); } #endregion #region Internal Methods internal static string Convert (HttpRequestHeader header) { return convert (header.ToString ()); } internal static string Convert (HttpResponseHeader header) { return convert (header.ToString ()); } internal void InternalRemove (string name) { base.Remove (name); } internal void InternalSet (string header, bool response) { var pos = checkColonSeparated (header); InternalSet (header.Substring (0, pos), header.Substring (pos + 1), response); } internal void InternalSet (string name, string value, bool response) { value = checkValue (value); if (IsMultiValue (name, response)) base.Add (name, value); else base.Set (name, value); } internal static bool IsHeaderName (string name) { return name.IsToken (); } internal static bool IsHeaderValue (string value) { return value.IsText (); } internal static bool IsMultiValue (string headerName, bool response) { if (headerName == null || headerName.Length == 0) return false; var info = getHeaderInfo (headerName); return info != null && info.IsMultiValue (response); } internal string ToStringMultiValue (bool response) { var buff = new StringBuilder (); Count.Times ( i => { var key = GetKey (i); if (IsMultiValue (key, response)) foreach (var val in GetValues (i)) buff.AppendFormat ("{0}: {1}\r\n", key, val); else buff.AppendFormat ("{0}: {1}\r\n", key, Get (i)); }); return buff.Append ("\r\n").ToString (); } #endregion #region Protected Methods /// <summary> /// Adds a header to the collection without checking if the header is on /// the restricted header list. /// </summary> /// <param name="headerName"> /// A <see cref="string"/> that represents the name of the header to add. /// </param> /// <param name="headerValue"> /// A <see cref="string"/> that represents the value of the header to add. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="headerName"/> is <see langword="null"/> or empty. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="headerName"/> or <paramref name="headerValue"/> contains invalid characters. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The length of <paramref name="headerValue"/> is greater than 65,535 characters. /// </exception> /// <exception cref="InvalidOperationException"> /// The current <see cref="WebHeaderCollection"/> instance doesn't allow /// the <paramref name="headerName"/>. /// </exception> protected void AddWithoutValidate (string headerName, string headerValue) { add (headerName, headerValue, true); } #endregion #region Public Methods /// <summary> /// Adds the specified <paramref name="header"/> to the collection. /// </summary> /// <param name="header"> /// A <see cref="string"/> that represents the header with the name and value separated by /// a colon (<c>':'</c>). /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="header"/> is <see langword="null"/>, empty, or the name part of /// <paramref name="header"/> is empty. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="header"/> doesn't contain a colon. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="header"/> is a restricted header. /// </para> /// <para> /// -or- /// </para> /// <para> /// The name or value part of <paramref name="header"/> contains invalid characters. /// </para> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The length of the value part of <paramref name="header"/> is greater than 65,535 characters. /// </exception> /// <exception cref="InvalidOperationException"> /// The current <see cref="WebHeaderCollection"/> instance doesn't allow /// the <paramref name="header"/>. /// </exception> public void Add (string header) { if (header == null || header.Length == 0) throw new ArgumentNullException ("header"); var pos = checkColonSeparated (header); add (header.Substring (0, pos), header.Substring (pos + 1), false); } /// <summary> /// Adds the specified request <paramref name="header"/> with /// the specified <paramref name="value"/> to the collection. /// </summary> /// <param name="header"> /// One of the <see cref="HttpRequestHeader"/> enum values, represents /// the request header to add. /// </param> /// <param name="value"> /// A <see cref="string"/> that represents the value of the header to add. /// </param> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="header"/> is a restricted header. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="value"/> contains invalid characters. /// </para> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The length of <paramref name="value"/> is greater than 65,535 characters. /// </exception> /// <exception cref="InvalidOperationException"> /// The current <see cref="WebHeaderCollection"/> instance doesn't allow /// the request <paramref name="header"/>. /// </exception> public void Add (HttpRequestHeader header, string value) { doWithCheckingState (addWithoutCheckingName, Convert (header), value, false, true); } /// <summary> /// Adds the specified response <paramref name="header"/> with /// the specified <paramref name="value"/> to the collection. /// </summary> /// <param name="header"> /// One of the <see cref="HttpResponseHeader"/> enum values, represents /// the response header to add. /// </param> /// <param name="value"> /// A <see cref="string"/> that represents the value of the header to add. /// </param> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="header"/> is a restricted header. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="value"/> contains invalid characters. /// </para> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The length of <paramref name="value"/> is greater than 65,535 characters. /// </exception> /// <exception cref="InvalidOperationException"> /// The current <see cref="WebHeaderCollection"/> instance doesn't allow /// the response <paramref name="header"/>. /// </exception> public void Add (HttpResponseHeader header, string value) { doWithCheckingState (addWithoutCheckingName, Convert (header), value, true, true); } /// <summary> /// Adds a header with the specified <paramref name="name"/> and /// <paramref name="value"/> to the collection. /// </summary> /// <param name="name"> /// A <see cref="string"/> that represents the name of the header to add. /// </param> /// <param name="value"> /// A <see cref="string"/> that represents the value of the header to add. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="name"/> is <see langword="null"/> or empty. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="name"/> or <paramref name="value"/> contains invalid characters. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="name"/> is a restricted header name. /// </para> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The length of <paramref name="value"/> is greater than 65,535 characters. /// </exception> /// <exception cref="InvalidOperationException"> /// The current <see cref="WebHeaderCollection"/> instance doesn't allow /// the header <paramref name="name"/>. /// </exception> public override void Add (string name, string value) { add (name, value, false); } /// <summary> /// Removes all headers from the collection. /// </summary> public override void Clear () { base.Clear (); _state = HttpHeaderType.Unspecified; } /// <summary> /// Get the value of the header at the specified <paramref name="index"/> in the collection. /// </summary> /// <returns> /// A <see cref="string"/> that receives the value of the header. /// </returns> /// <param name="index"> /// An <see cref="int"/> that represents the zero-based index of the header to find. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="index"/> is out of allowable range of indexes for the collection. /// </exception> public override string Get (int index) { return base.Get (index); } /// <summary> /// Get the value of the header with the specified <paramref name="name"/> in the collection. /// </summary> /// <returns> /// A <see cref="string"/> that receives the value of the header if found; /// otherwise, <see langword="null"/>. /// </returns> /// <param name="name"> /// A <see cref="string"/> that represents the name of the header to find. /// </param> public override string Get (string name) { return base.Get (name); } /// <summary> /// Gets the enumerator used to iterate through the collection. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> instance used to iterate through the collection. /// </returns> public override IEnumerator GetEnumerator () { return base.GetEnumerator (); } /// <summary> /// Get the name of the header at the specified <paramref name="index"/> in the collection. /// </summary> /// <returns> /// A <see cref="string"/> that receives the header name. /// </returns> /// <param name="index"> /// An <see cref="int"/> that represents the zero-based index of the header to find. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="index"/> is out of allowable range of indexes for the collection. /// </exception> public override string GetKey (int index) { return base.GetKey (index); } /// <summary> /// Gets an array of header values stored in the specified <paramref name="index"/> position of /// the collection. /// </summary> /// <returns> /// An array of <see cref="string"/> that receives the header values if found; /// otherwise, <see langword="null"/>. /// </returns> /// <param name="index"> /// An <see cref="int"/> that represents the zero-based index of the header to find. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="index"/> is out of allowable range of indexes for the collection. /// </exception> public override string[] GetValues (int index) { var vals = base.GetValues (index); return vals != null && vals.Length > 0 ? vals : null; } /// <summary> /// Gets an array of header values stored in the specified <paramref name="header"/>. /// </summary> /// <returns> /// An array of <see cref="string"/> that receives the header values if found; /// otherwise, <see langword="null"/>. /// </returns> /// <param name="header"> /// A <see cref="string"/> that represents the name of the header to find. /// </param> public override string[] GetValues (string header) { var vals = base.GetValues (header); return vals != null && vals.Length > 0 ? vals : null; } /// <summary> /// Populates a <see cref="SerializationInfo"/> instance with the data /// needed to serialize this instance. /// </summary> /// <param name="serializationInfo"> /// A <see cref="SerializationInfo"/> to populate with the data. /// </param> /// <param name="streamingContext"> /// A <see cref="StreamingContext"/> that specifies the destination for /// the serialization. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="serializationInfo"/> is <see langword="null"/>. /// </exception> [ SecurityPermission ( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter ) ] public override void GetObjectData ( SerializationInfo serializationInfo, StreamingContext streamingContext ) { if (serializationInfo == null) throw new ArgumentNullException ("serializationInfo"); serializationInfo.AddValue ("InternallyUsed", _internallyUsed); serializationInfo.AddValue ("State", (int) _state); var cnt = Count; serializationInfo.AddValue ("Count", cnt); for (var i = 0; i < cnt; i++) { serializationInfo.AddValue (i.ToString (), GetKey (i)); serializationInfo.AddValue ((cnt + i).ToString (), Get (i)); } } /// <summary> /// Determines whether the specified header can be set for the request. /// </summary> /// <returns> /// <c>true</c> if the header is restricted; otherwise, <c>false</c>. /// </returns> /// <param name="headerName"> /// A <see cref="string"/> that represents the name of the header to test. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="headerName"/> is <see langword="null"/> or empty. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="headerName"/> contains invalid characters. /// </exception> public static bool IsRestricted (string headerName) { return isRestricted (checkName (headerName), false); } /// <summary> /// Determines whether the specified header can be set for the request or the response. /// </summary> /// <returns> /// <c>true</c> if the header is restricted; otherwise, <c>false</c>. /// </returns> /// <param name="headerName"> /// A <see cref="string"/> that represents the name of the header to test. /// </param> /// <param name="response"> /// <c>true</c> if does the test for the response; for the request, <c>false</c>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="headerName"/> is <see langword="null"/> or empty. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="headerName"/> contains invalid characters. /// </exception> public static bool IsRestricted (string headerName, bool response) { return isRestricted (checkName (headerName), response); } /// <summary> /// Implements the <see cref="ISerializable"/> interface and raises the deserialization event /// when the deserialization is complete. /// </summary> /// <param name="sender"> /// An <see cref="object"/> that represents the source of the deserialization event. /// </param> public override void OnDeserialization (object sender) { } /// <summary> /// Removes the specified request <paramref name="header"/> from the collection. /// </summary> /// <param name="header"> /// One of the <see cref="HttpRequestHeader"/> enum values, represents /// the request header to remove. /// </param> /// <exception cref="ArgumentException"> /// <paramref name="header"/> is a restricted header. /// </exception> /// <exception cref="InvalidOperationException"> /// The current <see cref="WebHeaderCollection"/> instance doesn't allow /// the request <paramref name="header"/>. /// </exception> public void Remove (HttpRequestHeader header) { doWithCheckingState (removeWithoutCheckingName, Convert (header), null, false, false); } /// <summary> /// Removes the specified response <paramref name="header"/> from the collection. /// </summary> /// <param name="header"> /// One of the <see cref="HttpResponseHeader"/> enum values, represents /// the response header to remove. /// </param> /// <exception cref="ArgumentException"> /// <paramref name="header"/> is a restricted header. /// </exception> /// <exception cref="InvalidOperationException"> /// The current <see cref="WebHeaderCollection"/> instance doesn't allow /// the response <paramref name="header"/>. /// </exception> public void Remove (HttpResponseHeader header) { doWithCheckingState (removeWithoutCheckingName, Convert (header), null, true, false); } /// <summary> /// Removes the specified header from the collection. /// </summary> /// <param name="name"> /// A <see cref="string"/> that represents the name of the header to remove. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="name"/> is <see langword="null"/> or empty. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="name"/> contains invalid characters. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="name"/> is a restricted header name. /// </para> /// </exception> /// <exception cref="InvalidOperationException"> /// The current <see cref="WebHeaderCollection"/> instance doesn't allow /// the header <paramref name="name"/>. /// </exception> public override void Remove (string name) { doWithCheckingState (removeWithoutCheckingName, checkName (name), null, false); } /// <summary> /// Sets the specified request <paramref name="header"/> to the specified value. /// </summary> /// <param name="header"> /// One of the <see cref="HttpRequestHeader"/> enum values, represents /// the request header to set. /// </param> /// <param name="value"> /// A <see cref="string"/> that represents the value of the request header to set. /// </param> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="header"/> is a restricted header. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="value"/> contains invalid characters. /// </para> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The length of <paramref name="value"/> is greater than 65,535 characters. /// </exception> /// <exception cref="InvalidOperationException"> /// The current <see cref="WebHeaderCollection"/> instance doesn't allow /// the request <paramref name="header"/>. /// </exception> public void Set (HttpRequestHeader header, string value) { doWithCheckingState (setWithoutCheckingName, Convert (header), value, false, true); } /// <summary> /// Sets the specified response <paramref name="header"/> to the specified value. /// </summary> /// <param name="header"> /// One of the <see cref="HttpResponseHeader"/> enum values, represents /// the response header to set. /// </param> /// <param name="value"> /// A <see cref="string"/> that represents the value of the response header to set. /// </param> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="header"/> is a restricted header. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="value"/> contains invalid characters. /// </para> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The length of <paramref name="value"/> is greater than 65,535 characters. /// </exception> /// <exception cref="InvalidOperationException"> /// The current <see cref="WebHeaderCollection"/> instance doesn't allow /// the response <paramref name="header"/>. /// </exception> public void Set (HttpResponseHeader header, string value) { doWithCheckingState (setWithoutCheckingName, Convert (header), value, true, true); } /// <summary> /// Sets the specified header to the specified value. /// </summary> /// <param name="name"> /// A <see cref="string"/> that represents the name of the header to set. /// </param> /// <param name="value"> /// A <see cref="string"/> that represents the value of the header to set. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="name"/> is <see langword="null"/> or empty. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="name"/> or <paramref name="value"/> contains invalid characters. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="name"/> is a restricted header name. /// </para> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The length of <paramref name="value"/> is greater than 65,535 characters. /// </exception> /// <exception cref="InvalidOperationException"> /// The current <see cref="WebHeaderCollection"/> instance doesn't allow /// the header <paramref name="name"/>. /// </exception> public override void Set (string name, string value) { doWithCheckingState (setWithoutCheckingName, checkName (name), value, true); } /// <summary> /// Converts the current <see cref="WebHeaderCollection"/> to an array of <see cref="byte"/>. /// </summary> /// <returns> /// An array of <see cref="byte"/> that receives the converted current /// <see cref="WebHeaderCollection"/>. /// </returns> public byte[] ToByteArray () { return Encoding.UTF8.GetBytes (ToString ()); } /// <summary> /// Returns a <see cref="string"/> that represents the current /// <see cref="WebHeaderCollection"/>. /// </summary> /// <returns> /// A <see cref="string"/> that represents the current <see cref="WebHeaderCollection"/>. /// </returns> public override string ToString () { var buff = new StringBuilder (); Count.Times (i => buff.AppendFormat ("{0}: {1}\r\n", GetKey (i), Get (i))); return buff.Append ("\r\n").ToString (); } #endregion #region Explicit Interface Implementations /// <summary> /// Populates the specified <see cref="SerializationInfo"/> with the data needed to serialize /// the current <see cref="WebHeaderCollection"/>. /// </summary> /// <param name="serializationInfo"> /// A <see cref="SerializationInfo"/> that holds the serialized object data. /// </param> /// <param name="streamingContext"> /// A <see cref="StreamingContext"/> that specifies the destination for the serialization. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="serializationInfo"/> is <see langword="null"/>. /// </exception> [SecurityPermission ( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter, SerializationFormatter = true)] void ISerializable.GetObjectData ( SerializationInfo serializationInfo, StreamingContext streamingContext) { GetObjectData (serializationInfo, streamingContext); } #endregion } }
// Filename: ShapeDisplay.cs // Description: A helper class for importing ESRI shapefiles and // creating/displaying shapes on a WPF canvas. // Comments: Uses the classes from ShapeFile.cs. // 2007-01-29 nschan Initial revision. using ESRI.ArcGIS.Client; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data.OleDb; using System.IO; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Shapes; using System.Windows.Threading; namespace TestShapeFile { /// <summary> /// The GeometryType enumeration defines geometry types that /// can be used when creating WPF shapes. Choosing a stream /// geometry type can improve rendering performance. /// </summary> public enum GeometryType { /// <summary> /// Use path geometry containing path figures. /// </summary> UsePathGeometry, /// <summary> /// Use StreamGeometry with StreamGeometryContext class /// to specify drawing instructions. /// </summary> UseStreamGeometry, /// <summary> /// Same as UseStreamGeometry except that the figures /// will be unstroked for greater performance (borders /// won't be displayed for the shapes). /// </summary> UseStreamGeometryNotStroked } /// <summary> /// ShapeDisplay is a helper class for importing ESRI shapefiles /// and creating/displaying shapes on a WPF canvas. During the /// import step, a progress window is displayed. This is implemented /// using the WPF single-threaded programming model, which allows /// tasks to be executed by a Dispatcher instance while keeping the /// UI responsive. /// </summary> public class ShapeDisplay { #region Delegates /// <summary> /// Defines the prototype for a method that reads a block /// of shapefile records. Such a method is intended to be /// executed by the Dispatcher. /// </summary> /// <param name="info">Shapefile read information.</param> public delegate void ReadNextPrototype(ShapeFileReadInfo info); /// <summary> /// Defines the prototype for a method that creates and displays /// a set of WPF shapes. Such a method is intended to be /// executed by the Dispatcher. /// </summary> /// <param name="info">Shapefile read information.</param> public delegate void DisplayNextPrototype(ShapeFileReadInfo info); #endregion Delegates #region Constants private const int readShapesBlockingFactor = 50; private const int displayShapesBlockingFactor = 10; private const string baseLonLatText = "Lon/Lat: "; #endregion Constants #region Private fields // UI components. private Window owner; private Canvas canvas; private GraphicsLayer grLayer; private Dispatcher dispatcher; //private ProgressWindow progressWindow; // Used during reading of a shapefile. private bool isReadingShapeFile; private bool cancelReadShapeFile; private int wpfShapeCount; // Used during creation of WPF shapes. private List<Shape> shapeList = new List<Shape>(); private GeometryType geometryType = GeometryType.UseStreamGeometryNotStroked; // Transformation from lon/lat to canvas coordinates. private TransformGroup shapeTransform; // Combined view transformation (zoom and pan). private TransformGroup viewTransform = new TransformGroup(); private ScaleTransform zoomTransform = new ScaleTransform(); private TranslateTransform panTransform = new TranslateTransform(); // For coloring of WPF shapes. private Brush[] shapeBrushes; private Random rand = new Random(379013); private Brush strokeBrush = new SolidColorBrush(Color.FromArgb(150, 150, 150, 150)); // For panning operations. private bool isPanningEnabled = true; Point prevMouseLocation; bool isMouseDragging; private double panTolerance = 1; // Displaying lon/lat coordinates on the canvas. bool isDisplayLonLatEnabled = true; Label lonLatLabel = new Label(); #endregion Private fields #region Constructor /// <summary> /// Constructor for the ShapeDisplay class. /// </summary> /// <param name="owner">Window that acts as an owner to child windows.</param> /// <param name="canvas">The canvas on which to create WPF shapes.</param> public ShapeDisplay(Window owner, Canvas canvas) { // Keep reference to a Window to act as the owner for a progress window. if (owner == null) throw new ArgumentNullException("owner"); this.owner = owner; // Keep reference to the canvas and add mouse event handlers // for implementing panning. if (canvas == null) throw new ArgumentNullException("canvas"); this.canvas = canvas; this.canvas.MouseEnter += canvas_MouseEnter; this.canvas.MouseDown += canvas_MouseDown; this.canvas.MouseMove += canvas_MouseMove; this.canvas.MouseUp += canvas_MouseUp; this.canvas.MouseLeave += canvas_MouseLeave; // Keep reference to the dispatcher for task execution. this.dispatcher = this.canvas.Dispatcher; // Add the zoom and pan transforms to the view transform. this.viewTransform.Children.Add(this.zoomTransform); this.viewTransform.Children.Add(this.panTransform); // Configure the lon/lat label. this.lonLatLabel.Opacity = 0.70; } /// <summary> /// Constructor for the ShapeDisplay class. /// </summary> /// <param name="owner">Window that acts as an owner to child windows.</param> /// <param name="canvas">The canvas on which to create WPF shapes.</param> public ShapeDisplay(Window owner, GraphicsLayer layer) { // Keep reference to a Window to act as the owner for a progress window. if (owner == null) throw new ArgumentNullException("owner"); this.owner = owner; // Keep reference to the canvas and add mouse event handlers // for implementing panning. if (layer == null) throw new ArgumentNullException("layer"); this.grLayer = layer; /*this.grLayer.MouseEnter += new MouseEventHandler(canvas_MouseEnter); this.grLayer.MouseDown += new System.Windows.Input.MouseButtonEventHandler(canvas_MouseDown); this.grLayer.MouseMove += new System.Windows.Input.MouseEventHandler(canvas_MouseMove); this.grLayer.MouseUp += new System.Windows.Input.MouseButtonEventHandler(canvas_MouseUp); this.grLayer.MouseLeave += new MouseEventHandler(canvas_MouseLeave);*/ // Keep reference to the dispatcher for task execution. this.dispatcher = this.canvas.Dispatcher; // Add the zoom and pan transforms to the view transform. this.viewTransform.Children.Add(this.zoomTransform); this.viewTransform.Children.Add(this.panTransform); // Configure the lon/lat label. this.lonLatLabel.Opacity = 0.70; } #endregion Constructor #region Properties /// <summary> /// Indicates if a shapefile read operation is in progress. /// </summary> public bool IsReadingShapeFile { get { return this.isReadingShapeFile; } } /// <summary> /// Indicates if we can perform a zoom operation. This is true /// the shape transform has been set (meaning at least one shapefile /// has been loaded). /// </summary> public bool CanZoom { get { return (this.shapeTransform != null); } } /// <summary> /// Indicates if panning is enabled or not. This /// applies to both mouse and keyboard panning. /// </summary> public bool IsPanningEnabled { get { return this.isPanningEnabled; } set { this.isPanningEnabled = value; } } /// <summary> /// Indicates if display of lon/lat coordinates /// is enabled or not. /// </summary> public bool IsDisplayLonLatEnabled { get { return this.isDisplayLonLatEnabled; } set { if (this.isDisplayLonLatEnabled != value) { this.isDisplayLonLatEnabled = value; if (this.isDisplayLonLatEnabled) this.DisplayLonLatDefault(); else this.canvas.Children.Remove(this.lonLatLabel); } } } /// <summary> /// Specifies the geometry type to use when creating WPF shapes. /// </summary> public GeometryType GeometryType { get { return this.geometryType; } set { this.geometryType = value; } } #endregion Properties #region Public methods /// <summary> /// Read shapes and attributes from the given shapefile. /// </summary> /// <param name="fileName">Full pathname of a shapefile.</param> public void ReadShapeFile(string fileName) { this.isReadingShapeFile = true; this.cancelReadShapeFile = false; // Create an object to store shapefile info during the read. ShapeFileReadInfo info = new ShapeFileReadInfo(); info.FileName = fileName; info.ShapeFile = new ShapeFile(); info.Stream = null; info.NumberOfBytesRead = 0; info.RecordIndex = 0; try { // Read the File Header first. info.Stream = new FileStream(fileName, FileMode.Open, FileAccess.Read); info.ShapeFile.ReadShapeFileHeader(info.Stream); info.NumberOfBytesRead = ShapeFileHeader.Length; // Schedule the first read of shape file records using the dispatcher. this.dispatcher.BeginInvoke(DispatcherPriority.Normal, new ReadNextPrototype(this.ReadNextShapeRecord), info); } catch (IOException ex) { this.EndReadShapeFile(info); MessageBox.Show(ex.Message); } } /// <summary> /// Request the current shapefile read operation to be cancelled. /// </summary> public void CancelReadShapeFile() { this.cancelReadShapeFile = true; this.HideProgress(); } /// <summary> /// Reset the canvas. /// </summary> public void ResetCanvas() { // End reading of the shapefile. this.EndReadShapeFile(); // Clear the canvas. this.canvas.Children.Clear(); this.wpfShapeCount = 0; // Reset transformations. this.panTransform.X = 0; this.panTransform.Y = 0; this.zoomTransform.ScaleX = 1; this.zoomTransform.ScaleY = 1; this.shapeTransform = null; } /// <summary> /// Perform a zoom operation about the current center /// of the canvas. /// </summary> /// <param name="zoomFactor">Zoom multiplication factor (1, 2, 4, etc).</param> public void Zoom(double zoomFactor) { // Compute the coordinates of the center of the canvas // in terms of pre-view transformation values. We do this // by applying the inverse of the view transform. Point canvasCenter = new Point(this.canvas.ActualWidth / 2, this.canvas.ActualHeight / 2); canvasCenter = this.viewTransform.Inverse.Transform(canvasCenter); // Temporarily reset the panning transformation. this.panTransform.X = 0; this.panTransform.Y = 0; // Set the new zoom transformation scale factors. this.zoomTransform.ScaleX = zoomFactor; this.zoomTransform.ScaleY = zoomFactor; // Apply the updated view transform to the canvas center. // This gives us the updated location of the center point // on the canvas. By differencing this with the desired // center of the canvas, we can determine the ideal panning // transformation parameters. Point canvasLocation = this.viewTransform.Transform(canvasCenter); this.panTransform.X = this.canvas.ActualWidth / 2 - canvasLocation.X; this.panTransform.Y = this.canvas.ActualHeight / 2 - canvasLocation.Y; } /// <summary> /// Perform a panning operation given X and Y factor values /// which can be thought of as a fraction of the canvas actual /// width or height. /// </summary> /// <param name="factorX">Fraction of canvas actual width to pan horizontally.</param> /// <param name="factorY">Fraction of canvas actual height to pan vertically.</param> public void Pan(double factorX, double factorY) { if (!this.isPanningEnabled) return; this.panTransform.X += (factorX * this.canvas.ActualWidth); this.panTransform.Y += (factorY * this.canvas.ActualHeight); } /// <summary> /// Save the owner object (the main window) to XAML. /// This method may take a long time to run if there /// are many objects on the canvas (shapefile > 1 Mb). /// </summary> /// <param name="stream">Output stream for writing the XAML.</param> public void SaveToXaml(Stream stream) { System.Windows.Markup.XamlWriter.Save(this.owner, stream); } #endregion Public methods #region Transformations /// <summary> /// Computes a transformation so that the shapefile geometry /// will maximize the available space on the canvas and be /// perfectly centered as well. /// </summary> /// <param name="info">Shapefile information.</param> /// <returns>A transformation object.</returns> private TransformGroup CreateShapeTransform(ShapeFileReadInfo info) { // Bounding box for the shapefile. double xmin = info.ShapeFile.FileHeader.XMin; double xmax = info.ShapeFile.FileHeader.XMax; double ymin = info.ShapeFile.FileHeader.YMin; double ymax = info.ShapeFile.FileHeader.YMax; // Width and height of the bounding box. double width = Math.Abs(xmax - xmin); double height = Math.Abs(ymax - ymin); // Aspect ratio of the bounding box. double aspectRatio = width / height; // Aspect ratio of the canvas. double canvasRatio = this.canvas.ActualWidth / this.canvas.ActualHeight; // Compute a scale factor so that the shapefile geometry // will maximize the space used on the canvas while still // maintaining its aspect ratio. double scaleFactor = 1.0; if (aspectRatio < canvasRatio) scaleFactor = this.canvas.ActualHeight / height; else scaleFactor = this.canvas.ActualWidth / width; // Compute the scale transformation. Note that we flip // the Y-values because the lon/lat grid is like a cartesian // coordinate system where Y-values increase upwards. ScaleTransform xformScale = new ScaleTransform(scaleFactor, -scaleFactor); // Compute the translate transformation so that the shapefile // geometry will be centered on the canvas. TranslateTransform xformTrans = new TranslateTransform(); xformTrans.X = (this.canvas.ActualWidth - (xmin + xmax) * scaleFactor) / 2; xformTrans.Y = (this.canvas.ActualHeight + (ymin + ymax) * scaleFactor) / 2; // Add the two transforms to a transform group. TransformGroup xformGroup = new TransformGroup(); xformGroup.Children.Add(xformScale); xformGroup.Children.Add(xformTrans); return xformGroup; } #endregion Transformations #region Brushes for gradient coloring /// <summary> /// Create a set of linear gradient brushes which we can use /// as a random pool for assignment to WPF shapes. A higher /// gradient factor results in a stronger gradient effect. /// </summary> /// <param name="gradientFactor">Gradient factor from 0 to 1.</param> /// <param name="gradientAngle">Direction of gradient in degrees.</param> private void CreateShapeBrushes(double gradientFactor, double gradientAngle) { // Pick a set of base colors for the brushes. Color[] colors = new Color[] { Colors.Crimson, Colors.ForestGreen, Colors.RoyalBlue, Colors.Navy, Colors.DarkSeaGreen, Colors.LightSlateGray, Colors.DarkKhaki, Colors.Olive, Colors.Indigo, Colors.Violet }; // Create one brush per color. this.shapeBrushes = new Brush[colors.Length]; for (int i = 0; i < this.shapeBrushes.Length; i++) { this.shapeBrushes[i] = new LinearGradientBrush(ShapeDisplay.GetAdjustedColor(colors[i], gradientFactor), colors[i], gradientAngle); } } /// <summary> /// Given an input color, return an adjusted color using a /// factor value which ranges from 0 to 1. The larger the factor, /// the lighter the adjusted color. A factor of 0 means no adjustment /// to the input color. /// </summary> /// <remarks> /// Note that the alpha component of the input color is not adjusted. /// </remarks> /// <param name="inColor">Input color.</param> /// <param name="factor">Color adjustment factor, from 0 to 1.</param> /// <returns>An adjusted color value.</returns> private static Color GetAdjustedColor(Color inColor, double factor) { int red = inColor.R + (int)((255 - inColor.R) * factor); red = Math.Max(0, red); red = Math.Min(255, red); int green = inColor.G + (int)((255 - inColor.G) * factor); green = Math.Max(0, green); green = Math.Min(255, green); int blue = inColor.B + (int)((255 - inColor.B) * factor); blue = Math.Max(0, blue); blue = Math.Min(255, blue); return Color.FromArgb(inColor.A, (byte)red, (byte)green, (byte)blue); } /// <summary> /// Get the next brush that can be used to fill a WPF shape. /// </summary> /// <returns>A randomly selected brush.</returns> private Brush GetRandomShapeBrush() { int index = this.rand.Next() % this.shapeBrushes.Length; return this.shapeBrushes[index]; } #endregion Brushes for gradient coloring #region Reading ESRI shapes /// <summary> /// Read a block of shape file records and possibly schedule /// the next read with the dispatcher. /// </summary> /// <param name="info">Shapefile read information.</param> private void ReadNextShapeRecord(ShapeFileReadInfo info) { if (this.cancelReadShapeFile) return; try { // Read a block of shape records. for (int i = 0; i < ShapeDisplay.readShapesBlockingFactor; i++) { ShapeFileRecord record = info.ShapeFile.ReadShapeFileRecord(info.Stream); info.NumberOfBytesRead += (4 + record.ContentLength) * 2; } } catch (FileFormatException ex) { this.EndReadShapeFile(info); MessageBox.Show(ex.Message); return; } catch (IOException) { // Display the end progress (100 percent). this.ShowProgress("Reading shapefile...", 100); // Read attributes from the associated dBASE file. this.ReadDbaseAttributes(info); // Display shapes on the canvas. if (info.ShapeFile.Records.Count > 0) this.DisplayShapes(info); else this.EndReadShapeFile(info); return; } // Display the current progress. double progressValue = info.NumberOfBytesRead * 100.0 / (info.ShapeFile.FileHeader.FileLength * 2); progressValue = Math.Min(100, progressValue); this.ShowProgress("Reading shapefile...", progressValue); // Schedule the next read at Background priority. this.dispatcher.BeginInvoke(DispatcherPriority.Background, new ReadNextPrototype(this.ReadNextShapeRecord), info); } /// <summary> /// Perform some cleanup at the end of reading a shapefile. /// </summary> private void EndReadShapeFile() { this.HideProgress(); this.isReadingShapeFile = false; this.cancelReadShapeFile = true; } public delegate void GeometryAddEventHandler(PointCollection points); public event GeometryAddEventHandler GeometryAdd; /// <summary> /// Perform some cleanup at the end of reading a shapefile. /// </summary> /// <param name="info">Shapefile read information.</param> private void EndReadShapeFile(ShapeFileReadInfo info) { if (info != null && info.Stream != null) { info.Stream.Close(); info.Stream.Dispose(); info.Stream = null; } this.EndReadShapeFile(); } /// <summary> /// Read dBASE file attributes. /// </summary> /// <param name="info">Shapefile read information.</param> private void ReadDbaseAttributes(ShapeFileReadInfo info) { // Read attributes from the associated dBASE file. try { string dbaseFile = info.FileName.Replace(".shp", ".dbf"); dbaseFile = dbaseFile.Replace(".SHP", ".DBF"); info.ShapeFile.ReadAttributes(dbaseFile); } catch (OleDbException ex) { // Note: An exception will occur if the filename of the dBASE // file does not follow 8.3 naming conventions. In this case, // you must use its short (MS-DOS) filename. MessageBox.Show(ex.Message); // Activate the window. this.owner.Activate(); } } #endregion Reading ESRI shapes #region Creating / displaying WPF shapes /// <summary> /// Create a WPF shape given a shapefile record. /// </summary> /// <param name="shapeName">The name of the WPF shape.</param> /// <param name="record">Shapefile record.</param> /// <returns>The created WPF shape.</returns> private Shape CreateWPFShape(string shapeName, ShapeFileRecord record) { // Create a new geometry. Geometry geometry; if (this.geometryType == GeometryType.UsePathGeometry) geometry = this.CreatePathGeometry(record); else geometry = this.CreateStreamGeometry(record); // Transform the geometry based on current zoom and pan settings. //geometry.Transform = this.viewTransform; // Create a new WPF Path. System.Windows.Shapes.Path path = new System.Windows.Shapes.Path(); // Assign the geometry to the path and set its name. path.Data = geometry; path.Name = shapeName; // Set path properties. path.StrokeThickness = 0.5; if (record.ShapeType == (int)ShapeType.Polygon) { path.Stroke = this.strokeBrush; path.Fill = this.GetRandomShapeBrush(); } else { path.Stroke = Brushes.DimGray; } // Return the created WPF shape. return path; } /// <summary> /// Create a PathGeometry given a shapefile record. /// </summary> /// <param name="record">Shapefile record.</param> /// <returns>A PathGeometry instance.</returns> private Geometry CreatePathGeometry(ShapeFileRecord record) { // Create a new geometry. PathGeometry geometry = new PathGeometry(); // Add figures to the geometry. for (int i = 0; i < record.NumberOfParts; i++) { // Create a new path figure. PathFigure figure = new PathFigure(); // Determine the starting index and the end index // into the points array that defines the figure. int start = record.Parts[i]; int end; if (record.NumberOfParts > 1 && i != (record.NumberOfParts - 1)) end = record.Parts[i + 1]; else end = record.NumberOfPoints; // Add line segments to the figure. for (int j = start; j < end; j++) { System.Windows.Point pt = record.Points[j]; // Transform from lon/lat to canvas coordinates. pt = this.shapeTransform.Transform(pt); if (j == start) figure.StartPoint = pt; else figure.Segments.Add(new LineSegment(pt, true)); } // Add the new figure to the geometry. geometry.Figures.Add(figure); } // Return the created path geometry. return geometry; } public List<Geometry> Geos = new List<Geometry>(); /// <summary> /// Create a StreamGeometry given a shapefile record. /// </summary> /// <param name="record">Shapefile record.</param> /// <returns>A StreamGeometry instance.</returns> private Geometry CreateStreamGeometry(ShapeFileRecord record) { // Create a new stream geometry. StreamGeometry geometry = new StreamGeometry(); PointCollection points = new PointCollection(); // Obtain the stream geometry context for drawing each part. //using (StreamGeometryContext ctx = geometry.Open()) { // Draw figures. for (int i = 0; i < record.NumberOfParts; i++) { // Determine the starting index and the end index // into the points array that defines the figure. int start = record.Parts[i]; int end; if (record.NumberOfParts > 1 && i != (record.NumberOfParts - 1)) end = record.Parts[i + 1]; else end = record.NumberOfPoints; // Draw the figure. for (int j = start; j < end; j++) { System.Windows.Point pt = record.Points[j]; points.Add(pt); // Transform from lon/lat to canvas coordinates. //pt = this.shapeTransform.Transform(pt); // Decide if the line segments are stroked or not. For the // PolyLine type it must be stroked. bool isStroked = (record.ShapeType == (int)ShapeType.PolyLine) || !(this.geometryType == GeometryType.UseStreamGeometryNotStroked); // Register the drawing instruction. if (j == start) { } //ctx.BeginFigure(pt, true, false); //ctx.LineTo(pt, isStroked, true); } if (GeometryAdd != null) { GeometryAdd(points); points.Clear(); } } } //Geos.Add(geometry); // Return the created stream geometry. return geometry; } /// <summary> /// Create a WPF shape to represent a shapefile point or /// multipoint record. /// </summary> /// <param name="shapeName">The name of the WPF shape.</param> /// <param name="record">Shapefile record.</param> /// <returns>The created WPF shape.</returns> private Shape CreateWPFPoint(string shapeName, ShapeFileRecord record) { // Create a new geometry. GeometryGroup geometry = new GeometryGroup(); // Add ellipse geometries to the group. foreach (Point pt in record.Points) { // Create a new ellipse geometry. EllipseGeometry ellipseGeo = new EllipseGeometry(); // Transform center point of the ellipse from lon/lat to // canvas coordinates. ellipseGeo.Center = this.shapeTransform.Transform(pt); // Set the size of the ellipse. ellipseGeo.RadiusX = 0.1; ellipseGeo.RadiusY = 0.1; // Add the ellipse to the geometry group. geometry.Children.Add(ellipseGeo); } // Transform the geometry based on current zoom and pan settings. geometry.Transform = this.viewTransform; // Add the geometry to a new Path and set path properties. System.Windows.Shapes.Path path = new System.Windows.Shapes.Path(); path.Data = geometry; path.Name = shapeName; path.Fill = Brushes.Crimson; path.StrokeThickness = 1; path.Stroke = Brushes.DimGray; // Return the created WPF shape. return path; } /// <summary> /// Begin creating and displaying WPF shapes on the canvas. /// </summary> private void DisplayShapes(ShapeFileReadInfo info) { // Create shape brushes. if (this.shapeBrushes == null) this.CreateShapeBrushes(0.40, 45); // Set up the transformation for WPF shapes. if (this.shapeTransform == null) this.shapeTransform = this.CreateShapeTransform(info); // Schedule display of the first block of shapefile records // using the dispatcher. this.dispatcher.BeginInvoke(DispatcherPriority.Normal, new DisplayNextPrototype(this.DisplayNextShapeRecord), info); } /// <summary> /// Display a block of shape records as WPF shapes, and schedule /// the next display with the dispatcher if needed. /// </summary> /// <param name="info">Shapefile read information.</param> private void DisplayNextShapeRecord(ShapeFileReadInfo info) { if (this.cancelReadShapeFile) return; // Create a block of WPF shapes and add them to the shape list. this.shapeList.Clear(); int index = info.RecordIndex; for (; index < (info.RecordIndex + ShapeDisplay.displayShapesBlockingFactor); index++) { if (index >= info.ShapeFile.Records.Count) break; ShapeFileRecord record = info.ShapeFile.Records[index]; // Set the name of the WPF shape. ++this.wpfShapeCount; string shapeName = String.Format(System.Globalization.CultureInfo.InvariantCulture, "Shape{0}", this.wpfShapeCount); // Create the WPF shape. Shape shape; if (record.NumberOfParts == 0) shape = this.CreateWPFPoint(shapeName, record); else shape = this.CreateWPFShape(shapeName, record); // Set a tooltip for the shape that displays up to 5 attribute values. shape.ToolTip = shape.Name; if (record.Attributes != null) { string attr = String.Empty; for (int i = 0; i < Math.Min(5, record.Attributes.ItemArray.GetLength(0)); i++) { attr += (", " + record.Attributes[i].ToString()); } shape.ToolTip += attr; } // Add the shape to the shape list. //this.shapeList.Add(shape); // If the record just processed is very large, then don't process // any further records. if (record.Points.Count > 5000) { ++index; break; } } // Set the record index to read next (as part of the // next dispatched task). info.RecordIndex = index; // Add the newly created WPF shapes to the canvas. foreach (Shape shape in this.shapeList) { this.canvas.Children.Add(shape); } this.shapeList.Clear(); // Display the current progress. double progressValue = (index * 100.0) / info.ShapeFile.Records.Count; progressValue = Math.Min(100, progressValue); this.ShowProgress("Creating WPF shapes...", progressValue); // See if we need to dispatch another display operation. if (index < info.ShapeFile.Records.Count) { // Schedule the next display at Background priority. this.dispatcher.BeginInvoke(DispatcherPriority.Background, new DisplayNextPrototype(this.DisplayNextShapeRecord), info); } else { // End the progress. this.ShowProgress("Creating WPF shapes...", 100); this.EndReadShapeFile(info); } } #endregion Creating / displaying WPF shapes #region Displaying progress /// <summary> /// Show the progress window with the given progress value. /// </summary> /// <param name="progressText">Progress text to display.</param> /// <param name="progressValue">Progress value from 0 to 100 percent.</param> private void ShowProgress(string progressText, double progressValue) { /*if ( this.progressWindow == null ) { // Create a new progress window. this.progressWindow = new ProgressWindow(); this.progressWindow.Owner = this.owner; this.progressWindow.Cancel += new CancelEventHandler(this.progressWindow_Cancel); this.progressWindow.Closed += new System.EventHandler(this.progressWindow_Closed); this.progressWindow.Title = "Import Shapefile"; } // Show the progress window with new progress text and value. this.progressWindow.ProgressText = progressText; this.progressWindow.ProgressValue = progressValue; this.progressWindow.Show(); */ } /// <summary> /// Hide the progress window. /// </summary> private void HideProgress() { /*if ( this.progressWindow != null ) { this.progressWindow.Close(); }*/ } /// <summary> /// Handle the Cancel button being pressed in the progress window. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event arguments.</param> private void progressWindow_Cancel(object sender, CancelEventArgs e) { this.EndReadShapeFile(); } /// <summary> /// Handle closing of the progress window. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event arguments.</param> private void progressWindow_Closed(object sender, EventArgs e) { //this.progressWindow = null; } #endregion Displaying progress #region Lon/lat coordinates /// <summary> /// Given a canvas position, convert it to a longitude /// and latitude coordinate. /// </summary> /// <param name="canvasPosition">A canvas position or location.</param> /// <returns>The corresponding point in lon/lat coordinates.</returns> private Point GetLonLatCoordinates(Point canvasPosition) { // Apply the inverse of the view transformation. Point p1 = this.viewTransform.Inverse.Transform(canvasPosition); // Apply the inverse of the shape transformation. if (this.shapeTransform != null) { Point p2 = this.shapeTransform.Inverse.Transform(p1); return p2; } return p1; } /// <summary> /// Given a lon/lat coordinate, determine the corresponding /// display text. /// </summary> /// <param name="lonLat">A lon/lat coordinate.</param> /// <returns>Formatted lon/lat display text.</returns> private static string GetLonLatDisplayText(Point lonLat) { string text = ShapeDisplay.baseLonLatText; if (lonLat.X < -180 || lonLat.X > 180 || lonLat.Y < -90 || lonLat.Y > 90) text += "n/a"; else text += String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:0.00}, {1:0.00}", lonLat.X, lonLat.Y); return text; } /// <summary> /// Given a canvas position, display the corresponding /// lon/lat coordinates on the canvas. /// </summary> /// <param name="canvasPosition">A canvas position or location.</param> private void DisplayLonLatCoord(Point canvasPosition) { // Remove the lon/lat label from the canvas first. this.canvas.Children.Remove(this.lonLatLabel); if (this.shapeTransform != null) { // Convert from canvas position to lon/lat coordinates. Point lonLat = this.GetLonLatCoordinates(canvasPosition); // Convert lon/lat value to a display string. this.lonLatLabel.Content = ShapeDisplay.GetLonLatDisplayText(lonLat); // Add the label back to the canvas. This ensures that // it will appear on top of all other canvas elements. this.canvas.Children.Add(this.lonLatLabel); } } /// <summary> /// Display some default text in the lon/lat label. /// </summary> private void DisplayLonLatDefault() { // Remove the lon/lat label from the canvas first. this.canvas.Children.Remove(this.lonLatLabel); // Set the default text to display. this.lonLatLabel.Content = ShapeDisplay.baseLonLatText + "n/a"; // Add the label back to the canvas. This ensures that // it will appear on top of all other canvas elements. this.canvas.Children.Add(this.lonLatLabel); } #endregion Lon/lat coordinates #region Mouse handlers /// <summary> /// Handle the MouseEnter event for the canvas. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event arguments.</param> private void canvas_MouseEnter(object sender, MouseEventArgs e) { this.isMouseDragging = false; } /// <summary> /// Handle the MouseDown event for the canvas. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event arguments.</param> private void canvas_MouseDown(object sender, MouseButtonEventArgs e) { if (this.shapeTransform == null) return; // Display lon/lat coordinates if needed. Point canvasPosition = e.GetPosition(this.canvas); if (this.isDisplayLonLatEnabled) this.DisplayLonLatCoord(canvasPosition); // Update previous mouse location for start of dragging. this.prevMouseLocation = canvasPosition; this.isMouseDragging = true; } /// <summary> /// Handle the MouseMove event for the canvas. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event arguments.</param> private void canvas_MouseMove(object sender, MouseEventArgs e) { // Implement panning with the mouse. if (this.isMouseDragging) { if (!this.isPanningEnabled) return; // Obtain the current mouse location and compute the // difference with the previous mouse location. Point currMouseLocation = e.GetPosition(this.canvas); double xOffset = currMouseLocation.X - this.prevMouseLocation.X; double yOffset = currMouseLocation.Y - this.prevMouseLocation.Y; // To avoid panning on every single mouse move, we check // if the movement is larger than the pan tolerance. if (Math.Abs(xOffset) > this.panTolerance || Math.Abs(yOffset) > this.panTolerance) { this.panTransform.X += xOffset; this.panTransform.Y += yOffset; this.prevMouseLocation = currMouseLocation; } } else { // Display lon/lat coordinates if needed. if (this.isDisplayLonLatEnabled) this.DisplayLonLatCoord(e.GetPosition(this.canvas)); } } /// <summary> /// Handle the MouseUp event for the canvas. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event arguments.</param> private void canvas_MouseUp(object sender, MouseButtonEventArgs e) { this.isMouseDragging = false; } /// <summary> /// Handle the MouseLeave event for the canvas. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event arguments.</param> private void canvas_MouseLeave(object sender, MouseEventArgs e) { this.isMouseDragging = false; } #endregion Mouse handlers } } // END
using Plugin.Connectivity.Abstractions; using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using System.Linq; namespace Plugin.Connectivity { /// <summary> /// Implementation for Connectivity /// </summary> [Foundation.Preserve(AllMembers = true)] public class ConnectivityImplementation : BaseConnectivity { Task initialTask = null; /// <summary> /// Default constructor /// </summary> public ConnectivityImplementation() { //start an update on the background. initialTask = Task.Run(() => { UpdateConnected(false);}); Reachability.ReachabilityChanged += ReachabilityChanged; } async void ReachabilityChanged(object sender, EventArgs e) { //Add in artifical delay so the connection status has time to change //else it will return true no matter what. await Task.Delay(100); UpdateConnected(); } private bool isConnected; private NetworkStatus previousInternetStatus = NetworkStatus.NotReachable; private void UpdateConnected(bool triggerChange = true) { var remoteHostStatus = Reachability.RemoteHostStatus(); var internetStatus = Reachability.InternetConnectionStatus(); var previouslyConnected = isConnected; isConnected = (internetStatus == NetworkStatus.ReachableViaCarrierDataNetwork || internetStatus == NetworkStatus.ReachableViaWiFiNetwork) || (remoteHostStatus == NetworkStatus.ReachableViaCarrierDataNetwork || remoteHostStatus == NetworkStatus.ReachableViaWiFiNetwork); if (triggerChange) { if (previouslyConnected != isConnected || previousInternetStatus != internetStatus) OnConnectivityChanged(new ConnectivityChangedEventArgs { IsConnected = isConnected }); var connectionTypes = this.ConnectionTypes.ToArray(); OnConnectivityTypeChanged(new ConnectivityTypeChangedEventArgs { IsConnected = isConnected, ConnectionTypes = connectionTypes }); } previousInternetStatus = internetStatus; } /// <summary> /// Gets if there is an active internet connection /// </summary> public override bool IsConnected { get { if (initialTask?.IsCompleted ?? true) { UpdateConnected(false); return isConnected; } //await for the initial run to complete initialTask.Wait(); return isConnected; } } /// <summary> /// Tests if a host name is pingable /// </summary> /// <param name="host">The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address (127.0.0.1)</param> /// <param name="msTimeout">Timeout in milliseconds</param> /// <returns></returns> public override async Task<bool> IsReachable(string host, int msTimeout = 5000) { if (string.IsNullOrEmpty(host)) throw new ArgumentNullException(nameof(host)); if (!IsConnected) return false; return await IsRemoteReachable(host, 80, msTimeout); } /// <summary> /// Tests if a remote host name is reachable /// </summary> /// <param name="host">Host name can be a remote IP or URL of website</param> /// <param name="port">Port to attempt to check is reachable.</param> /// <param name="msTimeout">Timeout in milliseconds.</param> /// <returns></returns> public override async Task<bool> IsRemoteReachable(string host, int port = 80, int msTimeout = 5000) { if (string.IsNullOrEmpty(host)) throw new ArgumentNullException(nameof(host)); if (!IsConnected) return false; host = host.Replace("http://www.", string.Empty). Replace("http://", string.Empty). Replace("https://www.", string.Empty). Replace("https://", string.Empty). TrimEnd('/'); return await Task.Run(() => { try { var clientDone = new ManualResetEvent(false); var reachable = false; var hostEntry = new DnsEndPoint(host, port); using (var socket = new Socket(SocketType.Stream, ProtocolType.Tcp)) { var socketEventArg = new SocketAsyncEventArgs { RemoteEndPoint = hostEntry }; socketEventArg.Completed += (s, e) => { reachable = e.SocketError == SocketError.Success; clientDone.Set(); }; clientDone.Reset(); socket.ConnectAsync(socketEventArg); clientDone.WaitOne(msTimeout); return reachable; } } catch (Exception ex) { Debug.WriteLine("Unable to reach: " + host + " Error: " + ex); return false; } }); } /// <summary> /// Gets the list of all active connection types. /// </summary> public override IEnumerable<ConnectionType> ConnectionTypes { get { var statuses = Reachability.GetActiveConnectionType(); foreach (var status in statuses) { switch (status) { case NetworkStatus.ReachableViaCarrierDataNetwork: yield return ConnectionType.Cellular; break; case NetworkStatus.ReachableViaWiFiNetwork: yield return ConnectionType.WiFi; break; default: yield return ConnectionType.Other; break; } } } } /// <summary> /// Not supported on iOS /// </summary> public override IEnumerable<UInt64> Bandwidths { get { return new UInt64[] { }; } } private bool disposed = false; /// <summary> /// Dispose /// </summary> /// <param name="disposing"></param> public override void Dispose(bool disposing) { if (!disposed) { if (disposing) { Reachability.ReachabilityChanged -= ReachabilityChanged; Reachability.Dispose(); } disposed = true; } base.Dispose(disposing); } } }
using System.Collections.Generic; using Ivvy.API.Common; using Newtonsoft.Json; namespace Ivvy.API.Invoice { public class Invoice { public enum StatusOptions { NotPaid = 0, UnConfirmedPaid = 1, Paid = 2, WrittenOff = 3, Cancelled = 4, Refunded = 5 } public enum RefTypes { Custom = 0, EventRegistration = 1, MembershipSignUp = 2, MembershipRenewal = 3, VenueBooking = 4 } [JsonProperty("id")] public string Id { get; set; } [JsonProperty("reference")] public string Reference { get; set; } [JsonProperty("title")] public string Title { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("currency")] public string Currency { get; set; } [JsonProperty("totalCost")] public float? TotalCost { get; set; } [JsonProperty("totalTaxCost")] public float? TotalTaxCost { get; set; } [JsonProperty("amountPaid")] public float? AmountPaid { get; set; } [JsonProperty("toContactEmail")] public string ToContactEmail { get; set; } [JsonProperty("toContactName")] public string ToContactName { get; set; } [JsonProperty("currentStatus")] public StatusOptions CurrentStatus { get; set; } [JsonProperty("createdDate")] public string CreatedDate { get; set; } [JsonProperty("modifiedDate")] public string ModifiedDate { get; set; } [JsonProperty("issuedDate")] public string IssuedDate { get; set; } [JsonProperty("refType")] public RefTypes RefType { get; set; } [JsonProperty("refId")] public string RefId { get; set; } [JsonProperty("taxRateUsed")] public string TaxRateUsed { get; set; } [JsonProperty("isTaxCharged")] public string IsTaxCharged { get; set; } [JsonProperty("paymentDueDate")] public string PaymentDueDate { get; set; } [JsonProperty("eventId")] public long? EventId { get; set; } [JsonProperty("venueId")] public long? VenueId { get; set; } [JsonProperty("Company")] public Contact.Company Company { get; set; } [JsonProperty("toContactId")] public string ToContactId { get; set; } [JsonProperty("Contact")] public Contact.Contact Contact { get; set; } [JsonProperty("toAddress")] public Address ToAddress { get; set; } [JsonProperty("items")] public List<Item> Items { get; set; } [JsonProperty("payments")] public List<InvoicePayment> Payments { get; set; } [JsonProperty("refunds")] public List<InvoiceRefund> Refunds { get; set; } [JsonProperty("bookingCode")] public string BookingCode { get; set; } [JsonProperty("bookingId")] public int? BookingId { get; set; } } }
extern alias dialog; extern alias dialog10; using System; using System.ComponentModel.Design; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using EnvDTE; using Microsoft.VisualStudio; using Microsoft.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using NuGet.Options; using NuGet.VisualStudio; using NuGet.VisualStudio.Resources; using NuGetConsole; using NuGetConsole.Implementation; using ManagePackageDialog = dialog::NuGet.Dialog.PackageManagerWindow; using VS10ManagePackageDialog = dialog10::NuGet.Dialog.PackageManagerWindow; namespace NuGet.Tools { /// <summary> /// This is the class that implements the package exposed by this assembly. /// </summary> [PackageRegistration(UseManagedResourcesOnly = true)] [InstalledProductRegistration("#110", "#112", NuGetPackage.ProductVersion, IconResourceID = 400)] [ProvideMenuResource("Menus.ctmenu", 1)] [ProvideToolWindow(typeof(PowerConsoleToolWindow), Style = VsDockStyle.Tabbed, Window = "{34E76E81-EE4A-11D0-AE2E-00A0C90FFFC3}", // this is the guid of the Output tool window, which is present in both VS and VWD Orientation = ToolWindowOrientation.Right)] [ProvideOptionPage(typeof(PackageSourceOptionsPage), "Package Manager", "Package Sources", 113, 114, true)] [ProvideOptionPage(typeof(GeneralOptionPage), "Package Manager", "General", 113, 115, true)] [ProvideBindingPath] // Definition dll needs to be on VS binding path [ProvideAutoLoad(GuidList.guidAutoLoadNuGetString)] [FontAndColorsRegistration( "Package Manager Console", NuGetConsole.Implementation.GuidList.GuidPackageManagerConsoleFontAndColorCategoryString, "{" + GuidList.guidNuGetPkgString + "}")] [Guid(GuidList.guidNuGetPkgString)] public sealed class NuGetPackage : Package { // This product version will be updated by the build script to match the daily build version. // It is displayed in the Help - About box of Visual Studio public const string ProductVersion = "1.7.0.0"; private static readonly string[] _visualizerSupportedSKUs = new[] { "Premium", "Ultimate" }; private uint _debuggingContextCookie, _solutionBuildingContextCookie; private DTE _dte; private IConsoleStatus _consoleStatus; private IVsMonitorSelection _vsMonitorSelection; private bool? _isVisualizerSupported; private IPackageRestoreManager _packageRestoreManager; public NuGetPackage() { HttpClient.DefaultCredentialProvider = new VSRequestCredentialProvider(); } /// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { base.Initialize(); // get the UI context cookie for the debugging mode _vsMonitorSelection = (IVsMonitorSelection)GetService(typeof(IVsMonitorSelection)); // get debugging context cookie Guid debuggingContextGuid = VSConstants.UICONTEXT_Debugging; _vsMonitorSelection.GetCmdUIContextCookie(ref debuggingContextGuid, out _debuggingContextCookie); // get the solution building cookie Guid solutionBuildingContextGuid = VSConstants.UICONTEXT_SolutionBuilding; _vsMonitorSelection.GetCmdUIContextCookie(ref solutionBuildingContextGuid, out _solutionBuildingContextCookie); _dte = ServiceLocator.GetInstance<DTE>(); _consoleStatus = ServiceLocator.GetInstance<IConsoleStatus>(); _packageRestoreManager = ServiceLocator.GetInstance<IPackageRestoreManager>(); Debug.Assert(_packageRestoreManager != null); // Add our command handlers for menu (commands must exist in the .vsct file) AddMenuCommandHandlers(); // when NuGet loads, if the current solution has package // restore mode enabled, we make sure every thing is set up correctly. // For example, projects which were added outside of VS need to have // the <Import> element added. if (_packageRestoreManager.IsCurrentSolutionEnabledForRestore) { _packageRestoreManager.EnableCurrentSolutionForRestore(quietMode: true); } } private void AddMenuCommandHandlers() { OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (null != mcs) { // menu command for opening Package Manager Console CommandID toolwndCommandID = new CommandID(GuidList.guidNuGetConsoleCmdSet, PkgCmdIDList.cmdidPowerConsole); MenuCommand menuToolWin = new MenuCommand(ShowToolWindow, toolwndCommandID); mcs.AddCommand(menuToolWin); // menu command for opening Manage NuGet packages dialog CommandID managePackageDialogCommandID = new CommandID(GuidList.guidNuGetDialogCmdSet, PkgCmdIDList.cmdidAddPackageDialog); OleMenuCommand managePackageDialogCommand = new OleMenuCommand(ShowManageLibraryPackageDialog, null, BeforeQueryStatusForAddPackageDialog, managePackageDialogCommandID); mcs.AddCommand(managePackageDialogCommand); // menu command for opening "Manage NuGet packages for solution" dialog CommandID managePackageForSolutionDialogCommandID = new CommandID(GuidList.guidNuGetDialogCmdSet, PkgCmdIDList.cmdidAddPackageDialogForSolution); OleMenuCommand managePackageForSolutionDialogCommand = new OleMenuCommand(ShowManageLibraryPackageForSolutionDialog, null, BeforeQueryStatusForAddPackageForSolutionDialog, managePackageForSolutionDialogCommandID); mcs.AddCommand(managePackageForSolutionDialogCommand); // menu command for opening Package Source settings options page CommandID settingsCommandID = new CommandID(GuidList.guidNuGetConsoleCmdSet, PkgCmdIDList.cmdidSourceSettings); OleMenuCommand settingsMenuCommand = new OleMenuCommand(ShowPackageSourcesOptionPage, settingsCommandID); mcs.AddCommand(settingsMenuCommand); // menu command for opening General options page CommandID generalSettingsCommandID = new CommandID(GuidList.guidNuGetToolsGroupCmdSet, PkgCmdIDList.cmdIdGeneralSettings); OleMenuCommand generalSettingsCommand = new OleMenuCommand(ShowGeneralSettingsOptionPage, generalSettingsCommandID); mcs.AddCommand(generalSettingsCommand); // menu command for Package Visualizer CommandID visualizerCommandID = new CommandID(GuidList.guidNuGetToolsGroupCmdSet, PkgCmdIDList.cmdIdVisualizer); OleMenuCommand visualizerCommand = new OleMenuCommand(ExecuteVisualizer, null, QueryStatusForVisualizer, visualizerCommandID); mcs.AddCommand(visualizerCommand); // menu command for Package Restore command CommandID restorePackagesCommandID = new CommandID(GuidList.guidNuGetPackagesRestoreCmdSet, PkgCmdIDList.cmdidRestorePackages); var restorePackagesCommand = new OleMenuCommand(EnablePackagesRestore, null, QueryStatusEnablePackagesRestore, restorePackagesCommandID); mcs.AddCommand(restorePackagesCommand); } } private void ShowToolWindow(object sender, EventArgs e) { // Get the instance number 0 of this tool window. This window is single instance so this instance // is actually the only one. // The last flag is set to true so that if the tool window does not exists it will be created. ToolWindowPane window = this.FindToolWindow(typeof(PowerConsoleToolWindow), 0, true); if ((null == window) || (null == window.Frame)) { throw new NotSupportedException(Resources.CanNotCreateWindow); } IVsWindowFrame windowFrame = (IVsWindowFrame)window.Frame; ErrorHandler.ThrowOnFailure(windowFrame.Show()); } /// <summary> /// Executes the NuGet Visualizer. /// </summary> private void ExecuteVisualizer(object sender, EventArgs e) { var visualizer = new NuGet.Dialog.Visualizer( ServiceLocator.GetInstance<IVsPackageManagerFactory>(), ServiceLocator.GetInstance<ISolutionManager>()); string outputFile = visualizer.CreateGraph(); _dte.ItemOperations.OpenFile(outputFile); } private void ShowManageLibraryPackageDialog(object sender, EventArgs e) { if (_vsMonitorSelection.GetIsSolutionNodeSelected()) { ShowManageLibraryPackageDialog(null); } else { Project project = _vsMonitorSelection.GetActiveProject(); if (project != null && !project.IsUnloaded() && project.IsSupported()) { ShowManageLibraryPackageDialog(project); } else { // show error message when no supported project is selected. string projectName = project != null ? project.Name : String.Empty; string errorMessage; if (String.IsNullOrEmpty(projectName)) { errorMessage = Resources.NoProjectSelected; } else { errorMessage = String.Format(CultureInfo.CurrentCulture, VsResources.DTE_ProjectUnsupported, projectName); } MessageHelper.ShowWarningMessage(errorMessage, Resources.ErrorDialogBoxTitle); } } } private void ShowManageLibraryPackageForSolutionDialog(object sender, EventArgs e) { ShowManageLibraryPackageDialog(null); } private static void ShowManageLibraryPackageDialog(Project project) { DialogWindow window = VsVersionHelper.IsVisualStudio2010 ? GetVS10PackageManagerWindow(project) : GetPackageManagerWindow(project); try { window.ShowModal(); } catch (TargetInvocationException exception) { MessageHelper.ShowErrorMessage(exception, Resources.ErrorDialogBoxTitle); ExceptionHelper.WriteToActivityLog(exception); } } [MethodImpl(MethodImplOptions.NoInlining)] private static DialogWindow GetVS10PackageManagerWindow(Project project) { return new VS10ManagePackageDialog(project); } [MethodImpl(MethodImplOptions.NoInlining)] private static DialogWindow GetPackageManagerWindow(Project project) { return new ManagePackageDialog(project); } private void EnablePackagesRestore(object sender, EventArgs args) { _packageRestoreManager.EnableCurrentSolutionForRestore(quietMode: false); } private void QueryStatusEnablePackagesRestore(object sender, EventArgs args) { OleMenuCommand command = (OleMenuCommand)sender; command.Visible = IsSolutionOpen && !_packageRestoreManager.IsCurrentSolutionEnabledForRestore; command.Enabled = !_consoleStatus.IsBusy; } private void BeforeQueryStatusForAddPackageDialog(object sender, EventArgs args) { bool isSolutionSelected = _vsMonitorSelection.GetIsSolutionNodeSelected(); OleMenuCommand command = (OleMenuCommand)sender; command.Visible = !IsIDEInDebuggingOrBuildingContext() && (isSolutionSelected || HasActiveLoadedSupportedProject); // disable the dialog menu if the console is busy executing a command; command.Enabled = !_consoleStatus.IsBusy; if (command.Visible) { command.Text = isSolutionSelected ? Resources.ManagePackageForSolutionLabel : Resources.ManagePackageLabel; } } private void BeforeQueryStatusForAddPackageForSolutionDialog(object sender, EventArgs args) { OleMenuCommand command = (OleMenuCommand)sender; command.Visible = IsSolutionOpen && !IsIDEInDebuggingOrBuildingContext(); // disable the dialog menu if the console is busy executing a command; command.Enabled = !_consoleStatus.IsBusy; } private void QueryStatusForVisualizer(object sender, EventArgs args) { OleMenuCommand command = (OleMenuCommand)sender; command.Visible = IsSolutionOpen && IsVisualizerSupported; } private bool IsIDEInDebuggingOrBuildingContext() { int pfActive; int result = _vsMonitorSelection.IsCmdUIContextActive(_debuggingContextCookie, out pfActive); if (result == VSConstants.S_OK && pfActive > 0) { return true; } result = _vsMonitorSelection.IsCmdUIContextActive(_solutionBuildingContextCookie, out pfActive); if (result == VSConstants.S_OK && pfActive > 0) { return true; } return false; } private void ShowPackageSourcesOptionPage(object sender, EventArgs args) { ShowOptionPageSafe(typeof(PackageSourceOptionsPage)); } private void ShowGeneralSettingsOptionPage(object sender, EventArgs args) { ShowOptionPageSafe(typeof(GeneralOptionPage)); } private void ShowOptionPageSafe(Type optionPageType) { try { ShowOptionPage(optionPageType); } catch (Exception exception) { MessageHelper.ShowErrorMessage(exception, Resources.ErrorDialogBoxTitle); ExceptionHelper.WriteToActivityLog(exception); } } /// <summary> /// Gets whether the current IDE has an active, supported and non-unloaded project, which is a precondition for /// showing the Add Library Package Reference dialog /// </summary> private bool HasActiveLoadedSupportedProject { get { Project project = _vsMonitorSelection.GetActiveProject(); return project != null && !project.IsUnloaded() && project.IsSupported(); } } private bool IsSolutionOpen { get { return _dte != null && _dte.Solution != null && _dte.Solution.IsOpen; } } private bool IsVisualizerSupported { get { if (_isVisualizerSupported == null) { _isVisualizerSupported = _visualizerSupportedSKUs.Contains(_dte.Edition, StringComparer.OrdinalIgnoreCase); } return _isVisualizerSupported.Value; } } } }
// // System.Web.Compilation.AspTokenizer // // Authors: // Gonzalo Paniagua Javier (gonzalo@ximian.com) // // (C) 2002,2003 Ximian, Inc (http://www.ximian.com) // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.IO; using System.Text; using System.Web; namespace DodoNet.Http.Compilation { class Token { public const int EOF = 0x0200000; public const int IDENTIFIER = 0x0200001; public const int DIRECTIVE = 0x0200002; public const int ATTVALUE = 0x0200003; public const int TEXT = 0x0200004; public const int DOUBLEDASH = 0x0200005; public const int CLOSING = 0x0200006; } class AspTokenizer { TextReader sr; int current_token; StringBuilder sb, odds; int col, line; int begcol, begline; int position; bool inTag; bool expectAttrValue; bool alternatingQuotes; bool hasPutBack; bool verbatim; bool have_value; bool have_unget; int unget_value; string val; public AspTokenizer(TextReader reader) { this.sr = reader; sb = new StringBuilder(); odds = new StringBuilder(); col = line = 1; hasPutBack = inTag = false; } public bool Verbatim { get { return verbatim; } set { verbatim = value; } } public void put_back() { if (hasPutBack) throw new HttpException("put_back called twice!"); hasPutBack = true; position -= Value.Length; } public int get_token() { if (hasPutBack) { hasPutBack = false; position += Value.Length; return current_token; } begline = line; begcol = col; have_value = false; current_token = NextToken(); return current_token; } bool is_identifier_start_character(char c) { return (Char.IsLetter(c) || c == '_'); } bool is_identifier_part_character(char c) { return (Char.IsLetterOrDigit(c) || c == '_' || c == '-'); } void ungetc(int value) { have_unget = true; unget_value = value; // Only '/' passes through here now. // If we ever let \n here, update 'line' position--; col--; } int read_char() { int c; if (have_unget) { c = unget_value; have_unget = false; } else { c = sr.Read(); } if (c == '\r' && sr.Peek() == '\n') { c = sr.Read(); position++; } if (c == '\n') { col = -1; line++; } if (c != -1) { col++; position++; } return c; } int ReadAttValue(int start) { int quoteChar = 0; bool quoted = false; if (start == '"' || start == '\'') { quoteChar = start; quoted = true; } else { sb.Append((char)start); } int c; int last = 0; bool inServerTag = false; alternatingQuotes = true; while ((c = sr.Peek()) != -1) { if (c == '%' && last == '<') { inServerTag = true; } else if (inServerTag && c == '>' && last == '%') { inServerTag = false; } else if (!inServerTag) { if (!quoted && c == '/') { read_char(); c = sr.Peek(); if (c == -1) { c = '/'; } else if (c == '>') { ungetc('/'); break; } } else if (!quoted && (c == '>' || Char.IsWhiteSpace((char)c))) { break; } else if (quoted && c == quoteChar && last != '\\') { read_char(); break; } } else if (quoted && c == quoteChar) { alternatingQuotes = false; } sb.Append((char)c); read_char(); last = c; } return Token.ATTVALUE; } int NextToken() { int c; sb.Length = 0; odds.Length = 0; while ((c = read_char()) != -1) { if (verbatim) { inTag = false; sb.Append((char)c); return c; } if (inTag && expectAttrValue && (c == '"' || c == '\'')) return ReadAttValue(c); if (c == '<') { inTag = true; sb.Append((char)c); return c; } if (c == '>') { inTag = false; sb.Append((char)c); return c; } if (current_token == '<' && "%/!".IndexOf((char)c) != -1) { sb.Append((char)c); return c; } if (inTag && current_token == '%' && "@#=".IndexOf((char)c) != -1) { sb.Append((char)c); return c; } if (inTag && c == '-' && sr.Peek() == '-') { sb.Append("--"); read_char(); return Token.DOUBLEDASH; } if (!inTag) { sb.Append((char)c); while ((c = sr.Peek()) != -1 && c != '<') sb.Append((char)read_char()); return (c != -1 || sb.Length > 0) ? Token.TEXT : Token.EOF; } if (inTag && current_token == '=' && !Char.IsWhiteSpace((char)c)) return ReadAttValue(c); if (inTag && is_identifier_start_character((char)c)) { sb.Append((char)c); while ((c = sr.Peek()) != -1) { if (!is_identifier_part_character((char)c) && c != ':') break; sb.Append((char)read_char()); } if (current_token == '@' && Directive.IsDirective(sb.ToString())) return Token.DIRECTIVE; return Token.IDENTIFIER; } if (!Char.IsWhiteSpace((char)c)) { sb.Append((char)c); return c; } // keep otherwise discarded characters in case we need. odds.Append((char)c); } return Token.EOF; } public string Value { get { if (have_value) return val; have_value = true; val = sb.ToString(); return val; } } public string Odds { get { return odds.ToString(); } } public bool InTag { get { return inTag; } set { inTag = value; } } // Hack for preventing confusion with VB comments (see bug #63451) public bool ExpectAttrValue { get { return expectAttrValue; } set { expectAttrValue = value; } } public bool AlternatingQuotes { get { return alternatingQuotes; } } public int BeginLine { get { return begline; } } public int BeginColumn { get { return begcol; } } public int EndLine { get { return line; } } public int EndColumn { get { return col; } } public int Position { get { return position; } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Lucene.Net.Documents; using Lucene.Net.Index; using Microsoft.VisualStudio.TestTools.UnitTesting; using Document = Lucene.Net.Documents.Document; using DefaultSimilarity = Lucene.Net.Search.DefaultSimilarity; namespace LuceneNetSqlDirectory.Tests { [TestClass] public class TestSegmentReader:LuceneTestCase { private SqlServerDirectory _dir; private Document _testDoc = new Document(); private SegmentReader _reader = null; //TODO: Setup the reader w/ multiple documents [TestInitialize] public override void TestInitialize() { base.TestInitialize(); _testDoc = new Document(); _dir = new SqlServerDirectory(Connection,new Options()); DocHelper.SetupDoc(_testDoc); SegmentInfo info = DocHelper.WriteDoc(_dir, _testDoc); _reader = SegmentReader.Get(true, info, 1); } [TestMethod] public virtual void Test() { Assert.IsTrue(_dir != null); Assert.IsTrue(_reader != null); Assert.IsTrue(DocHelper.NameValues.Count > 0); Assert.IsTrue(DocHelper.NumFields(_testDoc) == DocHelper.All.Count); } [TestMethod] public virtual void TestDocument() { Assert.IsTrue(_reader.NumDocs() == 1); Assert.IsTrue(_reader.MaxDoc >= 1); Document result = _reader.Document(0); Assert.IsTrue(result != null); //There are 2 unstored fields on the document that are not preserved across writing Assert.IsTrue(DocHelper.NumFields(result) == DocHelper.NumFields(_testDoc) - DocHelper.Unstored.Count); var fields = result.GetFields(); foreach (var field in fields) { Assert.IsTrue(field != null); Assert.IsTrue(DocHelper.NameValues.Contains(field.Name)); } } [TestMethod] public virtual void TestDelete() { Document docToDelete = new Document(); DocHelper.SetupDoc(docToDelete); SegmentInfo info = DocHelper.WriteDoc(_dir, docToDelete); SegmentReader deleteReader = SegmentReader.Get(false, info, 1); Assert.IsTrue(deleteReader != null); Assert.IsTrue(deleteReader.NumDocs() == 1); deleteReader.DeleteDocument(0); Assert.IsTrue(deleteReader.IsDeleted(0) == true); Assert.IsTrue(deleteReader.HasDeletions == true); Assert.IsTrue(deleteReader.NumDocs() == 0); } [TestMethod] public virtual void TestGetFieldNameVariations() { System.Collections.Generic.ICollection<string> result = _reader.GetFieldNames(IndexReader.FieldOption.ALL); Assert.IsTrue(result != null); Assert.IsTrue(result.Count == DocHelper.All.Count); for (System.Collections.IEnumerator iter = result.GetEnumerator(); iter.MoveNext(); ) { System.String s = (System.String) iter.Current; //System.out.println("Name: " + s); Assert.IsTrue(DocHelper.NameValues.Contains(s) == true || s.Equals("")); } result = _reader.GetFieldNames(IndexReader.FieldOption.INDEXED); Assert.IsTrue(result != null); Assert.IsTrue(result.Count == DocHelper.Indexed.Count); for (System.Collections.IEnumerator iter = result.GetEnumerator(); iter.MoveNext(); ) { System.String s = (System.String) iter.Current; Assert.IsTrue(DocHelper.Indexed.Contains(s) == true || s.Equals("")); } result = _reader.GetFieldNames(IndexReader.FieldOption.UNINDEXED); Assert.IsTrue(result != null); Assert.IsTrue(result.Count == DocHelper.Unindexed.Count); //Get all indexed fields that are storing term vectors result = _reader.GetFieldNames(IndexReader.FieldOption.INDEXED_WITH_TERMVECTOR); Assert.IsTrue(result != null); Assert.IsTrue(result.Count == DocHelper.Termvector.Count); result = _reader.GetFieldNames(IndexReader.FieldOption.INDEXED_NO_TERMVECTOR); Assert.IsTrue(result != null); Assert.IsTrue(result.Count == DocHelper.Notermvector.Count); } [TestMethod] public virtual void TestTerms() { TermEnum terms = _reader.Terms(); Assert.IsTrue(terms != null); while (terms.Next() == true) { Term term = terms.Term; Assert.IsTrue(term != null); //System.out.println("Term: " + term); System.String fieldValue = (System.String) DocHelper.NameValues[term.Field]; Assert.IsTrue(fieldValue.IndexOf(term.Text) != - 1); } TermDocs termDocs = _reader.TermDocs(); Assert.IsTrue(termDocs != null); termDocs.Seek(new Term(DocHelper.TextField1Key, "field")); Assert.IsTrue(termDocs.Next() == true); termDocs.Seek(new Term(DocHelper.NoNormsKey, DocHelper.NoNormsText)); Assert.IsTrue(termDocs.Next() == true); TermPositions positions = _reader.TermPositions(); positions.Seek(new Term(DocHelper.TextField1Key, "field")); Assert.IsTrue(positions != null); Assert.IsTrue(positions.Doc == 0); Assert.IsTrue(positions.NextPosition() >= 0); } public static void CheckNorms(IndexReader reader) { // test omit norms for (int i = 0; i < DocHelper.Fields.Length; i++) { IFieldable f = DocHelper.Fields[i]; if (f.IsIndexed) { Assert.AreEqual(reader.HasNorms(f.Name), !f.OmitNorms); Assert.AreEqual(reader.HasNorms(f.Name), !DocHelper.NoNorms.Contains(f.Name)); if (!reader.HasNorms(f.Name)) { // test for fake norms of 1.0 or null depending on the flag byte[] norms = reader.Norms(f.Name); byte norm1 = DefaultSimilarity.EncodeNorm(1.0f); Assert.IsNull(norms); norms = new byte[reader.MaxDoc]; reader.Norms(f.Name, norms, 0); for (int j = 0; j < reader.MaxDoc; j++) { Assert.AreEqual(norms[j], norm1); } } } } } [TestMethod] public virtual void TestTermVectors() { ITermFreqVector result = _reader.GetTermFreqVector(0, DocHelper.TextField2Key); Assert.IsTrue(result != null); System.String[] terms = result.GetTerms(); int[] freqs = result.GetTermFrequencies(); Assert.IsTrue(terms != null && terms.Length == 3 && freqs != null && freqs.Length == 3); for (int i = 0; i < terms.Length; i++) { System.String term = terms[i]; int freq = freqs[i]; Assert.IsTrue(DocHelper.Field2Text.IndexOf(term) != - 1); Assert.IsTrue(freq > 0); } ITermFreqVector[] results = _reader.GetTermFreqVectors(0); Assert.IsTrue(results != null); Assert.IsTrue(results.Length == 3, "We do not have 3 term freq vectors, we have: " + results.Length); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // // // StrongName is an IIdentity representing strong names. // namespace System.Security.Policy { using System.IO; using System.Reflection; using System.Security.Util; using System.Security.Permissions; using System.Diagnostics.Contracts; using CultureInfo = System.Globalization.CultureInfo; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public sealed class StrongName : EvidenceBase, IIdentityPermissionFactory, IDelayEvaluatedEvidence { private StrongNamePublicKeyBlob m_publicKeyBlob; private String m_name; private Version m_version; // Delay evaluated evidence is for policy resolution only, so it doesn't make sense to save that // state away and then try to evaluate the strong name later. [NonSerialized] private RuntimeAssembly m_assembly = null; [NonSerialized] private bool m_wasUsed = false; internal StrongName() {} public StrongName( StrongNamePublicKeyBlob blob, String name, Version version ) : this(blob, name, version, null) { } internal StrongName(StrongNamePublicKeyBlob blob, String name, Version version, Assembly assembly) { if (name == null) throw new ArgumentNullException("name"); if (String.IsNullOrEmpty(name)) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyStrongName")); if (blob == null) throw new ArgumentNullException("blob"); if (version == null) throw new ArgumentNullException("version"); Contract.EndContractBlock(); RuntimeAssembly rtAssembly = assembly as RuntimeAssembly; if (assembly != null && rtAssembly == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), "assembly"); m_publicKeyBlob = blob; m_name = name; m_version = version; m_assembly = rtAssembly; } public StrongNamePublicKeyBlob PublicKey { get { return m_publicKeyBlob; } } public String Name { get { return m_name; } } public Version Version { get { return m_version; } } bool IDelayEvaluatedEvidence.IsVerified { [System.Security.SecurityCritical] // auto-generated get { #if FEATURE_CAS_POLICY return m_assembly != null ? m_assembly.IsStrongNameVerified : true; #else // !FEATURE_CAS_POLICY return true; #endif // FEATURE_CAS_POLICY } } bool IDelayEvaluatedEvidence.WasUsed { get { return m_wasUsed; } } void IDelayEvaluatedEvidence.MarkUsed() { m_wasUsed = true; } internal static bool CompareNames( String asmName, String mcName ) { if (mcName.Length > 0 && mcName[mcName.Length-1] == '*' && mcName.Length - 1 <= asmName.Length) return String.Compare( mcName, 0, asmName, 0, mcName.Length - 1, StringComparison.OrdinalIgnoreCase) == 0; else return String.Compare( mcName, asmName, StringComparison.OrdinalIgnoreCase) == 0; } public IPermission CreateIdentityPermission( Evidence evidence ) { return new StrongNameIdentityPermission( m_publicKeyBlob, m_name, m_version ); } public override EvidenceBase Clone() { return new StrongName(m_publicKeyBlob, m_name, m_version); } public Object Copy() { return Clone(); } #if FEATURE_CAS_POLICY internal SecurityElement ToXml() { SecurityElement root = new SecurityElement( "StrongName" ); root.AddAttribute( "version", "1" ); if (m_publicKeyBlob != null) root.AddAttribute( "Key", System.Security.Util.Hex.EncodeHexString( m_publicKeyBlob.PublicKey ) ); if (m_name != null) root.AddAttribute( "Name", m_name ); if (m_version != null) root.AddAttribute( "Version", m_version.ToString() ); return root; } internal void FromXml (SecurityElement element) { if (element == null) throw new ArgumentNullException("element"); if (String.Compare(element.Tag, "StrongName", StringComparison.Ordinal) != 0) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidXML")); Contract.EndContractBlock(); m_publicKeyBlob = null; m_version = null; string key = element.Attribute("Key"); if (key != null) m_publicKeyBlob = new StrongNamePublicKeyBlob(System.Security.Util.Hex.DecodeHexString(key)); m_name = element.Attribute("Name"); string version = element.Attribute("Version"); if (version != null) m_version = new Version(version); } public override String ToString() { return ToXml().ToString(); } #endif // FEATURE_CAS_POLICY public override bool Equals( Object o ) { StrongName that = (o as StrongName); return (that != null) && Equals( this.m_publicKeyBlob, that.m_publicKeyBlob ) && Equals( this.m_name, that.m_name ) && Equals( this.m_version, that.m_version ); } public override int GetHashCode() { if (m_publicKeyBlob != null) { return m_publicKeyBlob.GetHashCode(); } else if (m_name != null || m_version != null) { return (m_name == null ? 0 : m_name.GetHashCode()) + (m_version == null ? 0 : m_version.GetHashCode()); } else { return typeof( StrongName ).GetHashCode(); } } // INormalizeForIsolatedStorage is not implemented for startup perf // equivalent to INormalizeForIsolatedStorage.Normalize() internal Object Normalize() { MemoryStream ms = new MemoryStream(); BinaryWriter bw = new BinaryWriter(ms); bw.Write(m_publicKeyBlob.PublicKey); bw.Write(m_version.Major); bw.Write(m_name); ms.Position = 0; return ms; } } }
// SPDX-License-Identifier: MIT // Copyright wtfsckgh@gmail.com // Copyright iced contributors using System; using Generator.Constants.Encoder; using Generator.Enums; using Generator.Enums.Encoder; using Generator.IO; namespace Generator.Tables { [Generator(TargetLanguage.Other)] sealed class OpCodeInfoTxtGen { readonly GenTypes genTypes; public OpCodeInfoTxtGen(GeneratorContext generatorContext) => genTypes = generatorContext.Types; public void Generate() { var filename = genTypes.Dirs.GetUnitTestFilename("Encoder", "OpCodeInfos.txt"); using (var writer = new FileWriter(TargetLanguage.Other, FileUtils.OpenWrite(filename))) { writer.WriteFileHeader(); foreach (var def in genTypes.GetObject<InstructionDefs>(TypeIds.InstructionDefs).Defs) Write(writer, def); } } static void Write(FileWriter writer, InstructionDef def) { const string sepNoSpace = ","; const string sep = sepNoSpace + " "; writer.Write(def.Code.RawName); writer.Write(sep); writer.Write(def.Mnemonic.RawName); writer.Write(sep); writer.Write(def.Memory.RawName); writer.Write(sep); writer.Write(def.MemoryBroadcast.RawName); var encoding = def.Encoding switch { EncodingKind.Legacy => OpCodeInfoConstants.Encoding_Legacy, EncodingKind.VEX => OpCodeInfoConstants.Encoding_VEX, EncodingKind.EVEX => OpCodeInfoConstants.Encoding_EVEX, EncodingKind.XOP => OpCodeInfoConstants.Encoding_XOP, EncodingKind.D3NOW => OpCodeInfoConstants.Encoding_3DNOW, _ => throw new InvalidOperationException(), }; writer.Write(sep); writer.Write(encoding); var mp = def.MandatoryPrefix switch { MandatoryPrefix.None => OpCodeInfoConstants.MandatoryPrefix_None, MandatoryPrefix.PNP => OpCodeInfoConstants.MandatoryPrefix_NP, MandatoryPrefix.P66 => OpCodeInfoConstants.MandatoryPrefix_66, MandatoryPrefix.PF3 => OpCodeInfoConstants.MandatoryPrefix_F3, MandatoryPrefix.PF2 => OpCodeInfoConstants.MandatoryPrefix_F2, _ => throw new InvalidOperationException(), }; writer.Write(sep); writer.Write(mp); var table = def.Table switch { OpCodeTableKind.Normal => OpCodeInfoConstants.Table_Legacy, OpCodeTableKind.T0F => OpCodeInfoConstants.Table_0F, OpCodeTableKind.T0F38 => OpCodeInfoConstants.Table_0F38, OpCodeTableKind.T0F3A => OpCodeInfoConstants.Table_0F3A, OpCodeTableKind.XOP8 => OpCodeInfoConstants.Table_XOP8, OpCodeTableKind.XOP9 => OpCodeInfoConstants.Table_XOP9, OpCodeTableKind.XOPA => OpCodeInfoConstants.Table_XOPA, _ => throw new InvalidOperationException(), }; writer.Write(sep); writer.Write(table); writer.Write(sep); switch (def.OpCodeLength) { case 1: writer.Write(def.OpCode.ToString("X2")); break; case 2: writer.Write(def.OpCode.ToString("X4")); break; default: throw new InvalidOperationException(); } writer.Write(sep); writer.Write(def.OpCodeString); writer.Write(sep); writer.Write(def.InstructionString.Replace(',', '|')); writer.Write(sepNoSpace); void W(string prop) { writer.Write(" "); writer.Write(prop); } void WK(string key) { writer.Write(" "); writer.Write(key); writer.Write("="); } if (def.DecoderOption.Value != 0) { WK(OpCodeInfoKeywordKeys.DecoderOption); writer.Write(def.DecoderOption.RawName); } if (def.GroupIndex >= 0) { WK(OpCodeInfoKeywordKeys.GroupIndex); writer.Write(def.GroupIndex.ToString()); } if (def.RmGroupIndex >= 0) { WK(OpCodeInfoKeywordKeys.RmGroupIndex); writer.Write(def.RmGroupIndex.ToString()); } if ((def.Flags1 & InstructionDefFlags1.NoInstruction) != 0) W(OpCodeInfoKeywords.NoInstruction); if ((def.Flags1 & InstructionDefFlags1.Bit16) != 0) W(OpCodeInfoKeywords.Bit16); if ((def.Flags1 & (InstructionDefFlags1.Bit16 | InstructionDefFlags1.Bit32)) != 0) W(OpCodeInfoKeywords.Bit32); if ((def.Flags1 & InstructionDefFlags1.Bit64) != 0) W(OpCodeInfoKeywords.Bit64); if ((def.Flags1 & InstructionDefFlags1.Cpl0) != 0) W(OpCodeInfoKeywords.Cpl0); if ((def.Flags1 & InstructionDefFlags1.Cpl1) != 0) W(OpCodeInfoKeywords.Cpl1); if ((def.Flags1 & InstructionDefFlags1.Cpl2) != 0) W(OpCodeInfoKeywords.Cpl2); if ((def.Flags1 & InstructionDefFlags1.Cpl3) != 0) W(OpCodeInfoKeywords.Cpl3); if ((def.Flags1 & InstructionDefFlags1.Fwait) != 0) W(OpCodeInfoKeywords.Fwait); switch (def.OperandSize) { case CodeSize.Unknown: break; case CodeSize.Code16: W(OpCodeInfoKeywords.OperandSize16); break; case CodeSize.Code32: W(OpCodeInfoKeywords.OperandSize32); break; case CodeSize.Code64: W(OpCodeInfoKeywords.OperandSize64); break; default: throw new InvalidOperationException(); } switch (def.AddressSize) { case CodeSize.Unknown: break; case CodeSize.Code16: W(OpCodeInfoKeywords.AddressSize16); break; case CodeSize.Code32: W(OpCodeInfoKeywords.AddressSize32); break; case CodeSize.Code64: W(OpCodeInfoKeywords.AddressSize64); break; default: throw new InvalidOperationException(); } switch (def.LBit) { case OpCodeL.None: break; case OpCodeL.L0: case OpCodeL.LZ: W(OpCodeInfoKeywords.L0); break; case OpCodeL.L1: W(OpCodeInfoKeywords.L1); break; case OpCodeL.LIG: W(OpCodeInfoKeywords.LIG); break; case OpCodeL.L128: W(OpCodeInfoKeywords.L128); break; case OpCodeL.L256: W(OpCodeInfoKeywords.L256); break; case OpCodeL.L512: W(OpCodeInfoKeywords.L512); break; default: throw new InvalidOperationException(); } if ((def.Flags1 & InstructionDefFlags1.WIG32) != 0) W(OpCodeInfoKeywords.WIG32); else { switch (def.WBit) { case OpCodeW.None: break; case OpCodeW.W0: W(OpCodeInfoKeywords.W0); break; case OpCodeW.W1: W(OpCodeInfoKeywords.W1); break; case OpCodeW.WIG: W(OpCodeInfoKeywords.WIG); break; case OpCodeW.WIG32: default: throw new InvalidOperationException(); } } if (def.OpCount > 0) { WK(OpCodeInfoKeywordKeys.OpCodeOperandKind); for (int i = 0; i < def.OpCount; i++) { if (i > 0) writer.Write(";"); writer.Write(def.OpKindDefs[i].EnumValue.RawName); } } if ((def.Flags1 & InstructionDefFlags1.SaveRestore) != 0) W(OpCodeInfoKeywords.SaveRestore); if ((def.Flags1 & InstructionDefFlags1.StackInstruction) != 0) W(OpCodeInfoKeywords.StackInstruction); if ((def.Flags1 & InstructionDefFlags1.IgnoresSegment) != 0) W(OpCodeInfoKeywords.IgnoresSegment); if ((def.Flags1 & InstructionDefFlags1.OpMaskReadWrite) != 0) W(OpCodeInfoKeywords.OpMaskReadWrite); if ((def.Flags1 & InstructionDefFlags1.Lock) != 0) W(OpCodeInfoKeywords.Lock); if ((def.Flags1 & InstructionDefFlags1.Xacquire) != 0) W(OpCodeInfoKeywords.Xacquire); if ((def.Flags1 & InstructionDefFlags1.Xrelease) != 0) W(OpCodeInfoKeywords.Xrelease); switch (def.Flags1 & (InstructionDefFlags1.Rep | InstructionDefFlags1.Repne)) { case InstructionDefFlags1.Rep | InstructionDefFlags1.Repne: W(OpCodeInfoKeywords.Repe); W(OpCodeInfoKeywords.Repne); break; case InstructionDefFlags1.Rep: W(OpCodeInfoKeywords.Rep); break; case InstructionDefFlags1.Repne: W(OpCodeInfoKeywords.Repne); break; default: break; } if ((def.Flags1 & InstructionDefFlags1.Bnd) != 0) W(OpCodeInfoKeywords.Bnd); if ((def.Flags1 & InstructionDefFlags1.HintTaken) != 0) W(OpCodeInfoKeywords.HintTaken); if ((def.Flags1 & InstructionDefFlags1.Notrack) != 0) W(OpCodeInfoKeywords.Notrack); if ((MemorySize)def.Memory.Value != MemorySize.Unknown && def.Encoding == EncodingKind.EVEX) { WK(OpCodeInfoKeywordKeys.TupleType); writer.Write(def.TupleType.ToString()); } if ((def.Flags1 & InstructionDefFlags1.Broadcast) != 0) W(OpCodeInfoKeywords.Broadcast); if ((def.Flags1 & InstructionDefFlags1.RoundingControl) != 0) W(OpCodeInfoKeywords.RoundingControl); if ((def.Flags1 & InstructionDefFlags1.SuppressAllExceptions) != 0) W(OpCodeInfoKeywords.SuppressAllExceptions); if ((def.Flags1 & InstructionDefFlags1.OpMaskRegister) != 0) W(OpCodeInfoKeywords.OpMaskRegister); if ((def.Flags1 & InstructionDefFlags1.ZeroingMasking) != 0) W(OpCodeInfoKeywords.ZeroingMasking); if ((def.Flags1 & InstructionDefFlags1.RequireOpMaskRegister) != 0) W(OpCodeInfoKeywords.RequireOpMaskRegister); if ((def.Flags1 & InstructionDefFlags1.IgnoresModBits) != 0) W(OpCodeInfoKeywords.IgnoresModBits); if ((def.Flags1 & InstructionDefFlags1.RequiresUniqueRegNums) != 0) W(OpCodeInfoKeywords.RequiresUniqueRegNums); if ((def.Flags1 & InstructionDefFlags1.No66) != 0) W(OpCodeInfoKeywords.No66); if ((def.Flags1 & InstructionDefFlags1.NFx) != 0) W(OpCodeInfoKeywords.NFx); if ((def.Flags2 & InstructionDefFlags2.IntelDecoder16) != 0) W(OpCodeInfoKeywords.IntelDecoder16); if ((def.Flags2 & (InstructionDefFlags2.IntelDecoder16 | InstructionDefFlags2.IntelDecoder32)) != 0) W(OpCodeInfoKeywords.IntelDecoder32); if ((def.Flags2 & InstructionDefFlags2.IntelDecoder64) != 0) W(OpCodeInfoKeywords.IntelDecoder64); if ((def.Flags2 & InstructionDefFlags2.AmdDecoder16) != 0) W(OpCodeInfoKeywords.AmdDecoder16); if ((def.Flags2 & (InstructionDefFlags2.AmdDecoder16 | InstructionDefFlags2.AmdDecoder32)) != 0) W(OpCodeInfoKeywords.AmdDecoder32); if ((def.Flags2 & InstructionDefFlags2.AmdDecoder64) != 0) W(OpCodeInfoKeywords.AmdDecoder64); if ((def.Flags2 & InstructionDefFlags2.RealMode) != 0) W(OpCodeInfoKeywords.RealMode); if ((def.Flags2 & InstructionDefFlags2.ProtectedMode) != 0) W(OpCodeInfoKeywords.ProtectedMode); if ((def.Flags2 & InstructionDefFlags2.Virtual8086Mode) != 0) W(OpCodeInfoKeywords.Virtual8086Mode); if ((def.Flags2 & InstructionDefFlags2.CompatibilityMode) != 0) W(OpCodeInfoKeywords.CompatibilityMode); if ((def.Flags2 & InstructionDefFlags2.LongMode) != 0) W(OpCodeInfoKeywords.LongMode); if ((def.Flags2 & InstructionDefFlags2.UseOutsideSmm) != 0) W(OpCodeInfoKeywords.UseOutsideSmm); if ((def.Flags2 & InstructionDefFlags2.UseInSmm) != 0) W(OpCodeInfoKeywords.UseInSmm); if ((def.Flags2 & InstructionDefFlags2.UseOutsideEnclaveSgx) != 0) W(OpCodeInfoKeywords.UseOutsideEnclaveSgx); if ((def.Flags2 & InstructionDefFlags2.UseInEnclaveSgx1) != 0) W(OpCodeInfoKeywords.UseInEnclaveSgx1); if ((def.Flags2 & InstructionDefFlags2.UseInEnclaveSgx2) != 0) W(OpCodeInfoKeywords.UseInEnclaveSgx2); if ((def.Flags2 & InstructionDefFlags2.UseOutsideVmxOp) != 0) W(OpCodeInfoKeywords.UseOutsideVmxOp); if ((def.Flags2 & InstructionDefFlags2.UseInVmxRootOp) != 0) W(OpCodeInfoKeywords.UseInVmxRootOp); if ((def.Flags2 & InstructionDefFlags2.UseInVmxNonRootOp) != 0) W(OpCodeInfoKeywords.UseInVmxNonRootOp); if ((def.Flags2 & InstructionDefFlags2.UseOutsideSeam) != 0) W(OpCodeInfoKeywords.UseOutsideSeam); if ((def.Flags2 & InstructionDefFlags2.UseInSeam) != 0) W(OpCodeInfoKeywords.UseInSeam); if ((def.Flags2 & InstructionDefFlags2.TdxNonRootGenUd) != 0) W(OpCodeInfoKeywords.TdxNonRootGenUd); if ((def.Flags2 & InstructionDefFlags2.TdxNonRootGenVe) != 0) W(OpCodeInfoKeywords.TdxNonRootGenVe); if ((def.Flags2 & InstructionDefFlags2.TdxNonRootMayGenEx) != 0) W(OpCodeInfoKeywords.TdxNonRootMayGenEx); if ((def.Flags2 & InstructionDefFlags2.IntelVmExit) != 0) W(OpCodeInfoKeywords.IntelVmExit); if ((def.Flags2 & InstructionDefFlags2.IntelMayVmExit) != 0) W(OpCodeInfoKeywords.IntelMayVmExit); if ((def.Flags2 & InstructionDefFlags2.IntelSmmVmExit) != 0) W(OpCodeInfoKeywords.IntelSmmVmExit); if ((def.Flags2 & InstructionDefFlags2.AmdVmExit) != 0) W(OpCodeInfoKeywords.AmdVmExit); if ((def.Flags2 & InstructionDefFlags2.AmdMayVmExit) != 0) W(OpCodeInfoKeywords.AmdMayVmExit); if ((def.Flags2 & InstructionDefFlags2.TsxAbort) != 0) W(OpCodeInfoKeywords.TsxAbort); if ((def.Flags2 & InstructionDefFlags2.TsxImplAbort) != 0) W(OpCodeInfoKeywords.TsxImplAbort); if ((def.Flags2 & InstructionDefFlags2.TsxMayAbort) != 0) W(OpCodeInfoKeywords.TsxMayAbort); if ((def.Flags3 & InstructionDefFlags3.DefaultOpSize64) != 0) W(OpCodeInfoKeywords.DefaultOpSize64); if ((def.Flags3 & InstructionDefFlags3.ForceOpSize64) != 0) W(OpCodeInfoKeywords.ForceOpSize64); if ((def.Flags3 & InstructionDefFlags3.IntelForceOpSize64) != 0) W(OpCodeInfoKeywords.IntelForceOpSize64); if ((def.Flags3 & InstructionDefFlags3.InputOutput) != 0) W(OpCodeInfoKeywords.InputOutput); if ((def.Flags3 & InstructionDefFlags3.Nop) != 0) W(OpCodeInfoKeywords.Nop); if ((def.Flags3 & InstructionDefFlags3.ReservedNop) != 0) W(OpCodeInfoKeywords.ReservedNop); if ((def.Flags3 & InstructionDefFlags3.IgnoresRoundingControl) != 0) W(OpCodeInfoKeywords.IgnoresRoundingControl); if ((def.Flags3 & InstructionDefFlags3.SerializingIntel) != 0) W(OpCodeInfoKeywords.SerializingIntel); if ((def.Flags3 & InstructionDefFlags3.SerializingAmd) != 0) W(OpCodeInfoKeywords.SerializingAmd); if ((def.Flags3 & InstructionDefFlags3.MayRequireCpl0) != 0) W(OpCodeInfoKeywords.MayRequireCpl0); if ((def.Flags3 & InstructionDefFlags3.AmdLockRegBit) != 0) W(OpCodeInfoKeywords.AmdLockRegBit); if ((def.Flags3 & InstructionDefFlags3.CetTracked) != 0) W(OpCodeInfoKeywords.CetTracked); if ((def.Flags3 & InstructionDefFlags3.NonTemporal) != 0) W(OpCodeInfoKeywords.NonTemporal); if ((def.Flags3 & InstructionDefFlags3.FpuNoWait) != 0) W(OpCodeInfoKeywords.FpuNoWait); if ((def.Flags3 & InstructionDefFlags3.Privileged) != 0) W(OpCodeInfoKeywords.Privileged); writer.WriteLine(); } } }
// // TypeDefinition.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2011 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. // using System; using Mono.Cecil.Metadata; using Mono.Collections.Generic; namespace Mono.Cecil { public sealed class TypeDefinition : TypeReference, IMemberDefinition, ISecurityDeclarationProvider { uint attributes; TypeReference base_type; internal Range fields_range; internal Range methods_range; short packing_size = Mixin.NotResolvedMarker; int class_size = Mixin.NotResolvedMarker; Collection<TypeReference> interfaces; Collection<TypeDefinition> nested_types; Collection<MethodDefinition> methods; Collection<FieldDefinition> fields; Collection<EventDefinition> events; Collection<PropertyDefinition> properties; Collection<CustomAttribute> custom_attributes; Collection<SecurityDeclaration> security_declarations; public TypeAttributes Attributes { get { return (TypeAttributes) attributes; } set { attributes = (uint) value; } } public TypeReference BaseType { get { return base_type; } set { base_type = value; } } void ResolveLayout () { if (packing_size != Mixin.NotResolvedMarker || class_size != Mixin.NotResolvedMarker) return; if (!HasImage) { packing_size = Mixin.NoDataMarker; class_size = Mixin.NoDataMarker; return; } var row = Module.Read (this, (type, reader) => reader.ReadTypeLayout (type)); packing_size = row.Col1; class_size = row.Col2; } public bool HasLayoutInfo { get { if (packing_size >= 0 || class_size >= 0) return true; ResolveLayout (); return packing_size >= 0 || class_size >= 0; } } public short PackingSize { get { if (packing_size >= 0) return packing_size; ResolveLayout (); return packing_size >= 0 ? packing_size : (short) -1; } set { packing_size = value; } } public int ClassSize { get { if (class_size >= 0) return class_size; ResolveLayout (); return class_size >= 0 ? class_size : -1; } set { class_size = value; } } public bool HasInterfaces { get { if (interfaces != null) return interfaces.Count > 0; if (HasImage) return Module.Read (this, (type, reader) => reader.HasInterfaces (type)); return false; } } public Collection<TypeReference> Interfaces { get { if (interfaces != null) return interfaces; if (HasImage) return Module.Read (ref interfaces, this, (type, reader) => reader.ReadInterfaces (type)); return interfaces = new Collection<TypeReference> (); } } public bool HasNestedTypes { get { if (nested_types != null) return nested_types.Count > 0; if (HasImage) return Module.Read (this, (type, reader) => reader.HasNestedTypes (type)); return false; } } public Collection<TypeDefinition> NestedTypes { get { if (nested_types != null) return nested_types; if (HasImage) return Module.Read (ref nested_types, this, (type, reader) => reader.ReadNestedTypes (type)); return nested_types = new MemberDefinitionCollection<TypeDefinition> (this); } } public bool HasMethods { get { if (methods != null) return methods.Count > 0; if (HasImage) return methods_range.Length > 0; return false; } } public Collection<MethodDefinition> Methods { get { if (methods != null) return methods; if (HasImage) return Module.Read (ref methods, this, (type, reader) => reader.ReadMethods (type)); return methods = new MemberDefinitionCollection<MethodDefinition> (this); } } public bool HasFields { get { if (fields != null) return fields.Count > 0; if (HasImage) return fields_range.Length > 0; return false; } } public Collection<FieldDefinition> Fields { get { if (fields != null) return fields; if (HasImage) return Module.Read (ref fields, this, (type, reader) => reader.ReadFields (type)); return fields = new MemberDefinitionCollection<FieldDefinition> (this); } } public bool HasEvents { get { if (events != null) return events.Count > 0; if (HasImage) return Module.Read (this, (type, reader) => reader.HasEvents (type)); return false; } } public Collection<EventDefinition> Events { get { if (events != null) return events; if (HasImage) return Module.Read (ref events, this, (type, reader) => reader.ReadEvents (type)); return events = new MemberDefinitionCollection<EventDefinition> (this); } } public bool HasProperties { get { if (properties != null) return properties.Count > 0; if (HasImage) return Module.Read (this, (type, reader) => reader.HasProperties (type)); return false; } } public Collection<PropertyDefinition> Properties { get { if (properties != null) return properties; if (HasImage) return Module.Read (ref properties, this, (type, reader) => reader.ReadProperties (type)); return properties = new MemberDefinitionCollection<PropertyDefinition> (this); } } public bool HasSecurityDeclarations { get { if (security_declarations != null) return security_declarations.Count > 0; return this.GetHasSecurityDeclarations (Module); } } public Collection<SecurityDeclaration> SecurityDeclarations { get { return security_declarations ?? (this.GetSecurityDeclarations (ref security_declarations, Module)); } } public bool HasCustomAttributes { get { if (custom_attributes != null) return custom_attributes.Count > 0; return this.GetHasCustomAttributes (Module); } } public Collection<CustomAttribute> CustomAttributes { get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, Module)); } } public override bool HasGenericParameters { get { if (generic_parameters != null) return generic_parameters.Count > 0; return this.GetHasGenericParameters (Module); } } public override Collection<GenericParameter> GenericParameters { get { return generic_parameters ?? (this.GetGenericParameters (ref generic_parameters, Module)); } } #region TypeAttributes public bool IsNotPublic { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic, value); } } public bool IsPublic { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public, value); } } public bool IsNestedPublic { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic, value); } } public bool IsNestedPrivate { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate, value); } } public bool IsNestedFamily { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily, value); } } public bool IsNestedAssembly { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly, value); } } public bool IsNestedFamilyAndAssembly { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem, value); } } public bool IsNestedFamilyOrAssembly { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem, value); } } public bool IsAutoLayout { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout, value); } } public bool IsSequentialLayout { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout, value); } } public bool IsExplicitLayout { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout, value); } } public bool IsClass { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class, value); } } public bool IsInterface { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface, value); } } public bool IsAbstract { get { return attributes.GetAttributes ((uint) TypeAttributes.Abstract); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Abstract, value); } } public bool IsSealed { get { return attributes.GetAttributes ((uint) TypeAttributes.Sealed); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Sealed, value); } } public bool IsSpecialName { get { return attributes.GetAttributes ((uint) TypeAttributes.SpecialName); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.SpecialName, value); } } public bool IsImport { get { return attributes.GetAttributes ((uint) TypeAttributes.Import); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Import, value); } } public bool IsSerializable { get { return attributes.GetAttributes ((uint) TypeAttributes.Serializable); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Serializable, value); } } public bool IsWindowsRuntime { get { return attributes.GetAttributes ((uint) TypeAttributes.WindowsRuntime); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.WindowsRuntime, value); } } public bool IsAnsiClass { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass, value); } } public bool IsUnicodeClass { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass, value); } } public bool IsAutoClass { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass, value); } } public bool IsBeforeFieldInit { get { return attributes.GetAttributes ((uint) TypeAttributes.BeforeFieldInit); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.BeforeFieldInit, value); } } public bool IsRuntimeSpecialName { get { return attributes.GetAttributes ((uint) TypeAttributes.RTSpecialName); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.RTSpecialName, value); } } public bool HasSecurity { get { return attributes.GetAttributes ((uint) TypeAttributes.HasSecurity); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.HasSecurity, value); } } #endregion public bool IsEnum { get { return base_type != null && base_type.IsTypeOf ("System", "Enum"); } } public override bool IsValueType { get { if (base_type == null) return false; return base_type.IsTypeOf ("System", "Enum") || (base_type.IsTypeOf ("System", "ValueType") && !this.IsTypeOf ("System", "Enum")); } } public override bool IsPrimitive { get { ElementType primitive_etype; return MetadataSystem.TryGetPrimitiveElementType (this, out primitive_etype); } } public override MetadataType MetadataType { get { ElementType primitive_etype; if (MetadataSystem.TryGetPrimitiveElementType (this, out primitive_etype)) return (MetadataType) primitive_etype; return base.MetadataType; } } public override bool IsDefinition { get { return true; } } public new TypeDefinition DeclaringType { get { return (TypeDefinition) base.DeclaringType; } set { base.DeclaringType = value; } } public TypeDefinition (string @namespace, string name, TypeAttributes attributes) : base (@namespace, name) { this.attributes = (uint) attributes; this.token = new MetadataToken (TokenType.TypeDef); } public TypeDefinition (string @namespace, string name, TypeAttributes attributes, TypeReference baseType) : this (@namespace, name, attributes) { this.BaseType = baseType; } public override TypeDefinition Resolve () { return this; } } static partial class Mixin { public static TypeReference GetEnumUnderlyingType (this TypeDefinition self) { var fields = self.Fields; for (int i = 0; i < fields.Count; i++) { var field = fields [i]; if (!field.IsStatic) return field.FieldType; } throw new ArgumentException (); } public static TypeDefinition GetNestedType (this TypeDefinition self, string fullname) { if (!self.HasNestedTypes) return null; var nested_types = self.NestedTypes; for (int i = 0; i < nested_types.Count; i++) { var nested_type = nested_types [i]; if (nested_type.TypeFullName () == fullname) return nested_type; } return null; } } }
using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; //using System.Data; using System.Diagnostics; using SwinGameSDK; /// <summary> /// This includes a number of utility methods for /// drawing and interacting with the Mouse. /// </summary> static class UtilityFunctions { public const int FIELD_TOP = 122; public const int FIELD_LEFT = 349; public const int FIELD_WIDTH = 418; public const int FIELD_HEIGHT = 418; public const int MESSAGE_TOP = 548; public const int CELL_WIDTH = 40; public const int CELL_HEIGHT = 40; public const int CELL_GAP = 2; public const int SHIP_GAP = 3; private static readonly Color SMALL_SEA = SwinGame.RGBAColor(6, 60, 94, 255); private static readonly Color SMALL_SHIP = Color.Gray; private static readonly Color SMALL_MISS = SwinGame.RGBAColor(1, 147, 220, 255); private static readonly Color SMALL_HIT = SwinGame.RGBAColor(169, 24, 37, 255); private static readonly Color LARGE_SEA = SwinGame.RGBAColor(6, 60, 94, 255); private static readonly Color LARGE_SHIP = Color.Gray; private static readonly Color LARGE_MISS = SwinGame.RGBAColor(1, 147, 220, 255); private static readonly Color LARGE_HIT = SwinGame.RGBAColor(252, 2, 3, 255); private static readonly Color OUTLINE_COLOR = SwinGame.RGBAColor(5, 55, 88, 255); private static readonly Color SHIP_FILL_COLOR = Color.Gray; private static readonly Color SHIP_OUTLINE_COLOR = Color.White; private static readonly Color MESSAGE_COLOR = SwinGame.RGBAColor(2, 167, 252, 255); public const int ANIMATION_CELLS = 7; public const int FRAMES_PER_CELL = 8; /// <summary> /// Determines if the mouse is in a given rectangle. /// </summary> /// <param name="x">the x location to check</param> /// <param name="y">the y location to check</param> /// <param name="w">the width to check</param> /// <param name="h">the height to check</param> /// <returns>true if the mouse is in the area checked</returns> public static bool IsMouseInRectangle(int x, int y, int w, int h) { Point2D mouse = default(Point2D); bool result = false; mouse = SwinGame.MousePosition(); //if the mouse is inline with the button horizontally if (mouse.X >= x & mouse.X <= x + w) { //Check vertical position if (mouse.Y >= y & mouse.Y <= y + h) { result = true; } } return result; } /// <summary> /// Draws a large field using the grid and the indicated player's ships. /// </summary> /// <param name="grid">the grid to draw</param> /// <param name="thePlayer">the players ships to show</param> /// <param name="showShips">indicates if the ships should be shown</param> public static void DrawField(ISeaGrid grid, Player thePlayer, bool showShips) { DrawCustomField(grid, thePlayer, false, showShips, FIELD_LEFT, FIELD_TOP, FIELD_WIDTH, FIELD_HEIGHT, CELL_WIDTH, CELL_HEIGHT, CELL_GAP); } /// <summary> /// Draws a small field, showing the attacks made and the locations of the player's ships /// </summary> /// <param name="grid">the grid to show</param> /// <param name="thePlayer">the player to show the ships of</param> public static void DrawSmallField(ISeaGrid grid, Player thePlayer) { const int SMALL_FIELD_LEFT = 39; const int SMALL_FIELD_TOP = 373; const int SMALL_FIELD_WIDTH = 166; const int SMALL_FIELD_HEIGHT = 166; const int SMALL_FIELD_CELL_WIDTH = 13; const int SMALL_FIELD_CELL_HEIGHT = 13; const int SMALL_FIELD_CELL_GAP = 4; DrawCustomField(grid, thePlayer, true, true, SMALL_FIELD_LEFT, SMALL_FIELD_TOP, SMALL_FIELD_WIDTH, SMALL_FIELD_HEIGHT, SMALL_FIELD_CELL_WIDTH, SMALL_FIELD_CELL_HEIGHT, SMALL_FIELD_CELL_GAP); } /// <summary> /// Draws the player's grid and ships. /// </summary> /// <param name="grid">the grid to show</param> /// <param name="thePlayer">the player to show the ships of</param> /// <param name="small">true if the small grid is shown</param> /// <param name="showShips">true if ships are to be shown</param> /// <param name="left">the left side of the grid</param> /// <param name="top">the top of the grid</param> /// <param name="width">the width of the grid</param> /// <param name="height">the height of the grid</param> /// <param name="cellWidth">the width of each cell</param> /// <param name="cellHeight">the height of each cell</param> /// <param name="cellGap">the gap between the cells</param> private static void DrawCustomField(ISeaGrid grid, Player thePlayer, bool small, bool showShips, int left, int top, int width, int height, int cellWidth, int cellHeight, int cellGap) { //SwinGame.FillRectangle(Color.Blue, left, top, width, height) int rowTop = 0; int colLeft = 0; //Draw the grid for (int row = 0; row <= 9; row++) { rowTop = top + (cellGap + cellHeight) * row; for (int col = 0; col <= 9; col++) { colLeft = left + (cellGap + cellWidth) * col; Color fillColor = default(Color); bool draw = false; draw = true; switch (grid[row, col]) { //case TileView.Ship: // draw = false; // break; //If small Then fillColor = _SMALL_SHIP Else fillColor = _LARGE_SHIP case TileView.Miss: if (small) fillColor = SMALL_MISS; else fillColor = LARGE_MISS; break; case TileView.Hit: if (small) fillColor = SMALL_HIT; else fillColor = LARGE_HIT; break; case TileView.Sea: case TileView.Ship: if (small) fillColor = SMALL_SEA; else draw = false; break; } if (draw) { SwinGame.FillRectangle(fillColor, colLeft, rowTop, cellWidth, cellHeight); if (!small) { SwinGame.DrawRectangle(OUTLINE_COLOR, colLeft, rowTop, cellWidth, cellHeight); } } } } if (!showShips) { return; } int shipHeight = 0; int shipWidth = 0; string shipName = null; //Draw the ships foreach (Ship s in thePlayer) { if (s == null || !s.IsDeployed) continue; rowTop = top + (cellGap + cellHeight) * s.Row + SHIP_GAP; colLeft = left + (cellGap + cellWidth) * s.Column + SHIP_GAP; if (s.Direction == Direction.LeftRight) { shipName = "ShipLR" + s.Size; shipHeight = cellHeight - (SHIP_GAP * 2); shipWidth = (cellWidth + cellGap) * s.Size - (SHIP_GAP * 2) - cellGap; } else { //Up down shipName = "ShipUD" + s.Size; shipHeight = (cellHeight + cellGap) * s.Size - (SHIP_GAP * 2) - cellGap; shipWidth = cellWidth - (SHIP_GAP * 2); } if (!small) { SwinGame.DrawBitmap(GameResources.GameImage(shipName), colLeft, rowTop); } else { SwinGame.FillRectangle(SHIP_FILL_COLOR, colLeft, rowTop, shipWidth, shipHeight); SwinGame.DrawRectangle(SHIP_OUTLINE_COLOR, colLeft, rowTop, shipWidth, shipHeight); } } } private static string _message; /// <summary> /// The message to display /// </summary> /// <value>The message to display</value> /// <returns>The message to display</returns> public static string Message { get { return _message; } set { _message = value; } } /// <summary> /// Draws the message to the screen /// </summary> public static void DrawMessage() { SwinGame.DrawText(Message, MESSAGE_COLOR, GameResources.GameFont("Courier"), FIELD_LEFT, MESSAGE_TOP); } /// <summary> /// Draws the background for the current state of the game /// </summary> public static void DrawBackground() { switch (GameController.CurrentState) { case GameState.ViewingMainMenu: case GameState.ViewingGameMenu: case GameState.AlteringSettings: case GameState.ViewingHighScores: SwinGame.DrawBitmap(GameResources.GameImage("Menu"), 0, 0); break; case GameState.Discovering: case GameState.EndingGame: SwinGame.DrawBitmap(GameResources.GameImage("Discovery"), 0, 0); break; case GameState.Deploying: SwinGame.DrawBitmap(GameResources.GameImage("Deploy"), 0, 0); break; default: SwinGame.ClearScreen(); break; } SwinGame.DrawFramerate(675, 585, GameResources.GameFont("CourierSmall")); } /// <summary> /// Draws an explosion at the specified tile /// </summary> public static void AddExplosion(int row, int col) { AddAnimation(row, col, "Splash"); } /// <summary> /// Draws a splash at the specified tile /// </summary> public static void AddSplash(int row, int col) { AddAnimation(row, col, "Splash"); } private static List<Sprite> _Animations = new List<Sprite>(); private static void AddAnimation(int row, int col, string image) { Sprite s = default(Sprite); Bitmap imgObj = default(Bitmap); imgObj = GameResources.GameImage(image); imgObj.SetCellDetails(40, 40, 3, 3, 7); AnimationScript animation = default(AnimationScript); animation = SwinGame.LoadAnimationScript("splash.txt"); s = SwinGame.CreateSprite(imgObj, animation); s.X = FIELD_LEFT + col * (CELL_WIDTH + CELL_GAP); s.Y = FIELD_TOP + row * (CELL_HEIGHT + CELL_GAP); s.StartAnimation("splash"); _Animations.Add(s); } /// <summary> /// Advances the each active animation to its next frame, or destroys them if their end has been reached /// </summary> public static void UpdateAnimations() { List<Sprite> ended = new List<Sprite>(); foreach (Sprite s in _Animations) { SwinGame.UpdateSprite(s); if (s.AnimationHasEnded) { ended.Add(s); } } foreach (Sprite s in ended) { _Animations.Remove(s); SwinGame.FreeSprite(s); } } /// <summary> /// Draws the current frame for each active animation /// </summary> public static void DrawAnimations() { foreach (Sprite s in _Animations) { SwinGame.DrawSprite(s); } } /// <summary> /// NULL /// </summary> // TODO: I'm not actually sure what this method is doing public static void DrawAnimationSequence() { int i = 0; for (i = 1; i <= ANIMATION_CELLS * FRAMES_PER_CELL; i++) { UpdateAnimations(); GameController.DrawScreen(); } } } //======================================================= //Service provided by Telerik (www.telerik.com) //Conversion powered by NRefactory. //Twitter: @telerik //Facebook: facebook.com/telerik //=======================================================
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace ILCompiler.DependencyAnalysis.X64 { public struct X64Emitter { public X64Emitter(NodeFactory factory) { Builder = new ObjectDataBuilder(factory); TargetRegister = new TargetRegisterMap(factory.Target.OperatingSystem); } public ObjectDataBuilder Builder; public TargetRegisterMap TargetRegister; // Assembly stub creation api. TBD, actually make this general purpose public void EmitMOV(Register regDst, ref AddrMode memory) { EmitIndirInstructionSize(0x8a, regDst, ref memory); } public void EmitMOV(Register regDst, Register regSrc) { AddrMode rexAddrMode = new AddrMode(regSrc, null, 0, 0, AddrModeSize.Int64); EmitRexPrefix(regDst, ref rexAddrMode); Builder.EmitByte(0x89); Builder.EmitByte((byte)(0xC0 | (((int)regSrc & 0x07) << 3) | (((int)regDst & 0x07)))); } public void EmitMOV(Register regDst, int imm32) { AddrMode rexAddrMode = new AddrMode(regDst, null, 0, 0, AddrModeSize.Int32); EmitRexPrefix(regDst, ref rexAddrMode); Builder.EmitByte((byte)(0xB8 | ((int)regDst & 0x07))); Builder.EmitInt(imm32); } public void EmitLEAQ(Register reg, ISymbolNode symbol, int delta = 0) { AddrMode rexAddrMode = new AddrMode(Register.RAX, null, 0, 0, AddrModeSize.Int64); EmitRexPrefix(reg, ref rexAddrMode); Builder.EmitByte(0x8D); Builder.EmitByte((byte)(0x05 | (((int)reg) & 0x07) << 3)); Builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_REL32, delta); } public void EmitLEA(Register reg, ref AddrMode addrMode) { Debug.Assert(addrMode.Size != AddrModeSize.Int8 && addrMode.Size != AddrModeSize.Int16); EmitIndirInstruction(0x8D, reg, ref addrMode); } public void EmitCMP(ref AddrMode addrMode, sbyte immediate) { if (addrMode.Size == AddrModeSize.Int16) Builder.EmitByte(0x66); EmitIndirInstruction((byte)((addrMode.Size != AddrModeSize.Int8) ? 0x83 : 0x80), 0x7, ref addrMode); Builder.EmitByte((byte)immediate); } public void EmitADD(ref AddrMode addrMode, sbyte immediate) { if (addrMode.Size == AddrModeSize.Int16) Builder.EmitByte(0x66); EmitIndirInstruction((byte)((addrMode.Size != AddrModeSize.Int8) ? 0x83 : 0x80), (byte)0, ref addrMode); Builder.EmitByte((byte)immediate); } public void EmitJMP(ISymbolNode symbol) { Builder.EmitByte(0xE9); Builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_REL32); } public void EmitINT3() { Builder.EmitByte(0xCC); } public void EmitJmpToAddrMode(ref AddrMode addrMode) { EmitIndirInstruction(0xFF, 0x4, ref addrMode); } public void EmitRET() { Builder.EmitByte(0xC3); } public void EmitRETIfEqual() { // jne @+1 Builder.EmitByte(0x75); Builder.EmitByte(0x01); // ret Builder.EmitByte(0xC3); } private bool InSignedByteRange(int i) { return i == (int)(sbyte)i; } private void EmitImmediate(int immediate, int size) { switch (size) { case 0: break; case 1: Builder.EmitByte((byte)immediate); break; case 2: Builder.EmitShort((short)immediate); break; case 4: Builder.EmitInt(immediate); break; default: throw new NotImplementedException(); } } private void EmitModRM(byte subOpcode, ref AddrMode addrMode) { byte modRM = (byte)((subOpcode & 0x07) << 3); if (addrMode.BaseReg > Register.None) { Debug.Assert(addrMode.BaseReg >= Register.RegDirect); Register reg = (Register)(addrMode.BaseReg - Register.RegDirect); Builder.EmitByte((byte)(0xC0 | modRM | ((int)reg & 0x07))); } else { byte lowOrderBitsOfBaseReg = (byte)((int)addrMode.BaseReg & 0x07); modRM |= lowOrderBitsOfBaseReg; int offsetSize = 0; if (addrMode.Offset == 0 && (lowOrderBitsOfBaseReg != (byte)Register.RBP)) { offsetSize = 0; } else if (InSignedByteRange(addrMode.Offset)) { offsetSize = 1; modRM |= 0x40; } else { offsetSize = 4; modRM |= 0x80; } bool emitSibByte = false; Register sibByteBaseRegister = addrMode.BaseReg; if (addrMode.BaseReg == Register.None) { //# ifdef _TARGET_AMD64_ // x64 requires SIB to avoid RIP relative address emitSibByte = true; //#else // emitSibByte = (addrMode.m_indexReg != MDIL_REG_NO_INDEX); //#endif modRM &= 0x38; // set Mod bits to 00 and clear out base reg offsetSize = 4; // this forces 32-bit displacement if (emitSibByte) { // EBP in SIB byte means no base // ModRM base register forced to ESP in SIB code below sibByteBaseRegister = Register.RBP; } else { // EBP in ModRM means no base modRM |= (byte)(Register.RBP); } } else if (lowOrderBitsOfBaseReg == (byte)Register.RSP || addrMode.IndexReg.HasValue) { emitSibByte = true; } if (!emitSibByte) { Builder.EmitByte(modRM); } else { // MDIL_REG_ESP as the base is the marker that there is a SIB byte modRM = (byte)((modRM & 0xF8) | (int)Register.RSP); Builder.EmitByte(modRM); int indexRegAsInt = (int)(addrMode.IndexReg.HasValue ? addrMode.IndexReg.Value : Register.RSP); Builder.EmitByte((byte)((addrMode.Scale << 6) + ((indexRegAsInt & 0x07) << 3) + ((int)sibByteBaseRegister & 0x07))); } EmitImmediate(addrMode.Offset, offsetSize); } } private void EmitExtendedOpcode(int opcode) { if ((opcode >> 16) != 0) { if ((opcode >> 24) != 0) { Builder.EmitByte((byte)(opcode >> 24)); } Builder.EmitByte((byte)(opcode >> 16)); } Builder.EmitByte((byte)(opcode >> 8)); } private void EmitRexPrefix(Register reg, ref AddrMode addrMode) { byte rexPrefix = 0; // Check the situations where a REX prefix is needed // Are we accessing a byte register that wasn't byte accessible in x86? if (addrMode.Size == AddrModeSize.Int8 && reg >= Register.RSP) { rexPrefix |= 0x40; } // Is this a 64 bit instruction? if (addrMode.Size == AddrModeSize.Int64) { rexPrefix |= 0x48; } // Is the destination register one of the new ones? if (reg >= Register.R8) { rexPrefix |= 0x44; } // Is the index register one of the new ones? if (addrMode.IndexReg.HasValue && addrMode.IndexReg.Value >= Register.R8 && addrMode.IndexReg.Value <= Register.R15) { rexPrefix |= 0x42; } // Is the base register one of the new ones? if (addrMode.BaseReg >= Register.R8 && addrMode.BaseReg <= Register.R15 || addrMode.BaseReg >= (int)Register.R8 + Register.RegDirect && addrMode.BaseReg <= (int)Register.R15 + Register.RegDirect) { rexPrefix |= 0x41; } // If we have anything so far, emit it. if (rexPrefix != 0) { Builder.EmitByte(rexPrefix); } } private void EmitIndirInstruction(int opcode, byte subOpcode, ref AddrMode addrMode) { EmitRexPrefix(Register.RAX, ref addrMode); if ((opcode >> 8) != 0) { EmitExtendedOpcode(opcode); } Builder.EmitByte((byte)opcode); EmitModRM(subOpcode, ref addrMode); } private void EmitIndirInstruction(int opcode, Register dstReg, ref AddrMode addrMode) { EmitRexPrefix(dstReg, ref addrMode); if ((opcode >> 8) != 0) { EmitExtendedOpcode(opcode); } Builder.EmitByte((byte)opcode); EmitModRM((byte)((int)dstReg & 0x07), ref addrMode); } private void EmitIndirInstructionSize(int opcode, Register dstReg, ref AddrMode addrMode) { //# ifndef _TARGET_AMD64_ // assert that ESP, EBP, ESI, EDI are not accessed as bytes in 32-bit mode // Debug.Assert(!(addrMode.Size == AddrModeSize.Int8 && dstReg > Register.RBX)); //#endif Debug.Assert(addrMode.Size != 0); if (addrMode.Size == AddrModeSize.Int16) Builder.EmitByte(0x66); EmitIndirInstruction(opcode + ((addrMode.Size != AddrModeSize.Int8) ? 1 : 0), dstReg, ref addrMode); } } }
// // Copyright (C) 2012-2014 DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Net; using System.Linq; namespace Cassandra { internal class TokenMap { internal readonly TokenFactory Factory; private readonly List<IToken> _ring; private readonly Dictionary<string, Dictionary<IToken, HashSet<Host>>> _tokenToHostsByKeyspace; private readonly Dictionary<IToken, Host> _primaryReplicas; private static readonly Logger _logger = new Logger(typeof(ControlConnection)); internal TokenMap(TokenFactory factory, Dictionary<string, Dictionary<IToken, HashSet<Host>>> tokenToHostsByKeyspace, List<IToken> ring, Dictionary<IToken, Host> primaryReplicas) { Factory = factory; _tokenToHostsByKeyspace = tokenToHostsByKeyspace; _ring = ring; _primaryReplicas = primaryReplicas; } public static TokenMap Build(string partitioner, ICollection<Host> hosts, ICollection<KeyspaceMetadata> keyspaces) { var factory = TokenFactory.GetFactory(partitioner); if (factory == null) { return null; } var primaryReplicas = new Dictionary<IToken, Host>(); var allSorted = new SortedSet<IToken>(); var datacenters = new Dictionary<string, int>(); foreach (var host in hosts) { if (host.Datacenter != null) { if (!datacenters.ContainsKey(host.Datacenter)) { datacenters[host.Datacenter] = 1; } else { datacenters[host.Datacenter]++; } } foreach (var tokenStr in host.Tokens) { try { var token = factory.Parse(tokenStr); allSorted.Add(token); primaryReplicas[token] = host; } catch { _logger.Error(String.Format("Token {0} could not be parsed using {1} partitioner implementation", tokenStr, partitioner)); } } } var ring = new List<IToken>(allSorted); var tokenToHosts = new Dictionary<string, Dictionary<IToken, HashSet<Host>>>(keyspaces.Count); //Only consider nodes that have tokens var hostCount = hosts.Count(h => h.Tokens.Any()); foreach (var ks in keyspaces) { Dictionary<IToken, HashSet<Host>> replicas; if (ks.StrategyClass == ReplicationStrategies.SimpleStrategy) { replicas = ComputeTokenToReplicaSimple(ks.Replication["replication_factor"], hostCount, ring, primaryReplicas); } else if (ks.StrategyClass == ReplicationStrategies.NetworkTopologyStrategy) { replicas = ComputeTokenToReplicaNetwork(ks.Replication, ring, primaryReplicas, datacenters); } else { //No replication information, use primary replicas replicas = primaryReplicas.ToDictionary(kv => kv.Key, kv => new HashSet<Host>(new [] { kv.Value })); } tokenToHosts[ks.Name] = replicas; } return new TokenMap(factory, tokenToHosts, ring, primaryReplicas); } private static Dictionary<IToken, HashSet<Host>> ComputeTokenToReplicaNetwork(IDictionary<string, int> replicationFactors, List<IToken> ring, Dictionary<IToken, Host> primaryReplicas, Dictionary<string, int> datacenters) { var replicas = new Dictionary<IToken, HashSet<Host>>(); for (var i = 0; i < ring.Count; i++) { var token = ring[i]; var replicasByDc = new Dictionary<string, int>(); var tokenReplicas = new HashSet<Host>(); for (var j = 0; j < ring.Count; j++) { var replicaIndex = i + j; if (replicaIndex >= ring.Count) { //circle back replicaIndex = replicaIndex % ring.Count; } var h = primaryReplicas[ring[replicaIndex]]; var dcRf = 0; if (!replicationFactors.TryGetValue(h.Datacenter, out dcRf)) { continue; } dcRf = Math.Min(dcRf, datacenters[h.Datacenter]); var dcReplicas = 0; replicasByDc.TryGetValue(h.Datacenter, out dcReplicas); //Amount of replicas per dc is equals to the rf or the amount of host in the datacenter if (dcReplicas >= dcRf) { continue; } // On a cluster running virtual nodes, one host can own 2 continuous ranges, but these // are not replicas (NetworkTopologyStrategy.Java - calculateNaturalEndpoints) if(tokenReplicas.Contains(h)) continue; replicasByDc[h.Datacenter] = dcReplicas + 1; tokenReplicas.Add(h); if (IsDoneForToken(replicationFactors, replicasByDc, datacenters)) { break; } } replicas[token] = tokenReplicas; } return replicas; } internal static bool IsDoneForToken(IDictionary<string, int> replicationFactors, Dictionary<string, int> replicasByDc, Dictionary<string, int> datacenters) { foreach (var dc in replicationFactors.Keys) { var rf = Math.Min(replicationFactors[dc], datacenters.ContainsKey(dc) ? datacenters[dc] : 0); if (rf == 0) { //A DC is included in the RF but the DC does not exist continue; } if (!replicasByDc.ContainsKey(dc) || replicasByDc[dc] < rf) { return false; } } return true; } /// <summary> /// Converts token-primary to token-replicas /// </summary> private static Dictionary<IToken, HashSet<Host>> ComputeTokenToReplicaSimple(int replicationFactor, int hostCount, List<IToken> ring, Dictionary<IToken, Host> primaryReplicas) { var rf = Math.Min(replicationFactor, hostCount); var tokenToReplicas = new Dictionary<IToken, HashSet<Host>>(ring.Count); for (var i = 0; i < ring.Count; i++) { var token = ring[i]; var replicas = new HashSet<Host>(); replicas.Add(primaryReplicas[token]); var j = 1; while (replicas.Count < rf) { var nextReplicaIndex = i + j; if (nextReplicaIndex >= ring.Count) { //circle back nextReplicaIndex = nextReplicaIndex % ring.Count; } var nextReplica = primaryReplicas[ring[nextReplicaIndex]]; replicas.Add(nextReplica); j++; } tokenToReplicas.Add(token, replicas); } return tokenToReplicas; } public ICollection<Host> GetReplicas(string keyspaceName, IToken token) { // Find the primary replica var i = _ring.BinarySearch(token); if (i < 0) { //no exact match, use closest index i = ~i; if (i >= _ring.Count) { i = 0; } } var closestToken = _ring[i]; if (keyspaceName != null && _tokenToHostsByKeyspace.ContainsKey(keyspaceName)) { return _tokenToHostsByKeyspace[keyspaceName][closestToken]; } return new Host[] { _primaryReplicas[closestToken] }; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Composition; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.SolutionCrawler { public class WorkCoordinatorTests { private const string SolutionCrawler = "SolutionCrawler"; [WpfFact] public void RegisterService() { using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var registrationService = new SolutionCrawlerRegistrationService( SpecializedCollections.EmptyEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>(), AggregateAsynchronousOperationListener.EmptyListeners); // register and unregister workspace to the service registrationService.Register(workspace); registrationService.Unregister(workspace); } } [WpfFact, WorkItem(747226)] public async Task SolutionAdded_Simple() { using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solutionId = SolutionId.CreateNewId(); var projectId = ProjectId.CreateNewId(); var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), projects: new[] { ProjectInfo.Create(projectId, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1") }) }); var worker = await ExecuteOperation(workspace, w => w.OnSolutionAdded(solutionInfo)).ConfigureAwait(true); Assert.Equal(1, worker.SyntaxDocumentIds.Count); } } [WpfFact] public async Task SolutionAdded_Complex() { using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); var worker = await ExecuteOperation(workspace, w => w.OnSolutionAdded(solution)).ConfigureAwait(true); Assert.Equal(10, worker.SyntaxDocumentIds.Count); } } [WpfFact] public async Task Solution_Remove() { using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider).ConfigureAwait(true); var worker = await ExecuteOperation(workspace, w => w.OnSolutionRemoved()).ConfigureAwait(true); Assert.Equal(10, worker.InvalidateDocumentIds.Count); } } [WpfFact] public async Task Solution_Clear() { using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider).ConfigureAwait(true); var worker = await ExecuteOperation(workspace, w => w.ClearSolution()).ConfigureAwait(true); Assert.Equal(10, worker.InvalidateDocumentIds.Count); } } [WpfFact] public async Task Solution_Reload() { using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider).ConfigureAwait(true); var worker = await ExecuteOperation(workspace, w => w.OnSolutionReloaded(solution)).ConfigureAwait(true); Assert.Equal(0, worker.SyntaxDocumentIds.Count); } } [WpfFact] public async Task Solution_Change() { using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solutionInfo = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solutionInfo); await WaitWaiterAsync(workspace.ExportProvider).ConfigureAwait(true); var solution = workspace.CurrentSolution; var documentId = solution.Projects.First().DocumentIds[0]; solution = solution.RemoveDocument(documentId); var changedSolution = solution.AddProject("P3", "P3", LanguageNames.CSharp).AddDocument("D1", "").Project.Solution; var worker = await ExecuteOperation(workspace, w => w.ChangeSolution(changedSolution)).ConfigureAwait(true); Assert.Equal(1, worker.SyntaxDocumentIds.Count); } } [WpfFact] public async Task Project_Add() { using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider).ConfigureAwait(true); var projectId = ProjectId.CreateNewId(); var projectInfo = ProjectInfo.Create( projectId, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp, documents: new List<DocumentInfo> { DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1"), DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D2") }); var worker = await ExecuteOperation(workspace, w => w.OnProjectAdded(projectInfo)).ConfigureAwait(true); Assert.Equal(2, worker.SyntaxDocumentIds.Count); } } [WpfFact] public async Task Project_Remove() { using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider).ConfigureAwait(true); var projectid = workspace.CurrentSolution.ProjectIds[0]; var worker = await ExecuteOperation(workspace, w => w.OnProjectRemoved(projectid)).ConfigureAwait(true); Assert.Equal(0, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.InvalidateDocumentIds.Count); } } [WpfFact] public async Task Project_Change() { using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solutionInfo = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solutionInfo); await WaitWaiterAsync(workspace.ExportProvider).ConfigureAwait(true); var project = workspace.CurrentSolution.Projects.First(); var documentId = project.DocumentIds[0]; var solution = workspace.CurrentSolution.RemoveDocument(documentId); var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, solution)).ConfigureAwait(true); Assert.Equal(0, worker.SyntaxDocumentIds.Count); Assert.Equal(1, worker.InvalidateDocumentIds.Count); } } [WpfFact] public async Task Project_AssemblyName_Change() { using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solutionInfo = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solutionInfo); await WaitWaiterAsync(workspace.ExportProvider).ConfigureAwait(true); var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1").WithAssemblyName("newName"); var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, project.Solution)).ConfigureAwait(true); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); } } [WpfFact] public async Task Project_AnalyzerOptions_Change() { using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solutionInfo = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solutionInfo); await WaitWaiterAsync(workspace.ExportProvider).ConfigureAwait(true); var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1").AddAdditionalDocument("a1", SourceText.From("")).Project; var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, project.Solution)).ConfigureAwait(true); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); } } [WpfFact] public async Task Project_Reload() { using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider).ConfigureAwait(true); var project = solution.Projects[0]; var worker = await ExecuteOperation(workspace, w => w.OnProjectReloaded(project)).ConfigureAwait(true); Assert.Equal(0, worker.SyntaxDocumentIds.Count); } } [WpfFact] public async Task Document_Add() { using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider).ConfigureAwait(true); var project = solution.Projects[0]; var info = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "D6"); var worker = await ExecuteOperation(workspace, w => w.OnDocumentAdded(info)).ConfigureAwait(true); Assert.Equal(1, worker.SyntaxDocumentIds.Count); Assert.Equal(6, worker.DocumentIds.Count); } } [WpfFact] public async Task Document_Remove() { using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider).ConfigureAwait(true); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var worker = await ExecuteOperation(workspace, w => w.OnDocumentRemoved(id)).ConfigureAwait(true); Assert.Equal(0, worker.SyntaxDocumentIds.Count); Assert.Equal(4, worker.DocumentIds.Count); Assert.Equal(1, worker.InvalidateDocumentIds.Count); } } [WpfFact] public async Task Document_Reload() { using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider).ConfigureAwait(true); var id = solution.Projects[0].Documents[0]; var worker = await ExecuteOperation(workspace, w => w.OnDocumentReloaded(id)).ConfigureAwait(true); Assert.Equal(0, worker.SyntaxDocumentIds.Count); } } [WpfFact] public async Task Document_Reanalyze() { using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider).ConfigureAwait(true); var info = solution.Projects[0].Documents[0]; var worker = new Analyzer(); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(worker), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); // don't rely on background parser to have tree. explicitly do it here. TouchEverything(workspace.CurrentSolution); service.Reanalyze(workspace, worker, projectIds: null, documentIds: SpecializedCollections.SingletonEnumerable<DocumentId>(info.Id)); TouchEverything(workspace.CurrentSolution); await WaitAsync(service, workspace).ConfigureAwait(true); service.Unregister(workspace); Assert.Equal(1, worker.SyntaxDocumentIds.Count); Assert.Equal(1, worker.DocumentIds.Count); } } [WorkItem(670335)] public async Task Document_Change() { using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider).ConfigureAwait(true); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var worker = await ExecuteOperation(workspace, w => w.ChangeDocument(id, SourceText.From("//"))).ConfigureAwait(true); Assert.Equal(1, worker.SyntaxDocumentIds.Count); } } [WpfFact] public async Task Document_AdditionalFileChange() { using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider).ConfigureAwait(true); var project = solution.Projects[0]; var ncfile = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "D6"); var worker = await ExecuteOperation(workspace, w => w.OnAdditionalDocumentAdded(ncfile)).ConfigureAwait(true); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); worker = await ExecuteOperation(workspace, w => w.ChangeAdditionalDocument(ncfile.Id, SourceText.From("//"))).ConfigureAwait(true); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); worker = await ExecuteOperation(workspace, w => w.OnAdditionalDocumentRemoved(ncfile.Id)).ConfigureAwait(true); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); } } [WorkItem(670335)] public async Task Document_Cancellation() { using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider).ConfigureAwait(true); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var analyzer = new Analyzer(waitForCancellation: true); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); workspace.ChangeDocument(id, SourceText.From("//")); analyzer.RunningEvent.Wait(); workspace.ChangeDocument(id, SourceText.From("// ")); await WaitAsync(service, workspace).ConfigureAwait(true); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(5, analyzer.DocumentIds.Count); } } [WorkItem(670335)] public async Task Document_Cancellation_MultipleTimes() { using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider).ConfigureAwait(true); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var analyzer = new Analyzer(waitForCancellation: true); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); workspace.ChangeDocument(id, SourceText.From("//")); analyzer.RunningEvent.Wait(); analyzer.RunningEvent.Reset(); workspace.ChangeDocument(id, SourceText.From("// ")); analyzer.RunningEvent.Wait(); workspace.ChangeDocument(id, SourceText.From("// ")); await WaitAsync(service, workspace).ConfigureAwait(true); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(5, analyzer.DocumentIds.Count); } } [WorkItem(670335)] public async Task Document_InvocationReasons() { using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider).ConfigureAwait(true); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var analyzer = new Analyzer(blockedRun: true); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); // first invocation will block worker workspace.ChangeDocument(id, SourceText.From("//")); analyzer.RunningEvent.Wait(); var openReady = new ManualResetEventSlim(initialState: false); var closeReady = new ManualResetEventSlim(initialState: false); workspace.DocumentOpened += (o, e) => openReady.Set(); workspace.DocumentClosed += (o, e) => closeReady.Set(); // cause several different request to queue up workspace.ChangeDocument(id, SourceText.From("// ")); workspace.OpenDocument(id); workspace.CloseDocument(id); openReady.Set(); closeReady.Set(); analyzer.BlockEvent.Set(); await WaitAsync(service, workspace).ConfigureAwait(true); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(5, analyzer.DocumentIds.Count); } } [WpfFact] public async Task Document_TopLevelType_Whitespace() { var code = @"class C { $$ }"; var textToInsert = " "; await InsertText(code, textToInsert, expectDocumentAnalysis: true).ConfigureAwait(true); } [WpfFact] public async Task Document_TopLevelType_Character() { var code = @"class C { $$ }"; var textToInsert = "int"; await InsertText(code, textToInsert, expectDocumentAnalysis: true).ConfigureAwait(true); } [WpfFact] public async Task Document_TopLevelType_NewLine() { var code = @"class C { $$ }"; var textToInsert = "\r\n"; await InsertText(code, textToInsert, expectDocumentAnalysis: true).ConfigureAwait(true); } [WpfFact] public async Task Document_TopLevelType_NewLine2() { var code = @"class C { $$"; var textToInsert = "\r\n"; await InsertText(code, textToInsert, expectDocumentAnalysis: true).ConfigureAwait(true); } [WpfFact] public async Task Document_EmptyFile() { var code = @"$$"; var textToInsert = "class"; await InsertText(code, textToInsert, expectDocumentAnalysis: true).ConfigureAwait(true); } [WpfFact] public async Task Document_TopLevel1() { var code = @"class C { public void Test($$"; var textToInsert = "int"; await InsertText(code, textToInsert, expectDocumentAnalysis: true).ConfigureAwait(true); } [WpfFact] public async Task Document_TopLevel2() { var code = @"class C { public void Test(int $$"; var textToInsert = " "; await InsertText(code, textToInsert, expectDocumentAnalysis: true).ConfigureAwait(true); } [WpfFact] public async Task Document_TopLevel3() { var code = @"class C { public void Test(int i,$$"; var textToInsert = "\r\n"; await InsertText(code, textToInsert, expectDocumentAnalysis: true).ConfigureAwait(true); } [WpfFact] public async Task Document_InteriorNode1() { var code = @"class C { public void Test() {$$"; var textToInsert = "\r\n"; await InsertText(code, textToInsert, expectDocumentAnalysis: false).ConfigureAwait(true); } [WpfFact] public async Task Document_InteriorNode2() { var code = @"class C { public void Test() { $$ }"; var textToInsert = "int"; await InsertText(code, textToInsert, expectDocumentAnalysis: false).ConfigureAwait(true); } [WpfFact] public async Task Document_InteriorNode_Field() { var code = @"class C { int i = $$ }"; var textToInsert = "1"; await InsertText(code, textToInsert, expectDocumentAnalysis: false).ConfigureAwait(true); } [WpfFact] public async Task Document_InteriorNode_Field1() { var code = @"class C { int i = 1 + $$ }"; var textToInsert = "1"; await InsertText(code, textToInsert, expectDocumentAnalysis: false).ConfigureAwait(true); } [WpfFact] public async Task Document_InteriorNode_Accessor() { var code = @"class C { public int A { get { $$ } } }"; var textToInsert = "return"; await InsertText(code, textToInsert, expectDocumentAnalysis: false).ConfigureAwait(true); } [WpfFact] public async Task Document_TopLevelWhitespace() { var code = @"class C { /// $$ public int A() { } }"; var textToInsert = "return"; await InsertText(code, textToInsert, expectDocumentAnalysis: true).ConfigureAwait(true); } [WpfFact] public async Task Document_TopLevelWhitespace2() { var code = @"/// $$ class C { public int A() { } }"; var textToInsert = "return"; await InsertText(code, textToInsert, expectDocumentAnalysis: true).ConfigureAwait(true); } [WpfFact] public async Task Document_InteriorNode_Malformed() { var code = @"class C { public void Test() { $$"; var textToInsert = "int"; await InsertText(code, textToInsert, expectDocumentAnalysis: true).ConfigureAwait(true); } [WpfFact] public void VBPropertyTest() { var markup = @"Class C Default Public Property G(x As Integer) As Integer Get $$ End Get Set(value As Integer) End Set End Property End Class"; int position; string code; MarkupTestFile.GetPosition(markup, out code, out position); var root = Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.ParseCompilationUnit(code); var property = root.FindToken(position).Parent.FirstAncestorOrSelf<Microsoft.CodeAnalysis.VisualBasic.Syntax.PropertyBlockSyntax>(); var memberId = (new Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxFactsService()).GetMethodLevelMemberId(root, property); Assert.Equal(0, memberId); } [WpfFact, WorkItem(739943)] public async Task SemanticChange_Propagation() { var solution = GetInitialSolutionInfoWithP2P(); using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider).ConfigureAwait(true); var id = solution.Projects[0].Id; var info = DocumentInfo.Create(DocumentId.CreateNewId(id), "D6"); var worker = await ExecuteOperation(workspace, w => w.OnDocumentAdded(info)).ConfigureAwait(true); Assert.Equal(1, worker.SyntaxDocumentIds.Count); Assert.Equal(4, worker.DocumentIds.Count); #if false Assert.True(1 == worker.SyntaxDocumentIds.Count, string.Format("Expected 1 SyntaxDocumentIds, Got {0}\n\n{1}", worker.SyntaxDocumentIds.Count, GetListenerTrace(workspace.ExportProvider))); Assert.True(4 == worker.DocumentIds.Count, string.Format("Expected 4 DocumentIds, Got {0}\n\n{1}", worker.DocumentIds.Count, GetListenerTrace(workspace.ExportProvider))); #endif } } [WpfFact] public async Task ProgressReporterTest() { var solution = GetInitialSolutionInfoWithP2P(); using (var workspace = new WorkCoordinatorWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { await WaitWaiterAsync(workspace.ExportProvider).ConfigureAwait(true); var service = workspace.Services.GetService<ISolutionCrawlerService>(); var reporter = service.GetProgressReporter(workspace); Assert.False(reporter.InProgress); // set up events bool started = false; reporter.Started += (o, a) => { started = true; }; bool stopped = false; reporter.Stopped += (o, a) => { stopped = true; }; var registrationService = workspace.Services.GetService<ISolutionCrawlerRegistrationService>(); registrationService.Register(workspace); // first mutation workspace.OnSolutionAdded(solution); await WaitAsync((SolutionCrawlerRegistrationService)registrationService, workspace).ConfigureAwait(true); Assert.True(started); Assert.True(stopped); // reset started = false; stopped = false; // second mutation workspace.OnDocumentAdded(DocumentInfo.Create(DocumentId.CreateNewId(solution.Projects[0].Id), "D6")); await WaitAsync((SolutionCrawlerRegistrationService)registrationService, workspace).ConfigureAwait(true); Assert.True(started); Assert.True(stopped); registrationService.Unregister(workspace); } } private async Task InsertText(string code, string text, bool expectDocumentAnalysis, string language = LanguageNames.CSharp) { using (var workspace = TestWorkspaceFactory.CreateWorkspaceFromLines( SolutionCrawler, language, compilationOptions: null, parseOptions: null, content: new string[] { code })) { var analyzer = new Analyzer(); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); var testDocument = workspace.Documents.First(); var insertPosition = testDocument.CursorPosition; var textBuffer = testDocument.GetTextBuffer(); using (var edit = textBuffer.CreateEdit()) { edit.Insert(insertPosition.Value, text); edit.Apply(); } await WaitAsync(service, workspace).ConfigureAwait(true); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(expectDocumentAnalysis ? 1 : 0, analyzer.DocumentIds.Count); } } private async Task<Analyzer> ExecuteOperation(TestWorkspace workspace, Action<TestWorkspace> operation) { var worker = new Analyzer(); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(worker), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); // don't rely on background parser to have tree. explicitly do it here. TouchEverything(workspace.CurrentSolution); operation(workspace); TouchEverything(workspace.CurrentSolution); await WaitAsync(service, workspace).ConfigureAwait(true); service.Unregister(workspace); return worker; } private void TouchEverything(Solution solution) { foreach (var project in solution.Projects) { foreach (var document in project.Documents) { document.GetTextAsync().PumpingWait(); document.GetSyntaxRootAsync().PumpingWait(); document.GetSemanticModelAsync().PumpingWait(); } } } private async Task WaitAsync(SolutionCrawlerRegistrationService service, TestWorkspace workspace) { await WaitWaiterAsync(workspace.ExportProvider).ConfigureAwait(true); service.WaitUntilCompletion_ForTestingPurposesOnly(workspace); } private async Task WaitWaiterAsync(ExportProvider provider) { var workspaceWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as IAsynchronousOperationWaiter; await workspaceWaiter.CreateWaitTask().ConfigureAwait(true); var solutionCrawlerWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as IAsynchronousOperationWaiter; await solutionCrawlerWaiter.CreateWaitTask().ConfigureAwait(true); } private static SolutionInfo GetInitialSolutionInfoWithP2P() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var projectId3 = ProjectId.CreateNewId(); var projectId4 = ProjectId.CreateNewId(); var projectId5 = ProjectId.CreateNewId(); var solution = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), projects: new[] { ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D1") }), ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D2") }, projectReferences: new[] { new ProjectReference(projectId1) }), ProjectInfo.Create(projectId3, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId3), "D3") }, projectReferences: new[] { new ProjectReference(projectId2) }), ProjectInfo.Create(projectId4, VersionStamp.Create(), "P4", "P4", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId4), "D4") }), ProjectInfo.Create(projectId5, VersionStamp.Create(), "P5", "P5", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId5), "D5") }, projectReferences: new[] { new ProjectReference(projectId4) }), }); return solution; } private static SolutionInfo GetInitialSolutionInfo(TestWorkspace workspace) { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); return SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), projects: new[] { ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D1"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D2"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D3"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D4"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D5") }), ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D1"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D2"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D3"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D4"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D5") }) }); } private static IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> GetListeners(ExportProvider provider) { return provider.GetExports<IAsynchronousOperationListener, FeatureMetadata>(); } [Shared] [Export(typeof(IAsynchronousOperationListener))] [Export(typeof(IAsynchronousOperationWaiter))] [Feature(FeatureAttribute.SolutionCrawler)] private class SolutionCrawlerWaiter : AsynchronousOperationListener { internal SolutionCrawlerWaiter() { } } [Shared] [Export(typeof(IAsynchronousOperationListener))] [Export(typeof(IAsynchronousOperationWaiter))] [Feature(FeatureAttribute.Workspace)] private class WorkspaceWaiter : AsynchronousOperationListener { internal WorkspaceWaiter() { } } private class WorkCoordinatorWorkspace : TestWorkspace { private readonly IAsynchronousOperationWaiter _workspaceWaiter; private readonly IAsynchronousOperationWaiter _solutionCrawlerWaiter; public WorkCoordinatorWorkspace(ExportProvider exportProvider, string workspaceKind = null, bool disablePartialSolutions = true) : base(exportProvider, workspaceKind, disablePartialSolutions) { _workspaceWaiter = GetListeners(ExportProvider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as IAsynchronousOperationWaiter; _solutionCrawlerWaiter = GetListeners(ExportProvider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as IAsynchronousOperationWaiter; Assert.False(_workspaceWaiter.HasPendingWork); Assert.False(_solutionCrawlerWaiter.HasPendingWork); } protected override void Dispose(bool finalize) { base.Dispose(finalize); // Bug https://github.com/dotnet/roslyn/issues/5915 // Assert.False(_workspaceWaiter.HasPendingWork); // Assert.False(_solutionCrawlerWaiter.HasPendingWork); } } private class AnalyzerProvider : IIncrementalAnalyzerProvider { private readonly Analyzer _analyzer; public AnalyzerProvider(Analyzer analyzer) { _analyzer = analyzer; } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) { return _analyzer; } } internal class Metadata : IncrementalAnalyzerProviderMetadata { public Metadata(params string[] workspaceKinds) : base(new Dictionary<string, object> { { "WorkspaceKinds", workspaceKinds }, { "HighPriorityForActiveFile", false } }) { } public static readonly Metadata Crawler = new Metadata(SolutionCrawler); } private class Analyzer : IIncrementalAnalyzer { private readonly bool _waitForCancellation; private readonly bool _blockedRun; public readonly ManualResetEventSlim BlockEvent; public readonly ManualResetEventSlim RunningEvent; public readonly HashSet<DocumentId> SyntaxDocumentIds = new HashSet<DocumentId>(); public readonly HashSet<DocumentId> DocumentIds = new HashSet<DocumentId>(); public readonly HashSet<ProjectId> ProjectIds = new HashSet<ProjectId>(); public readonly HashSet<DocumentId> InvalidateDocumentIds = new HashSet<DocumentId>(); public readonly HashSet<ProjectId> InvalidateProjectIds = new HashSet<ProjectId>(); public Analyzer(bool waitForCancellation = false, bool blockedRun = false) { _waitForCancellation = waitForCancellation; _blockedRun = blockedRun; this.BlockEvent = new ManualResetEventSlim(initialState: false); this.RunningEvent = new ManualResetEventSlim(initialState: false); } public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken) { this.ProjectIds.Add(project.Id); return SpecializedTasks.EmptyTask; } public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken) { if (bodyOpt == null) { this.DocumentIds.Add(document.Id); } return SpecializedTasks.EmptyTask; } public Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) { this.SyntaxDocumentIds.Add(document.Id); Process(document.Id, cancellationToken); return SpecializedTasks.EmptyTask; } public void RemoveDocument(DocumentId documentId) { InvalidateDocumentIds.Add(documentId); } public void RemoveProject(ProjectId projectId) { InvalidateProjectIds.Add(projectId); } private void Process(DocumentId documentId, CancellationToken cancellationToken) { if (_blockedRun && !RunningEvent.IsSet) { this.RunningEvent.Set(); // Wait until unblocked this.BlockEvent.Wait(); } if (_waitForCancellation && !RunningEvent.IsSet) { this.RunningEvent.Set(); cancellationToken.WaitHandle.WaitOne(); cancellationToken.ThrowIfCancellationRequested(); } } #region unused public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task DocumentResetAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) { return false; } #endregion } #if false private string GetListenerTrace(ExportProvider provider) { var sb = new StringBuilder(); var workspaceWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as TestAsynchronousOperationListener; sb.AppendLine("workspace"); sb.AppendLine(workspaceWaiter.Trace()); var solutionCrawlerWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as TestAsynchronousOperationListener; sb.AppendLine("solutionCrawler"); sb.AppendLine(solutionCrawlerWaiter.Trace()); return sb.ToString(); } internal abstract partial class TestAsynchronousOperationListener : IAsynchronousOperationListener, IAsynchronousOperationWaiter { private readonly object gate = new object(); private readonly HashSet<TaskCompletionSource<bool>> pendingTasks = new HashSet<TaskCompletionSource<bool>>(); private readonly StringBuilder sb = new StringBuilder(); private int counter; public TestAsynchronousOperationListener() { } public IAsyncToken BeginAsyncOperation(string name, object tag = null) { lock (gate) { return new AsyncToken(this, name); } } private void Increment(string name) { lock (gate) { sb.AppendLine("i -> " + name + ":" + counter++); } } private void Decrement(string name) { lock (gate) { counter--; if (counter == 0) { foreach (var task in pendingTasks) { task.SetResult(true); } pendingTasks.Clear(); } sb.AppendLine("d -> " + name + ":" + counter); } } public virtual Task CreateWaitTask() { lock (gate) { var source = new TaskCompletionSource<bool>(); if (counter == 0) { // There is nothing to wait for, so we are immediately done source.SetResult(true); } else { pendingTasks.Add(source); } return source.Task; } } public bool TrackActiveTokens { get; set; } public bool HasPendingWork { get { return counter != 0; } } private class AsyncToken : IAsyncToken { private readonly TestAsynchronousOperationListener listener; private readonly string name; private bool disposed; public AsyncToken(TestAsynchronousOperationListener listener, string name) { this.listener = listener; this.name = name; listener.Increment(name); } public void Dispose() { lock (listener.gate) { if (disposed) { throw new InvalidOperationException("Double disposing of an async token"); } disposed = true; listener.Decrement(this.name); } } } public string Trace() { return sb.ToString(); } } #endif } }
#pragma warning disable 1591 using AjaxControlToolkit.Design; using System; using System.ComponentModel; using System.Drawing; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; namespace AjaxControlToolkit { /// <summary> /// PopupControl is an ASP.NET AJAX extender that can be attached to any control to open a popup /// window that displays additional content. This popup window will probably be interactive and /// located within an ASP.NET AJAX UpdatePanel. So, it will perform complex server-based processing /// (including postbacks) without affecting the rest of the page. The popup window can contain any /// content including ASP.NET server controls, HTML elements, etc. Once work of the popup window is /// done, a simple server-side call dismisses it and triggers any relevant script on the client to /// run and update the page dynamically. /// </summary> [ClientScriptResource("Sys.Extended.UI.PopupControlBehavior", Constants.PopupControlName)] [RequiredScript(typeof(PopupExtender))] [RequiredScript(typeof(CommonToolkitScripts))] [TargetControlType(typeof(WebControl))] [TargetControlType(typeof(HtmlControl))] [Designer(typeof(PopupControlExtenderDesigner))] [ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.PopupControlName + Constants.IconPostfix)] public class PopupControlExtender : DynamicPopulateExtenderControlBase { bool _shouldClose; string _closeString; Page _proxyForCurrentPopup; EventHandler _pagePreRenderHandler; public PopupControlExtender() { } // Constructor with a page - Used to initialize proxy controls only. private PopupControlExtender(Page page) { _proxyForCurrentPopup = page; // In this case, the control acts as a proxy // It is not actually added to control collections and does not participate in the page cycle // Attach the Page.PreRender event _pagePreRenderHandler = new EventHandler(Page_PreRender); _proxyForCurrentPopup.PreRender += _pagePreRenderHandler; } /// <summary> /// Returns a proxy PopupControlExtender representing the currently active popup on the specified page /// </summary> /// <remarks> /// Only the Cancel and Commit methods should be called on the proxy /// </remarks> /// <param name="page" type="Page">Page</param> /// <returns>Popup control extender</returns> public static PopupControlExtender GetProxyForCurrentPopup(Page page) { var popupControlExtender = new PopupControlExtender(page); return popupControlExtender; } /// <summary> /// Cancels the popup control and hides it abandoning results /// </summary> public void Cancel() { // It is possible for Cancel() to be called numerous times during the same postback so we just remember the desired state // Pass the magic cancel string as the result _closeString = "$$CANCEL$$"; _shouldClose = true; } /// <summary> /// Commits the popup control and hides it applying the specified result /// </summary> /// <param name="result" type="String">Result</param> public void Commit(string result) { // It is possible for Commit() to be called numerous times during the same postback so we just remember the desired state _closeString = result; _shouldClose = true; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); // Attach the Page.PreRender event - Make sure we hook up only once if(_pagePreRenderHandler == null) { _pagePreRenderHandler = new EventHandler(Page_PreRender); Page.PreRender += _pagePreRenderHandler; } } protected void Page_PreRender(object sender, EventArgs e) { // If Cancel()/Commit() were called, close the popup now if(_shouldClose) Close(_closeString); } // Closes the popup control, applying the specified result or abandoning it void Close(string result) { if(_proxyForCurrentPopup == null) { // Normal call - Simply register the relevant data item for the TargetControl ScriptManager.GetCurrent(Page).RegisterDataItem(TargetControl, result); } else { // Proxy call - Add a LiteralControl to pass the information down to the interested PopupControlExtender var literalControl = new LiteralControl(); literalControl.ID = "_PopupControl_Proxy_ID_"; _proxyForCurrentPopup.Controls.Add(literalControl); ScriptManager.GetCurrent(_proxyForCurrentPopup).RegisterDataItem(literalControl, result); } } /// <summary> /// The ID of the extender control /// </summary> [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [ClientPropertyName("extenderControlID")] public string ExtenderControlID { get { return GetPropertyValue("ExtenderControlID", String.Empty); } set { SetPropertyValue("ExtenderControlID", value); } } /// <summary> /// The ID of the control to display /// </summary> [ExtenderControlProperty] [IDReferenceProperty(typeof(WebControl))] [RequiredProperty] [DefaultValue("")] [ClientPropertyName("popupControlID")] public string PopupControlID { get { return GetPropertyValue("PopupControlID", String.Empty); } set { SetPropertyValue("PopupControlID", value); } } /// <summary> /// Optional setting specifying a property of the control being extended that /// should be set with the result of the popup /// </summary> /// <remarks> /// If the property value is missing (an empty line), the default "value" property will be used /// </remarks> [ExtenderControlProperty] [DefaultValue("")] [ClientPropertyName("commitProperty")] public string CommitProperty { get { return GetPropertyValue("CommitProperty", String.Empty); } set { SetPropertyValue("CommitProperty", value); } } /// <summary> /// Optional setting specifying an additional script to run after the result of the popup is set /// </summary> [ExtenderControlProperty] [DefaultValue("")] [ClientPropertyName("commitScript")] public string CommitScript { get { return GetPropertyValue("CommitScript", String.Empty); } set { SetPropertyValue("CommitScript", value); } } /// <summary> /// Optional setting specifying where the popup should be positioned relative to the target /// control (Left, Right, Top, Bottom, or Center) /// </summary> [ExtenderControlProperty] [DefaultValue(PopupControlPopupPosition.Center)] [ClientPropertyName("position")] public PopupControlPopupPosition Position { get { return GetPropertyValue("Position", PopupControlPopupPosition.Center); } set { SetPropertyValue("Position", value); } } /// <summary> /// The number of pixels to offset the Popup from its default position, as specified by Position /// </summary> [ExtenderControlProperty] [DefaultValue(0)] [ClientPropertyName("offsetX")] public int OffsetX { get { return GetPropertyValue("OffsetX", 0); } set { SetPropertyValue("OffsetX", value); } } /// <summary> /// The number of pixels to offset the Popup from its default position, as specified by Position /// </summary> [ExtenderControlProperty] [DefaultValue(0)] [ClientPropertyName("offsetY")] public int OffsetY { get { return GetPropertyValue("OffsetY", 0); } set { SetPropertyValue("OffsetY", value); } } /// <summary> /// OnShow animation will be played each time the popup is displayed. The /// popup will be positioned correctly but hidden. Animation can be used /// to display the popup with other visual effects /// </summary> [ExtenderControlProperty] [ClientPropertyName("onShow")] [Browsable(false)] [DefaultValue(null)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Animation OnShow { get { return GetAnimation(ref _onShow, "OnShow"); } set { SetAnimation(ref _onShow, "OnShow", value); } } Animation _onShow; /// <summary> /// OnHide animation will be played each time the popup is hidden /// </summary> [ExtenderControlProperty] [ClientPropertyName("onHide")] [Browsable(false)] [DefaultValue(null)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Animation OnHide { get { return GetAnimation(ref _onHide, "OnHide"); } set { SetAnimation(ref _onHide, "OnHide", value); } } Animation _onHide; // Convert server IDs into ClientIDs for animations protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); ResolveControlIDs(_onShow); ResolveControlIDs(_onHide); } } } #pragma warning restore 1591
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace Windows.UI.Xaml { [global::System.Security.SecurityCriticalAttribute] [global::System.Runtime.InteropServices.StructLayoutAttribute(global::System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct CornerRadius { public CornerRadius(double uniformRadius) { throw new global::System.NotImplementedException(); } public CornerRadius(double topLeft, double topRight, double bottomRight, double bottomLeft) { throw new global::System.NotImplementedException(); } public double BottomLeft { get { return default(double); } set { } } public double BottomRight { get { return default(double); } set { } } public double TopLeft { get { return default(double); } set { } } public double TopRight { get { return default(double); } set { } } [global::System.Security.SecuritySafeCriticalAttribute] public override bool Equals(object obj) { return default(bool); } public bool Equals(global::Windows.UI.Xaml.CornerRadius cornerRadius) { return default(bool); } [global::System.Security.SecuritySafeCriticalAttribute] public override int GetHashCode() { return default(int); } public static bool operator ==(global::Windows.UI.Xaml.CornerRadius cr1, global::Windows.UI.Xaml.CornerRadius cr2) { return default(bool); } public static bool operator !=(global::Windows.UI.Xaml.CornerRadius cr1, global::Windows.UI.Xaml.CornerRadius cr2) { return default(bool); } [global::System.Security.SecuritySafeCriticalAttribute] public override string ToString() { return default(string); } } [global::System.Security.SecurityCriticalAttribute] [global::System.Runtime.InteropServices.StructLayoutAttribute(global::System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Duration { public Duration(global::System.TimeSpan timeSpan) { throw new global::System.NotImplementedException(); } public static global::Windows.UI.Xaml.Duration Automatic { get { return default(global::Windows.UI.Xaml.Duration); } } public static global::Windows.UI.Xaml.Duration Forever { get { return default(global::Windows.UI.Xaml.Duration); } } public bool HasTimeSpan { get { return default(bool); } } public global::System.TimeSpan TimeSpan { get { return default(global::System.TimeSpan); } } public global::Windows.UI.Xaml.Duration Add(global::Windows.UI.Xaml.Duration duration) { return default(global::Windows.UI.Xaml.Duration); } public static int Compare(global::Windows.UI.Xaml.Duration t1, global::Windows.UI.Xaml.Duration t2) { return default(int); } [global::System.Security.SecuritySafeCriticalAttribute] public override bool Equals(object value) { return default(bool); } public bool Equals(global::Windows.UI.Xaml.Duration duration) { return default(bool); } public static bool Equals(global::Windows.UI.Xaml.Duration t1, global::Windows.UI.Xaml.Duration t2) { return default(bool); } [global::System.Security.SecuritySafeCriticalAttribute] public override int GetHashCode() { return default(int); } public static global::Windows.UI.Xaml.Duration operator +(global::Windows.UI.Xaml.Duration t1, global::Windows.UI.Xaml.Duration t2) { return default(global::Windows.UI.Xaml.Duration); } public static bool operator ==(global::Windows.UI.Xaml.Duration t1, global::Windows.UI.Xaml.Duration t2) { return default(bool); } public static bool operator >(global::Windows.UI.Xaml.Duration t1, global::Windows.UI.Xaml.Duration t2) { return default(bool); } public static bool operator >=(global::Windows.UI.Xaml.Duration t1, global::Windows.UI.Xaml.Duration t2) { return default(bool); } public static implicit operator global::Windows.UI.Xaml.Duration(global::System.TimeSpan timeSpan) { return default(global::Windows.UI.Xaml.Duration); } public static bool operator !=(global::Windows.UI.Xaml.Duration t1, global::Windows.UI.Xaml.Duration t2) { return default(bool); } public static bool operator <(global::Windows.UI.Xaml.Duration t1, global::Windows.UI.Xaml.Duration t2) { return default(bool); } public static bool operator <=(global::Windows.UI.Xaml.Duration t1, global::Windows.UI.Xaml.Duration t2) { return default(bool); } public static global::Windows.UI.Xaml.Duration operator -(global::Windows.UI.Xaml.Duration t1, global::Windows.UI.Xaml.Duration t2) { return default(global::Windows.UI.Xaml.Duration); } public static global::Windows.UI.Xaml.Duration operator +(global::Windows.UI.Xaml.Duration duration) { return default(global::Windows.UI.Xaml.Duration); } public global::Windows.UI.Xaml.Duration Subtract(global::Windows.UI.Xaml.Duration duration) { return default(global::Windows.UI.Xaml.Duration); } [global::System.Security.SecuritySafeCriticalAttribute] public override string ToString() { return default(string); } } [global::System.Security.SecurityCriticalAttribute] public enum DurationType { Automatic = 0, Forever = 2, TimeSpan = 1, } [global::System.Security.SecurityCriticalAttribute] [global::System.Runtime.InteropServices.StructLayoutAttribute(global::System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct GridLength { public GridLength(double pixels) { throw new global::System.NotImplementedException(); } public GridLength(double value, global::Windows.UI.Xaml.GridUnitType type) { throw new global::System.NotImplementedException(); } public static global::Windows.UI.Xaml.GridLength Auto { get { return default(global::Windows.UI.Xaml.GridLength); } } public global::Windows.UI.Xaml.GridUnitType GridUnitType { get { return default(global::Windows.UI.Xaml.GridUnitType); } } public bool IsAbsolute { get { return default(bool); } } public bool IsAuto { get { return default(bool); } } public bool IsStar { get { return default(bool); } } public double Value { get { return default(double); } } [global::System.Security.SecuritySafeCriticalAttribute] public override bool Equals(object oCompare) { return default(bool); } public bool Equals(global::Windows.UI.Xaml.GridLength gridLength) { return default(bool); } [global::System.Security.SecuritySafeCriticalAttribute] public override int GetHashCode() { return default(int); } public static bool operator ==(global::Windows.UI.Xaml.GridLength gl1, global::Windows.UI.Xaml.GridLength gl2) { return default(bool); } public static bool operator !=(global::Windows.UI.Xaml.GridLength gl1, global::Windows.UI.Xaml.GridLength gl2) { return default(bool); } [global::System.Security.SecuritySafeCriticalAttribute] public override string ToString() { return default(string); } } [global::System.Security.SecurityCriticalAttribute] public enum GridUnitType { Auto = 0, Pixel = 1, Star = 2, } [global::System.Security.SecurityCriticalAttribute] public partial class LayoutCycleException : global::System.Exception { public LayoutCycleException() { } public LayoutCycleException(string message) { } public LayoutCycleException(string message, global::System.Exception innerException) { } } [global::System.Security.SecurityCriticalAttribute] [global::System.Runtime.InteropServices.StructLayoutAttribute(global::System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Thickness { public Thickness(double uniformLength) { throw new global::System.NotImplementedException(); } public Thickness(double left, double top, double right, double bottom) { throw new global::System.NotImplementedException(); } public double Bottom { get { return default(double); } set { } } public double Left { get { return default(double); } set { } } public double Right { get { return default(double); } set { } } public double Top { get { return default(double); } set { } } [global::System.Security.SecuritySafeCriticalAttribute] public override bool Equals(object obj) { return default(bool); } public bool Equals(global::Windows.UI.Xaml.Thickness thickness) { return default(bool); } [global::System.Security.SecuritySafeCriticalAttribute] public override int GetHashCode() { return default(int); } public static bool operator ==(global::Windows.UI.Xaml.Thickness t1, global::Windows.UI.Xaml.Thickness t2) { return default(bool); } public static bool operator !=(global::Windows.UI.Xaml.Thickness t1, global::Windows.UI.Xaml.Thickness t2) { return default(bool); } [global::System.Security.SecuritySafeCriticalAttribute] public override string ToString() { return default(string); } } } namespace Windows.UI.Xaml.Automation { [global::System.Security.SecurityCriticalAttribute] public partial class ElementNotAvailableException : global::System.Exception { public ElementNotAvailableException() { } public ElementNotAvailableException(string message) { } public ElementNotAvailableException(string message, global::System.Exception innerException) { } } [global::System.Security.SecurityCriticalAttribute] public partial class ElementNotEnabledException : global::System.Exception { public ElementNotEnabledException() { } public ElementNotEnabledException(string message) { } public ElementNotEnabledException(string message, global::System.Exception innerException) { } } } namespace Windows.UI.Xaml.Controls.Primitives { [global::System.Security.SecurityCriticalAttribute] [global::System.Runtime.InteropServices.StructLayoutAttribute(global::System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct GeneratorPosition { public GeneratorPosition(int index, int offset) { throw new global::System.NotImplementedException(); } public int Index { get { return default(int); } set { } } public int Offset { get { return default(int); } set { } } [global::System.Security.SecuritySafeCriticalAttribute] public override bool Equals(object o) { return default(bool); } [global::System.Security.SecuritySafeCriticalAttribute] public override int GetHashCode() { return default(int); } public static bool operator ==(global::Windows.UI.Xaml.Controls.Primitives.GeneratorPosition gp1, global::Windows.UI.Xaml.Controls.Primitives.GeneratorPosition gp2) { return default(bool); } public static bool operator !=(global::Windows.UI.Xaml.Controls.Primitives.GeneratorPosition gp1, global::Windows.UI.Xaml.Controls.Primitives.GeneratorPosition gp2) { return default(bool); } [global::System.Security.SecuritySafeCriticalAttribute] public override string ToString() { return default(string); } } } namespace Windows.UI.Xaml.Markup { [global::System.Security.SecurityCriticalAttribute] public partial class XamlParseException : global::System.Exception { public XamlParseException() { } public XamlParseException(string message) { } public XamlParseException(string message, global::System.Exception innerException) { } } } namespace Windows.UI.Xaml.Media { [global::System.Security.SecurityCriticalAttribute] [global::System.Runtime.InteropServices.StructLayoutAttribute(global::System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Matrix : global::System.IFormattable { public Matrix(double m11, double m12, double m21, double m22, double offsetX, double offsetY) { throw new global::System.NotImplementedException(); } public static global::Windows.UI.Xaml.Media.Matrix Identity { get { return default(global::Windows.UI.Xaml.Media.Matrix); } } public bool IsIdentity { get { return default(bool); } } public double M11 { get { return default(double); } set { } } public double M12 { get { return default(double); } set { } } public double M21 { get { return default(double); } set { } } public double M22 { get { return default(double); } set { } } public double OffsetX { get { return default(double); } set { } } public double OffsetY { get { return default(double); } set { } } [global::System.Security.SecuritySafeCriticalAttribute] public override bool Equals(object o) { return default(bool); } public bool Equals(global::Windows.UI.Xaml.Media.Matrix value) { return default(bool); } [global::System.Security.SecuritySafeCriticalAttribute] public override int GetHashCode() { return default(int); } public static bool operator ==(global::Windows.UI.Xaml.Media.Matrix matrix1, global::Windows.UI.Xaml.Media.Matrix matrix2) { return default(bool); } public static bool operator !=(global::Windows.UI.Xaml.Media.Matrix matrix1, global::Windows.UI.Xaml.Media.Matrix matrix2) { return default(bool); } [global::System.Security.SecuritySafeCriticalAttribute] string System.IFormattable.ToString(string format, global::System.IFormatProvider provider) { return default(string); } [global::System.Security.SecuritySafeCriticalAttribute] public override string ToString() { return default(string); } public string ToString(global::System.IFormatProvider provider) { return default(string); } public global::Windows.Foundation.Point Transform(global::Windows.Foundation.Point point) { return default(global::Windows.Foundation.Point); } } } namespace Windows.UI.Xaml.Media.Animation { [global::System.Security.SecurityCriticalAttribute] [global::System.Runtime.InteropServices.StructLayoutAttribute(global::System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct KeyTime { public global::System.TimeSpan TimeSpan { get { return default(global::System.TimeSpan); } } [global::System.Security.SecuritySafeCriticalAttribute] public override bool Equals(object value) { return default(bool); } public bool Equals(global::Windows.UI.Xaml.Media.Animation.KeyTime value) { return default(bool); } public static bool Equals(global::Windows.UI.Xaml.Media.Animation.KeyTime keyTime1, global::Windows.UI.Xaml.Media.Animation.KeyTime keyTime2) { return default(bool); } public static global::Windows.UI.Xaml.Media.Animation.KeyTime FromTimeSpan(global::System.TimeSpan timeSpan) { return default(global::Windows.UI.Xaml.Media.Animation.KeyTime); } [global::System.Security.SecuritySafeCriticalAttribute] public override int GetHashCode() { return default(int); } public static bool operator ==(global::Windows.UI.Xaml.Media.Animation.KeyTime keyTime1, global::Windows.UI.Xaml.Media.Animation.KeyTime keyTime2) { return default(bool); } public static implicit operator global::Windows.UI.Xaml.Media.Animation.KeyTime(global::System.TimeSpan timeSpan) { return default(global::Windows.UI.Xaml.Media.Animation.KeyTime); } public static bool operator !=(global::Windows.UI.Xaml.Media.Animation.KeyTime keyTime1, global::Windows.UI.Xaml.Media.Animation.KeyTime keyTime2) { return default(bool); } [global::System.Security.SecuritySafeCriticalAttribute] public override string ToString() { return default(string); } } [global::System.Security.SecurityCriticalAttribute] [global::System.Runtime.InteropServices.StructLayoutAttribute(global::System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct RepeatBehavior : global::System.IFormattable { public RepeatBehavior(double count) { throw new global::System.NotImplementedException(); } public RepeatBehavior(global::System.TimeSpan duration) { throw new global::System.NotImplementedException(); } public double Count { get { return default(double); } set { } } public global::System.TimeSpan Duration { get { return default(global::System.TimeSpan); } set { } } public static global::Windows.UI.Xaml.Media.Animation.RepeatBehavior Forever { get { return default(global::Windows.UI.Xaml.Media.Animation.RepeatBehavior); } } public bool HasCount { get { return default(bool); } } public bool HasDuration { get { return default(bool); } } public global::Windows.UI.Xaml.Media.Animation.RepeatBehaviorType Type { get { return default(global::Windows.UI.Xaml.Media.Animation.RepeatBehaviorType); } set { } } [global::System.Security.SecuritySafeCriticalAttribute] public override bool Equals(object value) { return default(bool); } public bool Equals(global::Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior) { return default(bool); } public static bool Equals(global::Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior1, global::Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior2) { return default(bool); } [global::System.Security.SecuritySafeCriticalAttribute] public override int GetHashCode() { return default(int); } public static bool operator ==(global::Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior1, global::Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior2) { return default(bool); } public static bool operator !=(global::Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior1, global::Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior2) { return default(bool); } [global::System.Security.SecuritySafeCriticalAttribute] string System.IFormattable.ToString(string format, global::System.IFormatProvider formatProvider) { return default(string); } [global::System.Security.SecuritySafeCriticalAttribute] public override string ToString() { return default(string); } public string ToString(global::System.IFormatProvider formatProvider) { return default(string); } } [global::System.Security.SecurityCriticalAttribute] public enum RepeatBehaviorType { Count = 0, Duration = 1, Forever = 2, } } namespace Windows.UI.Xaml.Media.Media3D { [global::System.Security.SecurityCriticalAttribute] [global::System.Runtime.InteropServices.StructLayoutAttribute(global::System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Matrix3D : global::System.IFormattable { public Matrix3D(double m11, double m12, double m13, double m14, double m21, double m22, double m23, double m24, double m31, double m32, double m33, double m34, double offsetX, double offsetY, double offsetZ, double m44) { throw new global::System.NotImplementedException(); } public bool HasInverse { get { return default(bool); } } public static global::Windows.UI.Xaml.Media.Media3D.Matrix3D Identity { get { return default(global::Windows.UI.Xaml.Media.Media3D.Matrix3D); } } public bool IsIdentity { get { return default(bool); } } public double M11 { get { return default(double); } set { } } public double M12 { get { return default(double); } set { } } public double M13 { get { return default(double); } set { } } public double M14 { get { return default(double); } set { } } public double M21 { get { return default(double); } set { } } public double M22 { get { return default(double); } set { } } public double M23 { get { return default(double); } set { } } public double M24 { get { return default(double); } set { } } public double M31 { get { return default(double); } set { } } public double M32 { get { return default(double); } set { } } public double M33 { get { return default(double); } set { } } public double M34 { get { return default(double); } set { } } public double M44 { get { return default(double); } set { } } public double OffsetX { get { return default(double); } set { } } public double OffsetY { get { return default(double); } set { } } public double OffsetZ { get { return default(double); } set { } } [global::System.Security.SecuritySafeCriticalAttribute] public override bool Equals(object o) { return default(bool); } public bool Equals(global::Windows.UI.Xaml.Media.Media3D.Matrix3D value) { return default(bool); } [global::System.Security.SecuritySafeCriticalAttribute] public override int GetHashCode() { return default(int); } public void Invert() { } public static bool operator ==(global::Windows.UI.Xaml.Media.Media3D.Matrix3D matrix1, global::Windows.UI.Xaml.Media.Media3D.Matrix3D matrix2) { return default(bool); } public static bool operator !=(global::Windows.UI.Xaml.Media.Media3D.Matrix3D matrix1, global::Windows.UI.Xaml.Media.Media3D.Matrix3D matrix2) { return default(bool); } public static global::Windows.UI.Xaml.Media.Media3D.Matrix3D operator *(global::Windows.UI.Xaml.Media.Media3D.Matrix3D matrix1, global::Windows.UI.Xaml.Media.Media3D.Matrix3D matrix2) { return default(global::Windows.UI.Xaml.Media.Media3D.Matrix3D); } [global::System.Security.SecuritySafeCriticalAttribute] string System.IFormattable.ToString(string format, global::System.IFormatProvider provider) { return default(string); } [global::System.Security.SecuritySafeCriticalAttribute] public override string ToString() { return default(string); } public string ToString(global::System.IFormatProvider provider) { return default(string); } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <peter@majorsilence.com> This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Xml; using System.Data; using System.Collections; namespace fyiReporting.Data { /// <summary> /// FileDirCommand allows specifying the command for the web log. /// </summary> public class FileDirCommand : IDbCommand { FileDirConnection _fdc; // connection we're running under string _cmd; // command to execute // parsed constituents of the command string _Directory; // Directory string _FilePattern; // SearchPattern when doing the file lookup string _DirectoryPattern; // SearchPattern when doing the directory lookup string _TrimEmpty="yes"; // Directory with no files will be omitted from result set DataParameterCollection _Parameters = new DataParameterCollection(); public FileDirCommand(FileDirConnection conn) { _fdc = conn; } internal string Directory { get { // Check to see if "Directory" or "@Directory" is a parameter IDbDataParameter dp= _Parameters["Directory"] as IDbDataParameter; if (dp == null) dp= _Parameters["@Directory"] as IDbDataParameter; // Then check to see if the Directory value is a parameter? if (dp == null) dp = _Parameters[_Directory] as IDbDataParameter; if (dp != null) return dp.Value != null? dp.Value.ToString(): _Directory; // don't pass null; pass existing value return _Directory == null? _fdc.Directory: _Directory; } set {_Directory = value;} } internal string FilePattern { get { // Check to see if "FilePattern" or "@FilePattern" is a parameter IDbDataParameter dp= _Parameters["FilePattern"] as IDbDataParameter; if (dp == null) dp= _Parameters["@FilePattern"] as IDbDataParameter; // Then check to see if the FilePattern value is a parameter? if (dp == null) dp = _Parameters[_FilePattern] as IDbDataParameter; if (dp != null) return dp.Value as string; return _FilePattern; } set {_FilePattern = value;} } internal string DirectoryPattern { get { // Check to see if "DirectoryPattern" or "@DirectoryPattern" is a parameter IDbDataParameter dp= _Parameters["DirectoryPattern"] as IDbDataParameter; if (dp == null) dp= _Parameters["@DirectoryPattern"] as IDbDataParameter; // Then check to see if the DirectoryPattern value is a parameter? if (dp == null) dp = _Parameters[_DirectoryPattern] as IDbDataParameter; if (dp != null) return dp.Value as string; return _DirectoryPattern; } set {_DirectoryPattern = value;} } internal bool TrimEmpty { get { // Check to see if "TrimEmpty" or "@TrimEmpty" is a parameter IDbDataParameter dp= _Parameters["TrimEmpty"] as IDbDataParameter; if (dp == null) dp= _Parameters["@TrimEmpty"] as IDbDataParameter; // Then check to see if the TrimEmpty value is a parameter? if (dp == null) dp = _Parameters[_TrimEmpty] as IDbDataParameter; if (dp != null) { string tf = dp.Value as string; if (tf == null) return false; tf = tf.ToLower(); return (tf == "true" || tf == "yes"); } return _TrimEmpty=="yes"? true: false; // the value must be a constant } set {_TrimEmpty = value? "yes": "no";} } #region IDbCommand Members public void Cancel() { throw new NotImplementedException("Cancel not implemented"); } public void Prepare() { return; // Prepare is a noop } public System.Data.CommandType CommandType { get { throw new NotImplementedException("CommandType not implemented"); } set { throw new NotImplementedException("CommandType not implemented"); } } public IDataReader ExecuteReader(System.Data.CommandBehavior behavior) { if (!(behavior == CommandBehavior.SingleResult || behavior == CommandBehavior.SchemaOnly)) throw new ArgumentException("ExecuteReader supports SingleResult and SchemaOnly only."); return new FileDirDataReader(behavior, _fdc, this); } IDataReader System.Data.IDbCommand.ExecuteReader() { return ExecuteReader(System.Data.CommandBehavior.SingleResult); } public object ExecuteScalar() { throw new NotImplementedException("ExecuteScalar not implemented"); } public int ExecuteNonQuery() { throw new NotImplementedException("ExecuteNonQuery not implemented"); } public int CommandTimeout { get { return 0; } set { throw new NotImplementedException("CommandTimeout not implemented"); } } public IDbDataParameter CreateParameter() { return new FileDirDataParameter(); } public IDbConnection Connection { get { return this._fdc; } set { throw new NotImplementedException("Setting Connection not implemented"); } } public System.Data.UpdateRowSource UpdatedRowSource { get { throw new NotImplementedException("UpdatedRowSource not implemented"); } set { throw new NotImplementedException("UpdatedRowSource not implemented"); } } public string CommandText { get { return this._cmd; } set { // Parse the command string for keyword value pairs separated by ';' _FilePattern = null; _DirectoryPattern = null; _Directory = null; string[] args = value.Split(';'); foreach(string arg in args) { string[] param = arg.Trim().Split('='); if (param == null || param.Length != 2) continue; string key = param[0].Trim().ToLower(); string val = param[1]; switch (key) { case "directory": _Directory = val; break; case "filepattern": _FilePattern = val; break; case "directorypattern": _DirectoryPattern = val; break; default: throw new ArgumentException(string.Format("{0} is an unknown parameter key", param[0])); } } // User must specify both the url and the RowsXPath if (_Directory == null && this._fdc.Directory == null) { if (_Directory == null) throw new ArgumentException("CommandText requires a 'Directory=' parameter."); } _cmd = value; } } public IDataParameterCollection Parameters { get { return _Parameters; } } public IDbTransaction Transaction { get { throw new NotImplementedException("Transaction not implemented"); } set { throw new NotImplementedException("Transaction not implemented"); } } #endregion #region IDisposable Members public void Dispose() { // nothing to dispose of } #endregion } }
// <copyright file="DenseVectorTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2016 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; using System; using System.Collections.Generic; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex { #if NOSYSNUMERICS using Complex = Numerics.Complex; #else using Complex = System.Numerics.Complex; #endif /// <summary> /// Dense vector tests. /// </summary> public class DenseVectorTests : VectorTests { /// <summary> /// Creates a new instance of the Vector class. /// </summary> /// <param name="size">The size of the <strong>Vector</strong> to construct.</param> /// <returns>The new <c>Vector</c>.</returns> protected override Vector<Complex> CreateVector(int size) { return new DenseVector(size); } /// <summary> /// Creates a new instance of the Vector class. /// </summary> /// <param name="data">The array to create this vector from.</param> /// <returns>The new <c>Vector</c>.</returns> protected override Vector<Complex> CreateVector(IList<Complex> data) { var vector = new DenseVector(data.Count); for (var index = 0; index < data.Count; index++) { vector[index] = data[index]; } return vector; } /// <summary> /// Can create a dense vector form array. /// </summary> [Test] public void CanCreateDenseVectorFromArray() { var data = new Complex[Data.Length]; Array.Copy(Data, data, Data.Length); var vector = new DenseVector(data); for (var i = 0; i < data.Length; i++) { Assert.AreEqual(data[i], vector[i]); } vector[0] = new Complex(10.0, 1); Assert.AreEqual(new Complex(10.0, 1), data[0]); } /// <summary> /// Can create a dense vector from another dense vector. /// </summary> [Test] public void CanCreateDenseVectorFromAnotherDenseVector() { var vector = new DenseVector(Data); var other = DenseVector.OfVector(vector); Assert.AreNotSame(vector, other); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(vector[i], other[i]); } } /// <summary> /// Can create a dense vector from another vector. /// </summary> [Test] public void CanCreateDenseVectorFromAnotherVector() { var vector = (Vector<Complex>) new DenseVector(Data); var other = DenseVector.OfVector(vector); Assert.AreNotSame(vector, other); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(vector[i], other[i]); } } /// <summary> /// Can create a dense vector from user defined vector. /// </summary> [Test] public void CanCreateDenseVectorFromUserDefinedVector() { var vector = new UserDefinedVector(Data); var other = DenseVector.OfVector(vector); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(vector[i], other[i]); } } /// <summary> /// Can create a dense vector with constant values. /// </summary> [Test] public void CanCreateDenseVectorWithConstantValues() { var vector = DenseVector.Create(5, 5); foreach (var t in vector) { Assert.AreEqual(t, new Complex(5.0, 0)); } } /// <summary> /// Can create a dense matrix. /// </summary> [Test] public void CanCreateDenseMatrix() { var vector = new DenseVector(3); var matrix = Matrix<Complex>.Build.SameAs(vector, 2, 3); Assert.IsInstanceOf<DenseMatrix>(matrix); Assert.AreEqual(2, matrix.RowCount); Assert.AreEqual(3, matrix.ColumnCount); } /// <summary> /// Can convert a dense vector to an array. /// </summary> [Test] public void CanConvertDenseVectorToArray() { var vector = new DenseVector(Data); var array = (Complex[]) vector; Assert.IsInstanceOf(typeof (Complex[]), array); CollectionAssert.AreEqual(vector, array); } /// <summary> /// Can convert an array to a dense vector. /// </summary> [Test] public void CanConvertArrayToDenseVector() { var array = new[] {new Complex(1, 1), new Complex(2, 1), new Complex(3, 1), new Complex(4, 1)}; var vector = (DenseVector) array; Assert.IsInstanceOf(typeof (DenseVector), vector); CollectionAssert.AreEqual(array, array); } /// <summary> /// Can call unary plus operator on a vector. /// </summary> [Test] public void CanCallUnaryPlusOperatorOnDenseVector() { var vector = new DenseVector(Data); var other = +vector; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(vector[i], other[i]); } } /// <summary> /// Can add two dense vectors using "+" operator. /// </summary> [Test] public void CanAddTwoDenseVectorsUsingOperator() { var vector = new DenseVector(Data); var other = new DenseVector(Data); var result = vector + other; CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified."); CollectionAssert.AreEqual(Data, other, "Making sure the original vector wasn't modified."); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]*2.0, result[i]); } } /// <summary> /// Can call unary negate operator on a dense vector. /// </summary> [Test] public void CanCallUnaryNegationOperatorOnDenseVector() { var vector = new DenseVector(Data); var other = -vector; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(-Data[i], other[i]); } } /// <summary> /// Can subtract two dense vectors using "-" operator. /// </summary> [Test] public void CanSubtractTwoDenseVectorsUsingOperator() { var vector = new DenseVector(Data); var other = new DenseVector(Data); var result = vector - other; CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified."); CollectionAssert.AreEqual(Data, other, "Making sure the original vector wasn't modified."); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Complex.Zero, result[i]); } } /// <summary> /// Can multiply a dense vector by a scalar using "*" operator. /// </summary> [Test] public void CanMultiplyDenseVectorByScalarUsingOperators() { var vector = new DenseVector(Data); vector = vector*new Complex(2.0, 1); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]*new Complex(2.0, 1), vector[i]); } vector = vector*1.0; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]*new Complex(2.0, 1), vector[i]); } vector = new DenseVector(Data); vector = new Complex(2.0, 1)*vector; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]*new Complex(2.0, 1), vector[i]); } vector = 1.0*vector; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]*new Complex(2.0, 1), vector[i]); } } /// <summary> /// Can divide a dense vector by a scalar using "/" operator. /// </summary> [Test] public void CanDivideDenseVectorByComplexUsingOperators() { var vector = new DenseVector(Data); vector = vector/new Complex(2.0, 1); for (var i = 0; i < Data.Length; i++) { AssertHelpers.AlmostEqualRelative(Data[i]/new Complex(2.0, 1), vector[i], 14); } vector = vector/1.0; for (var i = 0; i < Data.Length; i++) { AssertHelpers.AlmostEqualRelative(Data[i]/new Complex(2.0, 1), vector[i], 14); } } /// <summary> /// Can calculate an outer product for a dense vector. /// </summary> [Test] public void CanCalculateOuterProductForDenseVector() { var vector1 = CreateVector(Data); var vector2 = CreateVector(Data); var m = Vector<Complex>.OuterProduct(vector1, vector2); for (var i = 0; i < vector1.Count; i++) { for (var j = 0; j < vector2.Count; j++) { Assert.AreEqual(m[i, j], vector1[i]*vector2[j]); } } } } }
/* Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft 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 SCG = System.Collections.Generic; namespace C5 { #region char comparer and equality comparer class CharComparer : SCG.IComparer<char> { public int Compare(char item1, char item2) { return item1 > item2 ? 1 : item1 < item2 ? -1 : 0; } } /// <summary> /// An equality comparer for type char, also known as System.Char. /// </summary> public class CharEqualityComparer : SCG.IEqualityComparer<char> { static CharEqualityComparer cached = new CharEqualityComparer(); CharEqualityComparer() { } /// <summary> /// /// </summary> /// <value></value> public static CharEqualityComparer Default { get { return cached ?? (cached = new CharEqualityComparer()); } } /// <summary> /// Get the hash code of this char /// </summary> /// <param name="item">The char</param> /// <returns>The same</returns> public int GetHashCode(char item) { return item.GetHashCode(); } /// <summary> /// Check if two chars are equal /// </summary> /// <param name="item1">first char</param> /// <param name="item2">second char</param> /// <returns>True if equal</returns> public bool Equals(char item1, char item2) { return item1 == item2; } } #endregion #region sbyte comparer and equality comparer [Serializable] class SByteComparer : SCG.IComparer<sbyte> { public int Compare(sbyte item1, sbyte item2) { return item1 > item2 ? 1 : item1 < item2 ? -1 : 0; } } /// <summary> /// An equality comparer for type sbyte, also known as System.SByte. /// <para>This class is a singleton and the instance can be accessed /// via the static <see cref="P:C5.SByteEqualityComparer.Default"/> property</para> /// </summary> [Serializable] [CLSCompliant(false)] public class SByteEqualityComparer : SCG.IEqualityComparer<sbyte> { static SByteEqualityComparer cached; SByteEqualityComparer() { } /// <summary> /// /// </summary> /// <value></value> public static SByteEqualityComparer Default { get { return cached ?? (cached = new SByteEqualityComparer()); } } /// <summary> /// Get the hash code of this sbyte, that is, itself /// </summary> /// <param name="item">The sbyte</param> /// <returns>The same</returns> public int GetHashCode(sbyte item) { return item.GetHashCode(); } /// <summary> /// Determine whether two sbytes are equal /// </summary> /// <param name="item1">first sbyte</param> /// <param name="item2">second sbyte</param> /// <returns>True if equal</returns> public bool Equals(sbyte item1, sbyte item2) { return item1 == item2; } } #endregion #region byte comparer and equality comparer class ByteComparer : SCG.IComparer<byte> { public int Compare(byte item1, byte item2) { return item1 > item2 ? 1 : item1 < item2 ? -1 : 0; } } /// <summary> /// An equality comparer for type byte, also known as System.Byte. /// <para>This class is a singleton and the instance can be accessed /// via the <see cref="P:C5.ByteEqualityComparer.Default"/> property</para> /// </summary> public class ByteEqualityComparer : SCG.IEqualityComparer<byte> { static ByteEqualityComparer cached = new ByteEqualityComparer(); ByteEqualityComparer() { } /// <summary> /// /// </summary> /// <value></value> public static ByteEqualityComparer Default { get { return cached ?? (cached = new ByteEqualityComparer()); } } /// <summary> /// Get the hash code of this byte, i.e. itself /// </summary> /// <param name="item">The byte</param> /// <returns>The same</returns> public int GetHashCode(byte item) { return item.GetHashCode(); } /// <summary> /// Check if two bytes are equal /// </summary> /// <param name="item1">first byte</param> /// <param name="item2">second byte</param> /// <returns>True if equal</returns> public bool Equals(byte item1, byte item2) { return item1 == item2; } } #endregion #region short comparer and equality comparer [Serializable] class ShortComparer : SCG.IComparer<short> { public int Compare(short item1, short item2) { return item1 > item2 ? 1 : item1 < item2 ? -1 : 0; } } /// <summary> /// An equality comparer for type short, also known as System.Int16. /// <para>This class is a singleton and the instance can be accessed /// via the static <see cref="P:C5.ShortEqualityComparer.Default"/> property</para> /// </summary> [Serializable] public class ShortEqualityComparer : SCG.IEqualityComparer<short> { static ShortEqualityComparer cached; ShortEqualityComparer() { } /// <summary> /// /// </summary> /// <value></value> public static ShortEqualityComparer Default { get { return cached ?? (cached = new ShortEqualityComparer()); } } /// <summary> /// Get the hash code of this short, that is, itself /// </summary> /// <param name="item">The short</param> /// <returns>The same</returns> public int GetHashCode(short item) { return item.GetHashCode(); } /// <summary> /// Determine whether two shorts are equal /// </summary> /// <param name="item1">first short</param> /// <param name="item2">second short</param> /// <returns>True if equal</returns> public bool Equals(short item1, short item2) { return item1 == item2; } } #endregion #region ushort comparer and equality comparer [Serializable] class UShortComparer : SCG.IComparer<ushort> { public int Compare(ushort item1, ushort item2) { return item1 > item2 ? 1 : item1 < item2 ? -1 : 0; } } /// <summary> /// An equality comparer for type ushort, also known as System.UInt16. /// <para>This class is a singleton and the instance can be accessed /// via the static <see cref="P:C5.UShortEqualityComparer.Default"/> property</para> /// </summary> [Serializable] [CLSCompliant(false)] public class UShortEqualityComparer : SCG.IEqualityComparer<ushort> { static UShortEqualityComparer cached; UShortEqualityComparer() { } /// <summary> /// /// </summary> /// <value></value> public static UShortEqualityComparer Default { get { return cached ?? (cached = new UShortEqualityComparer()); } } /// <summary> /// Get the hash code of this ushort, that is, itself /// </summary> /// <param name="item">The ushort</param> /// <returns>The same</returns> public int GetHashCode(ushort item) { return item.GetHashCode(); } /// <summary> /// Determine whether two ushorts are equal /// </summary> /// <param name="item1">first ushort</param> /// <param name="item2">second ushort</param> /// <returns>True if equal</returns> public bool Equals(ushort item1, ushort item2) { return item1 == item2; } } #endregion #region int comparer and equality comparer [Serializable] class IntComparer : SCG.IComparer<int> { public int Compare(int item1, int item2) { return item1 > item2 ? 1 : item1 < item2 ? -1 : 0; } } /// <summary> /// An equality comparer for type int, also known as System.Int32. /// <para>This class is a singleton and the instance can be accessed /// via the static <see cref="P:C5.IntEqualityComparer.Default"/> property</para> /// </summary> [Serializable] public class IntEqualityComparer : SCG.IEqualityComparer<int> { static IntEqualityComparer cached; IntEqualityComparer() { } /// <summary> /// /// </summary> /// <value></value> public static IntEqualityComparer Default { get { return cached ?? (cached = new IntEqualityComparer()); } } /// <summary> /// Get the hash code of this integer, that is, itself /// </summary> /// <param name="item">The integer</param> /// <returns>The same</returns> public int GetHashCode(int item) { return item; } /// <summary> /// Determine whether two integers are equal /// </summary> /// <param name="item1">first integer</param> /// <param name="item2">second integer</param> /// <returns>True if equal</returns> public bool Equals(int item1, int item2) { return item1 == item2; } } #endregion #region uint comparer and equality comparer [Serializable] class UIntComparer : SCG.IComparer<uint> { public int Compare(uint item1, uint item2) { return item1 > item2 ? 1 : item1 < item2 ? -1 : 0; } } /// <summary> /// An equality comparer for type uint, also known as System.UInt32. /// <para>This class is a singleton and the instance can be accessed /// via the static <see cref="P:C5.UIntEqualityComparer.Default"/> property</para> /// </summary> [Serializable] [CLSCompliant(false)] public class UIntEqualityComparer : SCG.IEqualityComparer<uint> { static UIntEqualityComparer cached; UIntEqualityComparer() { } /// <summary> /// /// </summary> /// <value></value> public static UIntEqualityComparer Default { get { return cached ?? (cached = new UIntEqualityComparer()); } } /// <summary> /// Get the hash code of this unsigned integer /// </summary> /// <param name="item">The integer</param> /// <returns>The same bit pattern as a signed integer</returns> public int GetHashCode(uint item) { return item.GetHashCode(); } /// <summary> /// Determine whether two unsigned integers are equal /// </summary> /// <param name="item1">first unsigned integer</param> /// <param name="item2">second unsigned integer</param> /// <returns>True if equal</returns> public bool Equals(uint item1, uint item2) { return item1 == item2; } } #endregion #region long comparer and equality comparer [Serializable] class LongComparer : SCG.IComparer<long> { public int Compare(long item1, long item2) { return item1 > item2 ? 1 : item1 < item2 ? -1 : 0; } } /// <summary> /// An equality comparer for type long, also known as System.Int64. /// <para>This class is a singleton and the instance can be accessed /// via the static <see cref="P:C5.LongEqualityComparer.Default"/> property</para> /// </summary> [Serializable] public class LongEqualityComparer : SCG.IEqualityComparer<long> { static LongEqualityComparer cached; LongEqualityComparer() { } /// <summary> /// /// </summary> /// <value></value> public static LongEqualityComparer Default { get { return cached ?? (cached = new LongEqualityComparer()); } } /// <summary> /// Get the hash code of this long integer /// </summary> /// <param name="item">The long integer</param> /// <returns>The hash code</returns> public int GetHashCode(long item) { return item.GetHashCode(); } /// <summary> /// Determine whether two long integers are equal /// </summary> /// <param name="item1">first long integer</param> /// <param name="item2">second long integer</param> /// <returns>True if equal</returns> public bool Equals(long item1, long item2) { return item1 == item2; } } #endregion #region ulong comparer and equality comparer [Serializable] class ULongComparer : SCG.IComparer<ulong> { public int Compare(ulong item1, ulong item2) { return item1 > item2 ? 1 : item1 < item2 ? -1 : 0; } } /// <summary> /// An equality comparer for type uint, also known as System.UInt64. /// <para>This class is a singleton and the instance can be accessed /// via the static <see cref="P:C5.ULongEqualityComparer.Default"/> property</para> /// </summary> [Serializable] [CLSCompliant(false)] public class ULongEqualityComparer : SCG.IEqualityComparer<ulong> { static ULongEqualityComparer cached; ULongEqualityComparer() { } /// <summary> /// /// </summary> /// <value></value> public static ULongEqualityComparer Default { get { return cached ?? (cached = new ULongEqualityComparer()); } } /// <summary> /// Get the hash code of this unsigned long integer /// </summary> /// <param name="item">The unsigned long integer</param> /// <returns>The hash code</returns> public int GetHashCode(ulong item) { return item.GetHashCode(); } /// <summary> /// Determine whether two unsigned long integers are equal /// </summary> /// <param name="item1">first unsigned long integer</param> /// <param name="item2">second unsigned long integer</param> /// <returns>True if equal</returns> public bool Equals(ulong item1, ulong item2) { return item1 == item2; } } #endregion #region float comparer and equality comparer class FloatComparer : SCG.IComparer<float> { public int Compare(float item1, float item2) { return item1 > item2 ? 1 : item1 < item2 ? -1 : 0; } } /// <summary> /// An equality comparer for type float, also known as System.Single. /// <para>This class is a singleton and the instance can be accessed /// via the static <see cref="P:C5.FloatEqualityComparer.Default"/> property</para> /// </summary> public class FloatEqualityComparer : SCG.IEqualityComparer<float> { static FloatEqualityComparer cached; FloatEqualityComparer() { } /// <summary> /// /// </summary> /// <value></value> public static FloatEqualityComparer Default { get { return cached ?? (cached = new FloatEqualityComparer()); } } /// <summary> /// Get the hash code of this float /// </summary> /// <param name="item">The float</param> /// <returns>The same</returns> public int GetHashCode(float item) { return item.GetHashCode(); } /// <summary> /// Check if two floats are equal /// </summary> /// <param name="item1">first float</param> /// <param name="item2">second float</param> /// <returns>True if equal</returns> public bool Equals(float item1, float item2) { return item1 == item2; } } #endregion #region double comparer and equality comparer class DoubleComparer : SCG.IComparer<double> { public int Compare(double item1, double item2) { return item1 > item2 ? 1 : item1 < item2 ? -1 : 0; } } /// <summary> /// An equality comparer for type double, also known as System.Double. /// <para>This class is a singleton and the instance can be accessed /// via the static <see cref="P:C5.DoubleEqualityComparer.Default"/> property</para> /// </summary> public class DoubleEqualityComparer : SCG.IEqualityComparer<double> { static DoubleEqualityComparer cached; DoubleEqualityComparer() { } /// <summary> /// /// </summary> /// <value></value> public static DoubleEqualityComparer Default { get { return cached ?? (cached = new DoubleEqualityComparer()); } } /// <summary> /// Get the hash code of this double /// </summary> /// <param name="item">The double</param> /// <returns>The same</returns> public int GetHashCode(double item) { return item.GetHashCode(); } /// <summary> /// Check if two doubles are equal /// </summary> /// <param name="item1">first double</param> /// <param name="item2">second double</param> /// <returns>True if equal</returns> public bool Equals(double item1, double item2) { return item1 == item2; } } #endregion #region decimal comparer and equality comparer [Serializable] class DecimalComparer : SCG.IComparer<decimal> { public int Compare(decimal item1, decimal item2) { return item1 > item2 ? 1 : item1 < item2 ? -1 : 0; } } /// <summary> /// An equality comparer for type decimal, also known as System.Decimal. /// <para>This class is a singleton and the instance can be accessed /// via the static <see cref="P:C5.DecimalEqualityComparer.Default"/> property</para> /// </summary> [Serializable] public class DecimalEqualityComparer : SCG.IEqualityComparer<decimal> { static DecimalEqualityComparer cached; DecimalEqualityComparer() { } /// <summary> /// /// </summary> /// <value></value> public static DecimalEqualityComparer Default { get { return cached ?? (cached = new DecimalEqualityComparer()); } } /// <summary> /// Get the hash code of this decimal. /// </summary> /// <param name="item">The decimal</param> /// <returns>The hash code</returns> public int GetHashCode(decimal item) { return item.GetHashCode(); } /// <summary> /// Determine whether two decimals are equal /// </summary> /// <param name="item1">first decimal</param> /// <param name="item2">second decimal</param> /// <returns>True if equal</returns> public bool Equals(decimal item1, decimal item2) { return item1 == item2; } } #endregion }
using System.Net; using FluentAssertions; using JsonApiDotNetCore.Serialization.Objects; using Microsoft.EntityFrameworkCore; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.AtomicOperations.LocalIds; public sealed class AtomicLocalIdTests : IClassFixture<IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext>> { private readonly IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> _testContext; private readonly OperationsFakers _fakers = new(); public AtomicLocalIdTests(IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> testContext) { _testContext = testContext; testContext.UseController<OperationsController>(); } [Fact] public async Task Can_create_resource_with_ManyToOne_relationship_using_local_ID() { // Arrange RecordCompany newCompany = _fakers.RecordCompany.Generate(); string newTrackTitle = _fakers.MusicTrack.Generate().Title; const string companyLocalId = "company-1"; var requestBody = new { atomic__operations = new object[] { new { op = "add", data = new { type = "recordCompanies", lid = companyLocalId, attributes = new { name = newCompany.Name, countryOfResidence = newCompany.CountryOfResidence } } }, new { op = "add", data = new { type = "musicTracks", attributes = new { title = newTrackTitle }, relationships = new { ownedBy = new { data = new { type = "recordCompanies", lid = companyLocalId } } } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Results.ShouldHaveCount(2); responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("recordCompanies"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("name").With(value => value.Should().Be(newCompany.Name)); resource.Attributes.ShouldContainKey("countryOfResidence").With(value => value.Should().Be(newCompany.CountryOfResidence)); }); responseDocument.Results[1].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("musicTracks"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("title").With(value => value.Should().Be(newTrackTitle)); }); short newCompanyId = short.Parse(responseDocument.Results[0].Data.SingleValue!.Id.ShouldNotBeNull()); Guid newTrackId = Guid.Parse(responseDocument.Results[1].Data.SingleValue!.Id.ShouldNotBeNull()); await _testContext.RunOnDatabaseAsync(async dbContext => { MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.OwnedBy).FirstWithIdAsync(newTrackId); trackInDatabase.Title.Should().Be(newTrackTitle); trackInDatabase.OwnedBy.ShouldNotBeNull(); trackInDatabase.OwnedBy.Id.Should().Be(newCompanyId); trackInDatabase.OwnedBy.Name.Should().Be(newCompany.Name); trackInDatabase.OwnedBy.CountryOfResidence.Should().Be(newCompany.CountryOfResidence); }); } [Fact] public async Task Can_create_resource_with_OneToMany_relationship_using_local_ID() { // Arrange Performer newPerformer = _fakers.Performer.Generate(); string newTrackTitle = _fakers.MusicTrack.Generate().Title; const string performerLocalId = "performer-1"; var requestBody = new { atomic__operations = new object[] { new { op = "add", data = new { type = "performers", lid = performerLocalId, attributes = new { artistName = newPerformer.ArtistName, bornAt = newPerformer.BornAt } } }, new { op = "add", data = new { type = "musicTracks", attributes = new { title = newTrackTitle }, relationships = new { performers = new { data = new[] { new { type = "performers", lid = performerLocalId } } } } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Results.ShouldHaveCount(2); responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("performers"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("artistName").With(value => value.Should().Be(newPerformer.ArtistName)); resource.Attributes.ShouldContainKey("bornAt").With(value => value.Should().Be(newPerformer.BornAt)); }); responseDocument.Results[1].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("musicTracks"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("title").With(value => value.Should().Be(newTrackTitle)); }); int newPerformerId = int.Parse(responseDocument.Results[0].Data.SingleValue!.Id.ShouldNotBeNull()); Guid newTrackId = Guid.Parse(responseDocument.Results[1].Data.SingleValue!.Id.ShouldNotBeNull()); await _testContext.RunOnDatabaseAsync(async dbContext => { MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.Performers).FirstWithIdAsync(newTrackId); trackInDatabase.Title.Should().Be(newTrackTitle); trackInDatabase.Performers.ShouldHaveCount(1); trackInDatabase.Performers[0].Id.Should().Be(newPerformerId); trackInDatabase.Performers[0].ArtistName.Should().Be(newPerformer.ArtistName); trackInDatabase.Performers[0].BornAt.Should().Be(newPerformer.BornAt); }); } [Fact] public async Task Can_create_resource_with_ManyToMany_relationship_using_local_ID() { // Arrange string newTrackTitle = _fakers.MusicTrack.Generate().Title; string newPlaylistName = _fakers.Playlist.Generate().Name; const string trackLocalId = "track-1"; var requestBody = new { atomic__operations = new object[] { new { op = "add", data = new { type = "musicTracks", lid = trackLocalId, attributes = new { title = newTrackTitle } } }, new { op = "add", data = new { type = "playlists", attributes = new { name = newPlaylistName }, relationships = new { tracks = new { data = new[] { new { type = "musicTracks", lid = trackLocalId } } } } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Results.ShouldHaveCount(2); responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("musicTracks"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("title").With(value => value.Should().Be(newTrackTitle)); }); responseDocument.Results[1].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("playlists"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("name").With(value => value.Should().Be(newPlaylistName)); }); Guid newTrackId = Guid.Parse(responseDocument.Results[0].Data.SingleValue!.Id.ShouldNotBeNull()); long newPlaylistId = long.Parse(responseDocument.Results[1].Data.SingleValue!.Id.ShouldNotBeNull()); await _testContext.RunOnDatabaseAsync(async dbContext => { Playlist playlistInDatabase = await dbContext.Playlists.Include(playlist => playlist.Tracks).FirstWithIdAsync(newPlaylistId); playlistInDatabase.Name.Should().Be(newPlaylistName); playlistInDatabase.Tracks.ShouldHaveCount(1); playlistInDatabase.Tracks[0].Id.Should().Be(newTrackId); playlistInDatabase.Tracks[0].Title.Should().Be(newTrackTitle); }); } [Fact] public async Task Cannot_consume_local_ID_that_is_assigned_in_same_operation() { // Arrange const string companyLocalId = "company-1"; string newCompanyName = _fakers.RecordCompany.Generate().Name; var requestBody = new { atomic__operations = new object[] { new { op = "remove", @ref = new { type = "lyrics", id = Unknown.StringId.For<Lyric, long>() } }, new { op = "add", data = new { type = "recordCompanies", lid = companyLocalId, attributes = new { name = newCompanyName }, relationships = new { parent = new { data = new { type = "recordCompanies", lid = companyLocalId } } } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("Local ID cannot be both defined and used within the same operation."); error.Detail.Should().Be("Local ID 'company-1' cannot be both defined and used within the same operation."); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/atomic:operations[1]"); } [Fact] public async Task Cannot_reassign_local_ID() { // Arrange string newPlaylistName = _fakers.Playlist.Generate().Name; const string playlistLocalId = "playlist-1"; var requestBody = new { atomic__operations = new object[] { new { op = "remove", @ref = new { type = "lyrics", id = Unknown.StringId.For<Lyric, long>() } }, new { op = "add", data = new { type = "playlists", lid = playlistLocalId, attributes = new { name = newPlaylistName } } }, new { op = "add", data = new { type = "playlists", lid = playlistLocalId, attributes = new { name = newPlaylistName } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("Another local ID with the same name is already defined at this point."); error.Detail.Should().Be("Another local ID with name 'playlist-1' is already defined at this point."); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/atomic:operations[2]"); } [Fact] public async Task Can_update_resource_using_local_ID() { // Arrange string newTrackTitle = _fakers.MusicTrack.Generate().Title; string newTrackGenre = _fakers.MusicTrack.Generate().Genre!; const string trackLocalId = "track-1"; var requestBody = new { atomic__operations = new object[] { new { op = "add", data = new { type = "musicTracks", lid = trackLocalId, attributes = new { title = newTrackTitle } } }, new { op = "update", data = new { type = "musicTracks", lid = trackLocalId, attributes = new { genre = newTrackGenre } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Results.ShouldHaveCount(2); responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("musicTracks"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("title").With(value => value.Should().Be(newTrackTitle)); resource.Attributes.ShouldContainKey("genre").With(value => value.Should().BeNull()); }); responseDocument.Results[1].Data.Value.Should().BeNull(); Guid newTrackId = Guid.Parse(responseDocument.Results[0].Data.SingleValue!.Id.ShouldNotBeNull()); await _testContext.RunOnDatabaseAsync(async dbContext => { MusicTrack trackInDatabase = await dbContext.MusicTracks.FirstWithIdAsync(newTrackId); trackInDatabase.Title.Should().Be(newTrackTitle); trackInDatabase.Genre.Should().Be(newTrackGenre); }); } [Fact] public async Task Can_update_resource_with_relationships_using_local_ID() { // Arrange string newTrackTitle = _fakers.MusicTrack.Generate().Title; string newArtistName = _fakers.Performer.Generate().ArtistName!; string newCompanyName = _fakers.RecordCompany.Generate().Name; const string trackLocalId = "track-1"; const string performerLocalId = "performer-1"; const string companyLocalId = "company-1"; var requestBody = new { atomic__operations = new object[] { new { op = "add", data = new { type = "musicTracks", lid = trackLocalId, attributes = new { title = newTrackTitle } } }, new { op = "add", data = new { type = "performers", lid = performerLocalId, attributes = new { artistName = newArtistName } } }, new { op = "add", data = new { type = "recordCompanies", lid = companyLocalId, attributes = new { name = newCompanyName } } }, new { op = "update", data = new { type = "musicTracks", lid = trackLocalId, relationships = new { ownedBy = new { data = new { type = "recordCompanies", lid = companyLocalId } }, performers = new { data = new[] { new { type = "performers", lid = performerLocalId } } } } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Results.ShouldHaveCount(4); responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("musicTracks"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("title").With(value => value.Should().Be(newTrackTitle)); }); responseDocument.Results[1].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("performers"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("artistName").With(value => value.Should().Be(newArtistName)); }); responseDocument.Results[2].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("recordCompanies"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("name").With(value => value.Should().Be(newCompanyName)); }); responseDocument.Results[3].Data.Value.Should().BeNull(); Guid newTrackId = Guid.Parse(responseDocument.Results[0].Data.SingleValue!.Id.ShouldNotBeNull()); int newPerformerId = int.Parse(responseDocument.Results[1].Data.SingleValue!.Id.ShouldNotBeNull()); short newCompanyId = short.Parse(responseDocument.Results[2].Data.SingleValue!.Id.ShouldNotBeNull()); await _testContext.RunOnDatabaseAsync(async dbContext => { // @formatter:wrap_chained_method_calls chop_always // @formatter:keep_existing_linebreaks true MusicTrack trackInDatabase = await dbContext.MusicTracks .Include(musicTrack => musicTrack.OwnedBy) .Include(musicTrack => musicTrack.Performers) .FirstWithIdAsync(newTrackId); // @formatter:keep_existing_linebreaks restore // @formatter:wrap_chained_method_calls restore trackInDatabase.Title.Should().Be(newTrackTitle); trackInDatabase.OwnedBy.ShouldNotBeNull(); trackInDatabase.OwnedBy.Id.Should().Be(newCompanyId); trackInDatabase.Performers.ShouldHaveCount(1); trackInDatabase.Performers[0].Id.Should().Be(newPerformerId); trackInDatabase.Performers[0].ArtistName.Should().Be(newArtistName); }); } [Fact] public async Task Can_create_ManyToOne_relationship_using_local_ID() { // Arrange string newTrackTitle = _fakers.MusicTrack.Generate().Title; string newCompanyName = _fakers.RecordCompany.Generate().Name; const string trackLocalId = "track-1"; const string companyLocalId = "company-1"; var requestBody = new { atomic__operations = new object[] { new { op = "add", data = new { type = "musicTracks", lid = trackLocalId, attributes = new { title = newTrackTitle } } }, new { op = "add", data = new { type = "recordCompanies", lid = companyLocalId, attributes = new { name = newCompanyName } } }, new { op = "update", @ref = new { type = "musicTracks", lid = trackLocalId, relationship = "ownedBy" }, data = new { type = "recordCompanies", lid = companyLocalId } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Results.ShouldHaveCount(3); responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("musicTracks"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("title").With(value => value.Should().Be(newTrackTitle)); }); responseDocument.Results[1].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("recordCompanies"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("name").With(value => value.Should().Be(newCompanyName)); }); responseDocument.Results[2].Data.Value.Should().BeNull(); Guid newTrackId = Guid.Parse(responseDocument.Results[0].Data.SingleValue!.Id.ShouldNotBeNull()); short newCompanyId = short.Parse(responseDocument.Results[1].Data.SingleValue!.Id.ShouldNotBeNull()); await _testContext.RunOnDatabaseAsync(async dbContext => { MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.OwnedBy).FirstWithIdAsync(newTrackId); trackInDatabase.Title.Should().Be(newTrackTitle); trackInDatabase.OwnedBy.ShouldNotBeNull(); trackInDatabase.OwnedBy.Id.Should().Be(newCompanyId); trackInDatabase.OwnedBy.Name.Should().Be(newCompanyName); }); } [Fact] public async Task Can_create_OneToMany_relationship_using_local_ID() { // Arrange string newTrackTitle = _fakers.MusicTrack.Generate().Title; string newArtistName = _fakers.Performer.Generate().ArtistName!; const string trackLocalId = "track-1"; const string performerLocalId = "performer-1"; var requestBody = new { atomic__operations = new object[] { new { op = "add", data = new { type = "musicTracks", lid = trackLocalId, attributes = new { title = newTrackTitle } } }, new { op = "add", data = new { type = "performers", lid = performerLocalId, attributes = new { artistName = newArtistName } } }, new { op = "update", @ref = new { type = "musicTracks", lid = trackLocalId, relationship = "performers" }, data = new[] { new { type = "performers", lid = performerLocalId } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Results.ShouldHaveCount(3); responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("musicTracks"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("title").With(value => value.Should().Be(newTrackTitle)); }); responseDocument.Results[1].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("performers"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("artistName").With(value => value.Should().Be(newArtistName)); }); responseDocument.Results[2].Data.Value.Should().BeNull(); Guid newTrackId = Guid.Parse(responseDocument.Results[0].Data.SingleValue!.Id.ShouldNotBeNull()); int newPerformerId = int.Parse(responseDocument.Results[1].Data.SingleValue!.Id.ShouldNotBeNull()); await _testContext.RunOnDatabaseAsync(async dbContext => { MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.Performers).FirstWithIdAsync(newTrackId); trackInDatabase.Title.Should().Be(newTrackTitle); trackInDatabase.Performers.ShouldHaveCount(1); trackInDatabase.Performers[0].Id.Should().Be(newPerformerId); trackInDatabase.Performers[0].ArtistName.Should().Be(newArtistName); }); } [Fact] public async Task Can_create_ManyToMany_relationship_using_local_ID() { // Arrange string newPlaylistName = _fakers.Playlist.Generate().Name; string newTrackTitle = _fakers.MusicTrack.Generate().Title; const string playlistLocalId = "playlist-1"; const string trackLocalId = "track-1"; var requestBody = new { atomic__operations = new object[] { new { op = "add", data = new { type = "playlists", lid = playlistLocalId, attributes = new { name = newPlaylistName } } }, new { op = "add", data = new { type = "musicTracks", lid = trackLocalId, attributes = new { title = newTrackTitle } } }, new { op = "update", @ref = new { type = "playlists", lid = playlistLocalId, relationship = "tracks" }, data = new[] { new { type = "musicTracks", lid = trackLocalId } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Results.ShouldHaveCount(3); responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("playlists"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("name").With(value => value.Should().Be(newPlaylistName)); }); responseDocument.Results[1].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("musicTracks"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("title").With(value => value.Should().Be(newTrackTitle)); }); responseDocument.Results[2].Data.Value.Should().BeNull(); long newPlaylistId = long.Parse(responseDocument.Results[0].Data.SingleValue!.Id.ShouldNotBeNull()); Guid newTrackId = Guid.Parse(responseDocument.Results[1].Data.SingleValue!.Id.ShouldNotBeNull()); await _testContext.RunOnDatabaseAsync(async dbContext => { Playlist playlistInDatabase = await dbContext.Playlists.Include(playlist => playlist.Tracks).FirstWithIdAsync(newPlaylistId); playlistInDatabase.Name.Should().Be(newPlaylistName); playlistInDatabase.Tracks.ShouldHaveCount(1); playlistInDatabase.Tracks[0].Id.Should().Be(newTrackId); playlistInDatabase.Tracks[0].Title.Should().Be(newTrackTitle); }); } [Fact] public async Task Can_replace_OneToMany_relationship_using_local_ID() { // Arrange Performer existingPerformer = _fakers.Performer.Generate(); string newTrackTitle = _fakers.MusicTrack.Generate().Title; string newArtistName = _fakers.Performer.Generate().ArtistName!; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Performers.Add(existingPerformer); await dbContext.SaveChangesAsync(); }); const string trackLocalId = "track-1"; const string performerLocalId = "performer-1"; var requestBody = new { atomic__operations = new object[] { new { op = "add", data = new { type = "musicTracks", lid = trackLocalId, attributes = new { title = newTrackTitle }, relationships = new { performers = new { data = new[] { new { type = "performers", id = existingPerformer.StringId } } } } } }, new { op = "add", data = new { type = "performers", lid = performerLocalId, attributes = new { artistName = newArtistName } } }, new { op = "update", @ref = new { type = "musicTracks", lid = trackLocalId, relationship = "performers" }, data = new[] { new { type = "performers", lid = performerLocalId } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Results.ShouldHaveCount(3); responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("musicTracks"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("title").With(value => value.Should().Be(newTrackTitle)); }); responseDocument.Results[1].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("performers"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("artistName").With(value => value.Should().Be(newArtistName)); }); responseDocument.Results[2].Data.Value.Should().BeNull(); Guid newTrackId = Guid.Parse(responseDocument.Results[0].Data.SingleValue!.Id.ShouldNotBeNull()); int newPerformerId = int.Parse(responseDocument.Results[1].Data.SingleValue!.Id.ShouldNotBeNull()); await _testContext.RunOnDatabaseAsync(async dbContext => { MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.Performers).FirstWithIdAsync(newTrackId); trackInDatabase.Title.Should().Be(newTrackTitle); trackInDatabase.Performers.ShouldHaveCount(1); trackInDatabase.Performers[0].Id.Should().Be(newPerformerId); trackInDatabase.Performers[0].ArtistName.Should().Be(newArtistName); }); } [Fact] public async Task Can_replace_ManyToMany_relationship_using_local_ID() { // Arrange MusicTrack existingTrack = _fakers.MusicTrack.Generate(); string newPlaylistName = _fakers.Playlist.Generate().Name; string newTrackTitle = _fakers.MusicTrack.Generate().Title; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.MusicTracks.Add(existingTrack); await dbContext.SaveChangesAsync(); }); const string playlistLocalId = "playlist-1"; const string trackLocalId = "track-1"; var requestBody = new { atomic__operations = new object[] { new { op = "add", data = new { type = "playlists", lid = playlistLocalId, attributes = new { name = newPlaylistName }, relationships = new { tracks = new { data = new[] { new { type = "musicTracks", id = existingTrack.StringId } } } } } }, new { op = "add", data = new { type = "musicTracks", lid = trackLocalId, attributes = new { title = newTrackTitle } } }, new { op = "update", @ref = new { type = "playlists", lid = playlistLocalId, relationship = "tracks" }, data = new[] { new { type = "musicTracks", lid = trackLocalId } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Results.ShouldHaveCount(3); responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("playlists"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("name").With(value => value.Should().Be(newPlaylistName)); }); responseDocument.Results[1].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("musicTracks"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("title").With(value => value.Should().Be(newTrackTitle)); }); responseDocument.Results[2].Data.Value.Should().BeNull(); long newPlaylistId = long.Parse(responseDocument.Results[0].Data.SingleValue!.Id.ShouldNotBeNull()); Guid newTrackId = Guid.Parse(responseDocument.Results[1].Data.SingleValue!.Id.ShouldNotBeNull()); await _testContext.RunOnDatabaseAsync(async dbContext => { Playlist playlistInDatabase = await dbContext.Playlists.Include(playlist => playlist.Tracks).FirstWithIdAsync(newPlaylistId); playlistInDatabase.Name.Should().Be(newPlaylistName); playlistInDatabase.Tracks.ShouldHaveCount(1); playlistInDatabase.Tracks[0].Id.Should().Be(newTrackId); playlistInDatabase.Tracks[0].Title.Should().Be(newTrackTitle); }); } [Fact] public async Task Can_add_to_OneToMany_relationship_using_local_ID() { // Arrange Performer existingPerformer = _fakers.Performer.Generate(); string newTrackTitle = _fakers.MusicTrack.Generate().Title; string newArtistName = _fakers.Performer.Generate().ArtistName!; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Performers.Add(existingPerformer); await dbContext.SaveChangesAsync(); }); const string trackLocalId = "track-1"; const string performerLocalId = "performer-1"; var requestBody = new { atomic__operations = new object[] { new { op = "add", data = new { type = "musicTracks", lid = trackLocalId, attributes = new { title = newTrackTitle }, relationships = new { performers = new { data = new[] { new { type = "performers", id = existingPerformer.StringId } } } } } }, new { op = "add", data = new { type = "performers", lid = performerLocalId, attributes = new { artistName = newArtistName } } }, new { op = "add", @ref = new { type = "musicTracks", lid = trackLocalId, relationship = "performers" }, data = new[] { new { type = "performers", lid = performerLocalId } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Results.ShouldHaveCount(3); responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("musicTracks"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("title").With(value => value.Should().Be(newTrackTitle)); }); responseDocument.Results[1].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("performers"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("artistName").With(value => value.Should().Be(newArtistName)); }); responseDocument.Results[2].Data.Value.Should().BeNull(); Guid newTrackId = Guid.Parse(responseDocument.Results[0].Data.SingleValue!.Id.ShouldNotBeNull()); int newPerformerId = int.Parse(responseDocument.Results[1].Data.SingleValue!.Id.ShouldNotBeNull()); await _testContext.RunOnDatabaseAsync(async dbContext => { MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.Performers).FirstWithIdAsync(newTrackId); trackInDatabase.Title.Should().Be(newTrackTitle); trackInDatabase.Performers.ShouldHaveCount(2); trackInDatabase.Performers[0].Id.Should().Be(existingPerformer.Id); trackInDatabase.Performers[0].ArtistName.Should().Be(existingPerformer.ArtistName); trackInDatabase.Performers[1].Id.Should().Be(newPerformerId); trackInDatabase.Performers[1].ArtistName.Should().Be(newArtistName); }); } [Fact] public async Task Can_add_to_ManyToMany_relationship_using_local_ID() { // Arrange List<MusicTrack> existingTracks = _fakers.MusicTrack.Generate(2); string newPlaylistName = _fakers.Playlist.Generate().Name; string newTrackTitle = _fakers.MusicTrack.Generate().Title; const string playlistLocalId = "playlist-1"; const string trackLocalId = "track-1"; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.MusicTracks.AddRange(existingTracks); await dbContext.SaveChangesAsync(); }); var requestBody = new { atomic__operations = new object[] { new { op = "add", data = new { type = "playlists", lid = playlistLocalId, attributes = new { name = newPlaylistName }, relationships = new { tracks = new { data = new[] { new { type = "musicTracks", id = existingTracks[0].StringId } } } } } }, new { op = "add", data = new { type = "musicTracks", lid = trackLocalId, attributes = new { title = newTrackTitle } } }, new { op = "add", @ref = new { type = "playlists", lid = playlistLocalId, relationship = "tracks" }, data = new[] { new { type = "musicTracks", lid = trackLocalId } } }, new { op = "add", @ref = new { type = "playlists", lid = playlistLocalId, relationship = "tracks" }, data = new[] { new { type = "musicTracks", id = existingTracks[1].StringId } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Results.ShouldHaveCount(4); responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("playlists"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("name").With(value => value.Should().Be(newPlaylistName)); }); responseDocument.Results[1].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("musicTracks"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("title").With(value => value.Should().Be(newTrackTitle)); }); responseDocument.Results[2].Data.Value.Should().BeNull(); responseDocument.Results[3].Data.Value.Should().BeNull(); long newPlaylistId = long.Parse(responseDocument.Results[0].Data.SingleValue!.Id.ShouldNotBeNull()); Guid newTrackId = Guid.Parse(responseDocument.Results[1].Data.SingleValue!.Id.ShouldNotBeNull()); await _testContext.RunOnDatabaseAsync(async dbContext => { Playlist playlistInDatabase = await dbContext.Playlists.Include(playlist => playlist.Tracks).FirstWithIdAsync(newPlaylistId); playlistInDatabase.Name.Should().Be(newPlaylistName); playlistInDatabase.Tracks.ShouldHaveCount(3); playlistInDatabase.Tracks.Should().ContainSingle(musicTrack => musicTrack.Id == existingTracks[0].Id); playlistInDatabase.Tracks.Should().ContainSingle(musicTrack => musicTrack.Id == existingTracks[1].Id); playlistInDatabase.Tracks.Should().ContainSingle(musicTrack => musicTrack.Id == newTrackId); }); } [Fact] public async Task Can_remove_from_OneToMany_relationship_using_local_ID() { // Arrange Performer existingPerformer = _fakers.Performer.Generate(); string newTrackTitle = _fakers.MusicTrack.Generate().Title; string newArtistName1 = _fakers.Performer.Generate().ArtistName!; string newArtistName2 = _fakers.Performer.Generate().ArtistName!; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Performers.Add(existingPerformer); await dbContext.SaveChangesAsync(); }); const string trackLocalId = "track-1"; const string performerLocalId1 = "performer-1"; const string performerLocalId2 = "performer-2"; var requestBody = new { atomic__operations = new object[] { new { op = "add", data = new { type = "performers", lid = performerLocalId1, attributes = new { artistName = newArtistName1 } } }, new { op = "add", data = new { type = "performers", lid = performerLocalId2, attributes = new { artistName = newArtistName2 } } }, new { op = "add", data = new { type = "musicTracks", lid = trackLocalId, attributes = new { title = newTrackTitle }, relationships = new { performers = new { data = new object[] { new { type = "performers", id = existingPerformer.StringId }, new { type = "performers", lid = performerLocalId1 }, new { type = "performers", lid = performerLocalId2 } } } } } }, new { op = "remove", @ref = new { type = "musicTracks", lid = trackLocalId, relationship = "performers" }, data = new[] { new { type = "performers", lid = performerLocalId1 }, new { type = "performers", lid = performerLocalId2 } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Results.ShouldHaveCount(4); responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("performers"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("artistName").With(value => value.Should().Be(newArtistName1)); }); responseDocument.Results[1].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("performers"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("artistName").With(value => value.Should().Be(newArtistName2)); }); responseDocument.Results[2].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("musicTracks"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("title").With(value => value.Should().Be(newTrackTitle)); }); responseDocument.Results[3].Data.Value.Should().BeNull(); Guid newTrackId = Guid.Parse(responseDocument.Results[2].Data.SingleValue!.Id.ShouldNotBeNull()); await _testContext.RunOnDatabaseAsync(async dbContext => { MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.Performers).FirstWithIdAsync(newTrackId); trackInDatabase.Title.Should().Be(newTrackTitle); trackInDatabase.Performers.ShouldHaveCount(1); trackInDatabase.Performers[0].Id.Should().Be(existingPerformer.Id); trackInDatabase.Performers[0].ArtistName.Should().Be(existingPerformer.ArtistName); }); } [Fact] public async Task Can_remove_from_ManyToMany_relationship_using_local_ID() { // Arrange Playlist existingPlaylist = _fakers.Playlist.Generate(); existingPlaylist.Tracks = _fakers.MusicTrack.Generate(2); string newTrackTitle = _fakers.MusicTrack.Generate().Title; const string trackLocalId = "track-1"; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Playlists.Add(existingPlaylist); await dbContext.SaveChangesAsync(); }); var requestBody = new { atomic__operations = new object[] { new { op = "add", data = new { type = "musicTracks", lid = trackLocalId, attributes = new { title = newTrackTitle } } }, new { op = "add", @ref = new { type = "playlists", id = existingPlaylist.StringId, relationship = "tracks" }, data = new[] { new { type = "musicTracks", lid = trackLocalId } } }, new { op = "remove", @ref = new { type = "playlists", id = existingPlaylist.StringId, relationship = "tracks" }, data = new[] { new { type = "musicTracks", id = existingPlaylist.Tracks[1].StringId } } }, new { op = "remove", @ref = new { type = "playlists", id = existingPlaylist.StringId, relationship = "tracks" }, data = new[] { new { type = "musicTracks", lid = trackLocalId } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Results.ShouldHaveCount(4); responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("musicTracks"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("title").With(value => value.Should().Be(newTrackTitle)); }); responseDocument.Results[1].Data.Value.Should().BeNull(); responseDocument.Results[2].Data.Value.Should().BeNull(); responseDocument.Results[3].Data.Value.Should().BeNull(); await _testContext.RunOnDatabaseAsync(async dbContext => { Playlist playlistInDatabase = await dbContext.Playlists.Include(playlist => playlist.Tracks).FirstWithIdAsync(existingPlaylist.Id); playlistInDatabase.Tracks.ShouldHaveCount(1); playlistInDatabase.Tracks[0].Id.Should().Be(existingPlaylist.Tracks[0].Id); }); } [Fact] public async Task Can_delete_resource_using_local_ID() { // Arrange string newTrackTitle = _fakers.MusicTrack.Generate().Title; const string trackLocalId = "track-1"; var requestBody = new { atomic__operations = new object[] { new { op = "add", data = new { type = "musicTracks", lid = trackLocalId, attributes = new { title = newTrackTitle } } }, new { op = "remove", @ref = new { type = "musicTracks", lid = trackLocalId } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Results.ShouldHaveCount(2); responseDocument.Results[0].Data.SingleValue.ShouldNotBeNull().With(resource => { resource.Type.Should().Be("musicTracks"); resource.Lid.Should().BeNull(); resource.Attributes.ShouldContainKey("title").With(value => value.Should().Be(newTrackTitle)); }); responseDocument.Results[1].Data.Value.Should().BeNull(); Guid newTrackId = Guid.Parse(responseDocument.Results[0].Data.SingleValue!.Id.ShouldNotBeNull()); await _testContext.RunOnDatabaseAsync(async dbContext => { MusicTrack? trackInDatabase = await dbContext.MusicTracks.FirstWithIdOrDefaultAsync(newTrackId); trackInDatabase.Should().BeNull(); }); } [Fact] public async Task Cannot_consume_unassigned_local_ID_in_ref() { // Arrange var requestBody = new { atomic__operations = new object[] { new { op = "remove", @ref = new { type = "lyrics", id = Unknown.StringId.For<Lyric, long>() } }, new { op = "remove", @ref = new { type = "musicTracks", lid = Unknown.LocalId } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("Server-generated value for local ID is not available at this point."); error.Detail.Should().Be($"Server-generated value for local ID '{Unknown.LocalId}' is not available at this point."); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/atomic:operations[1]"); } [Fact] public async Task Cannot_consume_unassigned_local_ID_in_data_element() { // Arrange var requestBody = new { atomic__operations = new object[] { new { op = "remove", @ref = new { type = "lyrics", id = Unknown.StringId.For<Lyric, long>() } }, new { op = "update", data = new { type = "musicTracks", lid = Unknown.LocalId, attributes = new { } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("Server-generated value for local ID is not available at this point."); error.Detail.Should().Be($"Server-generated value for local ID '{Unknown.LocalId}' is not available at this point."); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/atomic:operations[1]"); } [Fact] public async Task Cannot_consume_unassigned_local_ID_in_data_array() { // Arrange MusicTrack existingTrack = _fakers.MusicTrack.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.MusicTracks.Add(existingTrack); await dbContext.SaveChangesAsync(); }); var requestBody = new { atomic__operations = new object[] { new { op = "remove", @ref = new { type = "lyrics", id = Unknown.StringId.For<Lyric, long>() } }, new { op = "add", @ref = new { type = "musicTracks", id = existingTrack.StringId, relationship = "performers" }, data = new[] { new { type = "performers", lid = Unknown.LocalId } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("Server-generated value for local ID is not available at this point."); error.Detail.Should().Be($"Server-generated value for local ID '{Unknown.LocalId}' is not available at this point."); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/atomic:operations[1]"); } [Fact] public async Task Cannot_consume_unassigned_local_ID_in_relationship_data_element() { // Arrange string newTrackTitle = _fakers.MusicTrack.Generate().Title; var requestBody = new { atomic__operations = new object[] { new { op = "remove", @ref = new { type = "lyrics", id = Unknown.StringId.For<Lyric, long>() } }, new { op = "add", data = new { type = "musicTracks", attributes = new { title = newTrackTitle }, relationships = new { ownedBy = new { data = new { type = "recordCompanies", lid = Unknown.LocalId } } } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("Server-generated value for local ID is not available at this point."); error.Detail.Should().Be($"Server-generated value for local ID '{Unknown.LocalId}' is not available at this point."); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/atomic:operations[1]"); } [Fact] public async Task Cannot_consume_unassigned_local_ID_in_relationship_data_array() { // Arrange string newPlaylistName = _fakers.Playlist.Generate().Name; var requestBody = new { atomic__operations = new object[] { new { op = "remove", @ref = new { type = "lyrics", id = Unknown.StringId.For<Lyric, long>() } }, new { op = "add", data = new { type = "playlists", attributes = new { name = newPlaylistName }, relationships = new { tracks = new { data = new[] { new { type = "musicTracks", lid = Unknown.LocalId } } } } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("Server-generated value for local ID is not available at this point."); error.Detail.Should().Be($"Server-generated value for local ID '{Unknown.LocalId}' is not available at this point."); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/atomic:operations[1]"); } [Fact] public async Task Cannot_consume_local_ID_of_different_type_in_same_operation() { // Arrange const string trackLocalId = "track-1"; string newTrackTitle = _fakers.MusicTrack.Generate().Title; var requestBody = new { atomic__operations = new object[] { new { op = "remove", @ref = new { type = "lyrics", id = Unknown.StringId.For<Lyric, long>() } }, new { op = "add", data = new { type = "musicTracks", lid = trackLocalId, attributes = new { title = newTrackTitle }, relationships = new { ownedBy = new { data = new { type = "recordCompanies", lid = trackLocalId } } } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("Incompatible type in Local ID usage."); error.Detail.Should().Be("Local ID 'track-1' belongs to resource type 'musicTracks' instead of 'recordCompanies'."); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/atomic:operations[1]"); } [Fact] public async Task Cannot_consume_local_ID_of_different_type_in_ref() { // Arrange const string companyLocalId = "company-1"; string newCompanyName = _fakers.RecordCompany.Generate().Name; var requestBody = new { atomic__operations = new object[] { new { op = "remove", @ref = new { type = "lyrics", id = Unknown.StringId.For<Lyric, long>() } }, new { op = "add", data = new { type = "recordCompanies", lid = companyLocalId, attributes = new { name = newCompanyName } } }, new { op = "remove", @ref = new { type = "musicTracks", lid = companyLocalId } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("Incompatible type in Local ID usage."); error.Detail.Should().Be("Local ID 'company-1' belongs to resource type 'recordCompanies' instead of 'musicTracks'."); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/atomic:operations[2]"); } [Fact] public async Task Cannot_consume_local_ID_of_different_type_in_data_element() { // Arrange const string performerLocalId = "performer-1"; var requestBody = new { atomic__operations = new object[] { new { op = "remove", @ref = new { type = "lyrics", id = Unknown.StringId.For<Lyric, long>() } }, new { op = "add", data = new { type = "performers", lid = performerLocalId } }, new { op = "update", data = new { type = "playlists", lid = performerLocalId, attributes = new { } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("Incompatible type in Local ID usage."); error.Detail.Should().Be("Local ID 'performer-1' belongs to resource type 'performers' instead of 'playlists'."); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/atomic:operations[2]"); } [Fact] public async Task Cannot_consume_local_ID_of_different_type_in_data_array() { // Arrange MusicTrack existingTrack = _fakers.MusicTrack.Generate(); const string companyLocalId = "company-1"; string newCompanyName = _fakers.RecordCompany.Generate().Name; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.MusicTracks.Add(existingTrack); await dbContext.SaveChangesAsync(); }); var requestBody = new { atomic__operations = new object[] { new { op = "remove", @ref = new { type = "lyrics", id = Unknown.StringId.For<Lyric, long>() } }, new { op = "add", data = new { type = "recordCompanies", lid = companyLocalId, attributes = new { name = newCompanyName } } }, new { op = "add", @ref = new { type = "musicTracks", id = existingTrack.StringId, relationship = "performers" }, data = new[] { new { type = "performers", lid = companyLocalId } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("Incompatible type in Local ID usage."); error.Detail.Should().Be("Local ID 'company-1' belongs to resource type 'recordCompanies' instead of 'performers'."); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/atomic:operations[2]"); } [Fact] public async Task Cannot_consume_local_ID_of_different_type_in_relationship_data_element() { // Arrange string newPlaylistName = _fakers.Playlist.Generate().Name; string newTrackTitle = _fakers.MusicTrack.Generate().Title; const string playlistLocalId = "playlist-1"; var requestBody = new { atomic__operations = new object[] { new { op = "remove", @ref = new { type = "lyrics", id = Unknown.StringId.For<Lyric, long>() } }, new { op = "add", data = new { type = "playlists", lid = playlistLocalId, attributes = new { name = newPlaylistName } } }, new { op = "add", data = new { type = "musicTracks", attributes = new { title = newTrackTitle }, relationships = new { ownedBy = new { data = new { type = "recordCompanies", lid = playlistLocalId } } } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("Incompatible type in Local ID usage."); error.Detail.Should().Be("Local ID 'playlist-1' belongs to resource type 'playlists' instead of 'recordCompanies'."); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/atomic:operations[2]"); } [Fact] public async Task Cannot_consume_local_ID_of_different_type_in_relationship_data_array() { // Arrange const string performerLocalId = "performer-1"; string newPlaylistName = _fakers.Playlist.Generate().Name; var requestBody = new { atomic__operations = new object[] { new { op = "remove", @ref = new { type = "lyrics", id = Unknown.StringId.For<Lyric, long>() } }, new { op = "add", data = new { type = "performers", lid = performerLocalId } }, new { op = "add", data = new { type = "playlists", attributes = new { name = newPlaylistName }, relationships = new { tracks = new { data = new[] { new { type = "musicTracks", lid = performerLocalId } } } } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.ShouldHaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("Incompatible type in Local ID usage."); error.Detail.Should().Be("Local ID 'performer-1' belongs to resource type 'performers' instead of 'musicTracks'."); error.Source.ShouldNotBeNull(); error.Source.Pointer.Should().Be("/atomic:operations[2]"); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using CodeFirstWebFramework; namespace AccountServer { /// <summary> /// Common code for customer &amp; supplier /// </summary> public abstract class CustomerSupplier : AppModule { /// <summary> /// "S" for supplier, "C" for customer /// </summary> public string NameType; /// <summary> /// "Customer" or "Supplier" /// </summary> public string Name; /// <summary> /// The different document types /// </summary> public DocType InvoiceDoc, CreditDoc, PaymentDoc; /// <summary> /// Purchase Ledger or Sales Ledger /// </summary> public Acct LedgerAccount; string _module; public CustomerSupplier(string nameType, Acct ledgerAccount, DocType invoiceDoc, DocType creditDoc, DocType paymentDoc) { NameType = nameType; Name = NameType.NameType(); LedgerAccount = ledgerAccount; InvoiceDoc = invoiceDoc; CreditDoc = creditDoc; PaymentDoc = paymentDoc; _module = nameType == "C" ? "/customer/" : "/supplier/"; } protected override void Init() { base.Init(); InsertMenuOptions(new MenuOption("Listing", _module + "default.html")); if(Settings.RecordVat) InsertMenuOptions(new MenuOption("VAT codes", _module + "vatcodes.html")); if (!SecurityOn || UserAccessLevel >= AccessLevel.ReadWrite) InsertMenuOptions( new MenuOption("New " + Name, _module + "detail.html?id=0"), new MenuOption("New " + InvoiceDoc.UnCamel(), _module + "document.html?id=0&type=" + (int)InvoiceDoc), new MenuOption("New " + CreditDoc.UnCamel(), _module + "document.html?id=0&type=" + (int)CreditDoc), new MenuOption("New " + PaymentDoc.UnCamel(), _module + "payment.html?id=0") ); } /// <summary> /// All Customers or Suppliers /// </summary> public object DefaultListing() { return Database.Query(@"SELECT NameAddress.*, Count(Outstanding) AS Outstanding FROM NameAddress LEFT JOIN Journal ON NameAddressId = idNameAddress AND AccountId = " + (int)LedgerAccount + @" AND Outstanding <> 0 WHERE Type=" + Database.Quote(NameType) + @" GROUP BY idNameAddress ORDER BY Name "); } /// <summary> /// Get record for editing /// </summary> public void Detail(int id) { RecordDetail record = Database.QueryOne<RecordDetail>(@"SELECT NameAddress.*, Sum(Outstanding) AS Outstanding FROM NameAddress LEFT JOIN Journal ON NameAddressId = idNameAddress AND AccountId = " + (int)LedgerAccount + @" AND Outstanding <> 0 WHERE idNameAddress = " + id ); if (record.Id == null) record.Type = NameType; else { checkNameType(record.Type, NameType); addNameToMenuOptions((int)record.Id); Title += " - " + record.Name; } Record = record; } public AjaxReturn DetailSave(NameAddress json) { checkNameType(json.Type, NameType); return SaveRecord(json, true); } /// <summary> /// Retrieve document, or prepare new one /// </summary> public JObject document(int id, DocType type) { Title = Title.Replace("Document", type.UnCamel()); Extended_Document header = getDocument<Extended_Document>(id); if (header.idDocument == null) { header.DocumentTypeId = (int)type; header.DocType = type.UnCamel(); header.DocumentDate = Utils.Today; header.DocumentName = ""; header.DocumentIdentifier = Settings.NextNumber(type).ToString(); if (GetParameters["name"].IsInteger()) { JObject name = Database.QueryOne("*", "WHERE Type = " + Database.Quote(NameType) + " AND idNameAddress = " + GetParameters["name"], "NameAddress"); if (name != null) { checkNameType(name.AsString("Type"), NameType); header.DocumentNameAddressId = name.AsInt("idNameAddress"); header.DocumentAddress = name.AsString("Address"); header.DocumentName = name.AsString("Name"); } } } else { checkDocType(header.DocumentTypeId, type); checkNameType(header.DocumentNameAddressId, NameType); } JObject record = new JObject().AddRange("header", header); nextPreviousDocument(record, "WHERE DocumentTypeId = " + (int)type); record.AddRange("VatCodes", SelectVatCodes(), "Names", SelectNames(NameType)); return record; } /// <summary> /// Update a document after editing /// </summary> public AjaxReturn DocumentSave(InvoiceDocument json) { Database.BeginTransaction(); Extended_Document document = json.header; DocType t = checkDocType(document.DocumentTypeId, InvoiceDoc, CreditDoc); JObject oldDoc = getCompleteDocument(document.idDocument); int sign = SignFor(t); Extended_Document original = getDocument(document); decimal vat = 0; decimal net = 0; if (document.idDocument == null) allocateDocumentIdentifier(document); foreach (InvoiceLine detail in json.detail) { if ((detail.ProductId == 0 || detail.ProductId == null) && (detail.AccountId == 0 || detail.AccountId == null)) { Utils.Check(detail.LineAmount == 0 && detail.VatAmount == 0, "All lines must be allocated to an account"); continue; } net += detail.LineAmount; vat += detail.VatAmount; } Utils.Check(document.DocumentAmount == net + vat, "Document does not balance"); decimal changeInDocumentAmount = -sign * (document.DocumentAmount - original.DocumentAmount); var lineNum = 1; fixNameAddress(document, NameType); if(SecurityOn && Settings.RequireAuthorisation && NameType == "S") { if (Admin && document.Authorised == 0) { document.Authorised = null; } else if (original.Authorised == null || original.Authorised == Session.User.idUser) { document.Authorised = document.Authorised > 0 ? Session.User.idUser : null; } else { document.Authorised = original.Authorised; } } Database.Update(document); // Find any existing VAT record Journal vatJournal = Database.QueryOne<Journal>("SELECT * FROM Journal WHERE DocumentId = " + document.idDocument + " AND AccountId = " + (int)Acct.VATControl + " ORDER BY JournalNum DESC"); Journal journal = Database.Get(new Journal() { DocumentId = (int)document.idDocument, JournalNum = lineNum }); journal.DocumentId = (int)document.idDocument; journal.JournalNum = lineNum++; journal.AccountId = (int)LedgerAccount; journal.NameAddressId = document.DocumentNameAddressId; journal.Memo = document.DocumentMemo; journal.Amount += changeInDocumentAmount; journal.Outstanding += changeInDocumentAmount; Database.Update(journal); foreach (InvoiceLine detail in json.detail) { if ((detail.ProductId == 0 || detail.ProductId == null) && (detail.AccountId == 0 || detail.AccountId == null)) continue; journal = Database.Get(new Journal() { DocumentId = (int)document.idDocument, JournalNum = lineNum }); journal.DocumentId = (int)document.idDocument; journal.JournalNum = lineNum++; journal.AccountId = (int)detail.AccountId; journal.NameAddressId = document.DocumentNameAddressId; journal.Memo = detail.Memo; journal.Outstanding += sign * detail.LineAmount - journal.Amount; journal.Amount = sign * detail.LineAmount; Database.Update(journal); Line line = new Line() { idLine = journal.idJournal, Qty = detail.Qty, ProductId = detail.ProductId, LineAmount = detail.LineAmount, VatCodeId = detail.VatCodeId, VatRate = detail.VatRate, VatAmount = detail.VatAmount }; Database.Update(line); } Database.Execute("DELETE FROM Line WHERE idLine IN (SELECT idJournal FROM Journal WHERE DocumentId = " + document.idDocument + " AND JournalNum >= " + lineNum + ")"); Database.Execute("DELETE FROM Journal WHERE DocumentId = " + document.idDocument + " AND JournalNum >= " + lineNum); if (vat != 0 || vatJournal.idJournal != null) { vat *= sign; decimal changeInVatAmount = vat - vatJournal.Amount; Utils.Check(document.VatPaid == null || document.VatPaid < 1 || changeInVatAmount == 0, "Cannot alter VAT on this document, it has already been declared"); vatJournal.DocumentId = (int)document.idDocument; vatJournal.AccountId = (int)Acct.VATControl; vatJournal.NameAddressId = document.DocumentNameAddressId; vatJournal.Memo = "Total VAT"; vatJournal.JournalNum = lineNum++; vatJournal.Amount = vat; vatJournal.Outstanding += changeInVatAmount; Database.Update(vatJournal); } JObject newDoc = getCompleteDocument(document.idDocument); Database.AuditUpdate("Document", document.idDocument, oldDoc, newDoc); Settings.RegisterNumber(this, document.DocumentTypeId, Utils.ExtractNumber(document.DocumentIdentifier)); Database.Commit(); return new AjaxReturn() { message = "Document saved", id = document.idDocument }; } public AjaxReturn DocumentDelete(int id) { return deleteDocument(id, InvoiceDoc, CreditDoc); } /// <summary> /// Retrieve a payment for editing /// </summary> public void Payment(int id) { PaymentDocument document = getPayment(id); JObject record = document.ToJObject(); nextPreviousDocument(record, "WHERE DocumentTypeId = " + (int)PaymentDoc); record.Add("BankAccounts", SelectBankAccounts()); record.Add("Names", SelectNames(NameType)); Record = record; } /// <summary> /// Retrieve a payment, or prepare a new one /// </summary> PaymentDocument getPayment(int? id) { PaymentHeader header = getDocument<PaymentHeader>(id); if (header.idDocument == null) { header.DocumentTypeId = (int)PaymentDoc; header.DocumentDate = Utils.Today; header.DocumentName = ""; header.DocumentIdentifier = "Payment"; if (GetParameters["acct"].IsInteger()) { header.DocumentAccountId = int.Parse(GetParameters["acct"]); } else if (Settings.DefaultBankAccount > 0) header.DocumentAccountId = (int)Settings.DefaultBankAccount; if (GetParameters["name"].IsInteger()) { JObject name = Database.QueryOne("*", "WHERE idNameAddress = " + GetParameters["name"], "NameAddress"); if (name != null) { checkNameType(name.AsString("Type"), NameType); header.DocumentNameAddressId = name.AsInt("idNameAddress"); header.DocumentAddress = name.AsString("Address"); header.DocumentName = name.AsString("Name"); } } } else { checkDocType(header.DocumentTypeId, PaymentDoc); checkNameType(header.DocumentNameAddressId, NameType); } PaymentDocument previous = new PaymentDocument() { header = header, detail = PaymentListing(header.idDocument, header.DocumentNameAddressId).ToList() }; return previous; } /// <summary> /// Get the payment details of an existing payment from the audit trail. /// Finds the most recent audit record. /// </summary> public PaymentDocument PaymentGetAudit(int? id) { if (id > 0) { AuditTrail t = Database.QueryOne<AuditTrail>("SELECT * FROM AuditTrail WHERE TableName = 'Payment' AND ChangeType <= " + (int)AuditType.Update + " AND RecordId = " + id + " ORDER BY DateChanged DESC"); if(!string.IsNullOrEmpty(t.Record)) return JObject.Parse(t.Record).ToObject<PaymentDocument>(); } return null; } /// <summary> /// List all the documents with an outstanding amount. /// For an existing document, also include all other documents that were paid by this one. /// </summary> public IEnumerable<PaymentLine> PaymentListing(int? id, int? name) { if (name > 0) { if (id == null) id = 0; return Database.Query<PaymentLine>("SELECT Document.*, DocType, " + (LedgerAccount == Acct.PurchaseLedger ? "-Amount AS Amount, CASE WHEN PaymentAmount IS NULL THEN -Outstanding ELSE PaymentAmount - Outstanding END AS Outstanding" : "Amount, CASE WHEN PaymentAmount IS NULL THEN Outstanding ELSE PaymentAmount + Outstanding END AS Outstanding") + @", CASE WHEN PaymentAmount IS NULL THEN 0 ELSE PaymentAmount END AS AmountPaid FROM Document JOIN Journal ON DocumentId = idDocument AND AccountId = " + (int)LedgerAccount + @" JOIN DocumentType ON idDocumentType = DocumentTypeId LEFT JOIN Payments ON idPaid = idDocument AND idPayment = " + id + @" WHERE NameAddressId = " + name + @" AND DocumentTypeId " + Database.In(InvoiceDoc, CreditDoc) + @" AND ((Outstanding <> 0" + ((SecurityOn && Settings.RequireAuthorisation && !Authorise && NameType == "S") ? " AND Authorised > 0" : "") + @") OR PaymentAmount IS NOT NULL) ORDER BY DocumentDate"); } return new List<PaymentLine>(); } public AjaxReturn PaymentSave(PaymentDocument json) { decimal amount = 0; Database.BeginTransaction(); PaymentHeader document = json.header; checkDocType(document.DocumentTypeId, PaymentDoc); checkNameType(document.DocumentNameAddressId, NameType); checkAccountIsAcctType(document.DocumentAccountId, AcctType.Bank, AcctType.CreditCard); if (document.idDocument == null) allocateDocumentIdentifier(document); PaymentDocument oldDoc = getPayment(document.idDocument); int sign = -SignFor(PaymentDoc); // Update the outstanding on the paid documents foreach (PaymentLine payment in json.detail) { Utils.Check(!SecurityOn || !Settings.RequireAuthorisation || Authorise || NameType != "S" || payment.Authorised > 0, "Cannot pay unauthorised document"); decimal a = payment.AmountPaid; PaymentLine old = oldDoc.PaymentFor(payment.idDocument); if (old != null) a -= old.AmountPaid; // reduce update by the amount paid last time it was saved int? docId = payment.idDocument; if (a != 0) { Database.Execute("UPDATE Journal SET Outstanding = Outstanding - " + sign * a + " WHERE DocumentId = " + Database.Quote(docId) + " AND AccountId = " + (int)LedgerAccount); amount += a; } } json.detail = json.detail.Where(l => l.AmountPaid != 0).ToList(); document.DocumentOutstanding = json.header.Remaining; decimal changeInDocumentAmount; decimal changeInOutstanding; // Virtual method, as calculation is different for customers and suppliers calculatePaymentChanges(json, amount, out changeInDocumentAmount, out changeInOutstanding); document.DocumentTypeId = (int)PaymentDoc; Database.Update(document); // Now delete the old cross reference records, and replace with new Database.Execute("DELETE FROM Payments WHERE idPayment = " + document.idDocument); foreach (PaymentLine payment in json.detail) { if (payment.AmountPaid != 0) { Database.Execute("INSERT INTO Payments (idPayment, idPaid, PaymentAmount) VALUES(" + document.idDocument + ", " + payment.idDocument + ", " + payment.AmountPaid + ")"); } } // Journal between bank account and sales/purchase ledger Journal journal = Database.Get(new Journal() { DocumentId = (int)document.Id, JournalNum = 1 }); journal.DocumentId = (int)document.idDocument; journal.JournalNum = 1; journal.NameAddressId = document.DocumentNameAddressId; journal.Memo = document.DocumentMemo; journal.AccountId = document.DocumentAccountId; journal.Amount += changeInDocumentAmount; journal.Outstanding += changeInOutstanding; Database.Update(journal); journal = Database.Get(new Journal() { DocumentId = (int)document.Id, JournalNum = 2 }); journal.DocumentId = (int)document.idDocument; journal.JournalNum = 2; journal.NameAddressId = document.DocumentNameAddressId; journal.Memo = document.DocumentMemo; journal.AccountId = (int)LedgerAccount; journal.Amount -= changeInDocumentAmount; journal.Outstanding -= changeInOutstanding; Database.Update(journal); Line line = Database.Get(new Line() { idLine = journal.idJournal }); line.idLine = journal.idJournal; line.LineAmount += PaymentDoc == DocType.BillPayment ? -changeInDocumentAmount : changeInDocumentAmount; Database.Update(line); oldDoc = PaymentGetAudit(document.idDocument); Database.AuditUpdate("Payment", document.idDocument, oldDoc == null ? null : oldDoc.ToJObject(), json.ToJObject()); Database.Commit(); return new AjaxReturn() { message = "Payment saved", id = document.idDocument }; } protected abstract void calculatePaymentChanges(PaymentDocument json, decimal amount, out decimal changeInDocumentAmount, out decimal changeInOutstanding); public AjaxReturn PaymentDelete(int id) { return deleteDocument(id, PaymentDoc); } /// <summary> /// Show payment history for a document (either a payment or an invoice/credit) /// </summary> public void PaymentHistory(int id) { Extended_Document document = getDocument<Extended_Document>(id); bool payment; Utils.Check(document.DocumentTypeId != 0, "Document {0} not found", id); switch ((DocType)document.DocumentTypeId) { case DocType.Invoice: case DocType.CreditMemo: case DocType.Bill: case DocType.Credit: payment = false; break; case DocType.Payment: case DocType.BillPayment: payment = true; break; default: throw new CheckException("No Payment History for {0}s", ((DocType)document.DocumentTypeId).UnCamel()); } Record = new JObject().AddRange( "header", document, "detail", Database.Query(@"SELECT * FROM Payments JOIN Extended_Document ON idDocument = " + (payment ? "idPaid" : "idPayment") + @" WHERE " + (payment ? "idPayment" : "idPaid") + " = " + id + @" ORDER BY DocumentDate, idDocument")); } public void VatCodes() { // Use customer template Module = "customer"; } public object VatCodesListing() { return Database.Query("*", "ORDER BY Code", "VatCode"); } public void VatCode(int id) { // Use customer template Module = "customer"; VatCode record = Database.Get<VatCode>(id); if (record.Id != null) Title += " - " + record.Code + ":" + record.VatDescription; Record = record; } public AjaxReturn VatCodeDelete(int id) { AjaxReturn result = new AjaxReturn(); try { Database.Delete("VatCode", id, true); result.message = "VAT code deleted"; } catch { result.error = "Cannot delete - VAT code in use"; } return result; } public AjaxReturn VatCodeSave(VatCode json) { return SaveRecord(json, true); } void addNameToMenuOptions(int id) { foreach (MenuOption option in Menu) if(option.Text.StartsWith("New ")) option.Url += "&name=" + id; } public class RecordDetail : NameAddress { public decimal? Outstanding; } public class InvoiceDocument : JsonObject { public Extended_Document header; public List<InvoiceLine> detail; } public class PaymentLine : Document { public string DocType; public decimal Amount; public decimal Outstanding; public decimal AmountPaid; } public class PaymentHeader : Extended_Document { public decimal Allocated; public decimal Remaining; } public class PaymentDocument : JsonObject { public PaymentDocument() { detail = new List<PaymentLine>(); } public PaymentHeader header; public List<PaymentLine> detail; public PaymentLine PaymentFor(int? documentId) { return detail.FirstOrDefault(d => d.idDocument == documentId); } } } public class InvoiceLine : Line { public int? AccountId; public string Memo; } }
//------------------------------------------------------------------------------ // <copyright file="ToolStripDropDownItem.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Windows.Forms { using System; using System.Drawing; using System.Windows.Forms; using System.ComponentModel; using System.Diagnostics; using System.Security.Permissions; using System.Windows.Forms.Layout; /// <include file='doc\ToolStripDropDownItem.uex' path='docs/doc[@for="ToolStripDropDownItem"]/*' /> /// <devdoc> /// Base class for ToolStripItems that display DropDown windows. /// </devdoc> [Designer("System.Windows.Forms.Design.ToolStripMenuItemDesigner, " + AssemblyRef.SystemDesign)] [DefaultProperty("DropDownItems")] public abstract class ToolStripDropDownItem : ToolStripItem { private ToolStripDropDown dropDown = null; private ToolStripDropDownDirection toolStripDropDownDirection = ToolStripDropDownDirection.Default; private static readonly object EventDropDownShow = new object(); private static readonly object EventDropDownHide = new object(); private static readonly object EventDropDownOpened = new object(); private static readonly object EventDropDownClosed = new object(); private static readonly object EventDropDownItemClicked = new object(); /// <include file='doc\ToolStripDropDownItem.uex' path='docs/doc[@for="ToolStripDropDownItem.ToolStripDropDownItem"]/*' /> /// <devdoc> /// Protected ctor so you can't create one of these without deriving from it. /// </devdoc> protected ToolStripDropDownItem() { } protected ToolStripDropDownItem(string text, Image image, EventHandler onClick) : base(text, image, onClick) { } protected ToolStripDropDownItem(string text, Image image, EventHandler onClick, string name) : base(text, image, onClick, name) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] protected ToolStripDropDownItem(string text, Image image, params ToolStripItem[] dropDownItems) : this(text, image, (EventHandler)null) { if (dropDownItems != null) { this.DropDownItems.AddRange(dropDownItems); } } /// <include file='doc\ToolStripDropDownItem.uex' path='docs/doc[@for="ToolStripDropDownItem.DropDown"]/*' /> /// <devdoc> /// The ToolStripDropDown that will be displayed when this item is clicked. /// </devdoc> [ TypeConverter(typeof(ReferenceConverter)), SRCategory(SR.CatData), SRDescription(SR.ToolStripDropDownDescr) ] public ToolStripDropDown DropDown { get { if (dropDown == null) { DropDown = CreateDefaultDropDown(); if (!(this is ToolStripOverflowButton)) { dropDown.SetAutoGeneratedInternal(true); } if (ParentInternal != null) { dropDown.ShowItemToolTips = ParentInternal.ShowItemToolTips; } } return dropDown; } set { if (dropDown != value) { if (dropDown != null) { dropDown.Opened -= new EventHandler(DropDown_Opened); dropDown.Closed -= new ToolStripDropDownClosedEventHandler(DropDown_Closed); dropDown.ItemClicked -= new ToolStripItemClickedEventHandler(DropDown_ItemClicked); dropDown.UnassignDropDownItem(); } dropDown = value; if (dropDown != null) { dropDown.Opened += new EventHandler(DropDown_Opened); dropDown.Closed += new ToolStripDropDownClosedEventHandler(DropDown_Closed); dropDown.ItemClicked += new ToolStripItemClickedEventHandler(DropDown_ItemClicked); dropDown.AssignToDropDownItem(); } } } } // the area which activates the dropdown. internal virtual Rectangle DropDownButtonArea { get { return this.Bounds; } } [Browsable(false)] [SRDescription(SR.ToolStripDropDownItemDropDownDirectionDescr)] [SRCategory(SR.CatBehavior)] public ToolStripDropDownDirection DropDownDirection { get { if (toolStripDropDownDirection == ToolStripDropDownDirection.Default) { ToolStrip parent = ParentInternal; if (parent != null) { ToolStripDropDownDirection dropDownDirection = parent.DefaultDropDownDirection; if (OppositeDropDownAlign || this.RightToLeft != parent.RightToLeft && (this.RightToLeft != RightToLeft.Inherit)) { dropDownDirection = RTLTranslateDropDownDirection(dropDownDirection, RightToLeft); } if (IsOnDropDown) { // we gotta make sure that we dont collide with the existing menu. Rectangle bounds = GetDropDownBounds(dropDownDirection); Rectangle ownerItemBounds = new Rectangle(TranslatePoint(Point.Empty, ToolStripPointType.ToolStripItemCoords, ToolStripPointType.ScreenCoords), Size); Rectangle intersectionBetweenChildAndParent = Rectangle.Intersect(bounds, ownerItemBounds); // grab the intersection if (intersectionBetweenChildAndParent.Width >= 2) { RightToLeft toggledRightToLeft = (RightToLeft == RightToLeft.Yes) ? RightToLeft.No : RightToLeft.Yes; ToolStripDropDownDirection newDropDownDirection = RTLTranslateDropDownDirection(dropDownDirection, toggledRightToLeft); // verify that changing the dropdown direction actually causes less intersection. int newIntersectionWidth = Rectangle.Intersect(GetDropDownBounds(newDropDownDirection), ownerItemBounds).Width; if (newIntersectionWidth < intersectionBetweenChildAndParent.Width) { dropDownDirection = newDropDownDirection; } } } return dropDownDirection; } } // someone has set a custom override return toolStripDropDownDirection; } set { // cant use Enum.IsValid as its not sequential switch (value) { case ToolStripDropDownDirection.AboveLeft: case ToolStripDropDownDirection.AboveRight: case ToolStripDropDownDirection.BelowLeft: case ToolStripDropDownDirection.BelowRight: case ToolStripDropDownDirection.Left: case ToolStripDropDownDirection.Right: case ToolStripDropDownDirection.Default: break; default: throw new InvalidEnumArgumentException("value", (int)value, typeof(ToolStripDropDownDirection)); } if (toolStripDropDownDirection != value) { toolStripDropDownDirection = value; if (HasDropDownItems && DropDown.Visible) { DropDown.Location = DropDownLocation; } } } } /// <include file='doc\ToolStripDropDownItem.uex' path='docs/doc[@for="ToolStripDropDownItem.DropDownClosed"]/*' /> /// <devdoc> /// Occurs when the dropdown is closed /// </devdoc> [ SRCategory(SR.CatAction), SRDescription(SR.ToolStripDropDownClosedDecr) ] public event EventHandler DropDownClosed { add { Events.AddHandler(EventDropDownClosed, value); } remove { Events.RemoveHandler(EventDropDownClosed, value); } } /// <include file='doc\ToolStripDropDownItem.uex' path='docs/doc[@for="ToolStripDropDownItem.DropDownLocation"]/*' /> internal protected virtual Point DropDownLocation { get { if (ParentInternal == null || !HasDropDownItems){ return Point.Empty; } ToolStripDropDownDirection dropDownDirection = DropDownDirection; return GetDropDownBounds(dropDownDirection).Location; } } /// <include file='doc\WinBarPopupItem.uex' path='docs/doc[@for="ToolStripDropDownItem.DropDownOpening"]/*' /> [ SRCategory(SR.CatAction), SRDescription(SR.ToolStripDropDownOpeningDescr) ] public event EventHandler DropDownOpening { add { Events.AddHandler(EventDropDownShow, value); } remove { Events.RemoveHandler(EventDropDownShow, value); } } /// <include file='doc\ToolStripDropDownItem.uex' path='docs/doc[@for="ToolStripDropDownItem.DropDownOpened"]/*' /> /// <devdoc> /// Occurs when the dropdown is opened /// </devdoc> [ SRCategory(SR.CatAction), SRDescription(SR.ToolStripDropDownOpenedDescr) ] public event EventHandler DropDownOpened { add { Events.AddHandler(EventDropDownOpened, value); } remove { Events.RemoveHandler(EventDropDownOpened, value); } } /// <include file='doc\ToolStripDropDownItem.uex' path='docs/doc[@for="ToolStripDropDownItem.DropDownItems"]/*' /> /// <devdoc> /// Returns the DropDown's items collection. /// </devdoc> [ DesignerSerializationVisibility(DesignerSerializationVisibility.Content), SRCategory(SR.CatData), SRDescription(SR.ToolStripDropDownItemsDescr) ] public ToolStripItemCollection DropDownItems { get { return DropDown.Items; } } /// <include file='doc\ToolStripDropDownItem.uex' path='docs/doc[@for="ToolStripDropDownItem.DropDownItemClicked"]/*' /> /// <devdoc> /// Occurs when the dropdown is opened /// </devdoc> [SRCategory(SR.CatAction)] public event ToolStripItemClickedEventHandler DropDownItemClicked { add { Events.AddHandler(EventDropDownItemClicked, value); } remove { Events.RemoveHandler(EventDropDownItemClicked, value); } } /// <include file='doc\ToolStripPopupItem.uex' path='docs/doc[@for="ToolStripDropDownItem.HasDropDownItems"]/*' /> [Browsable(false)] public virtual bool HasDropDownItems { get { //VSWhidbey 354665: use count of visible DisplayedItems instead so that we take into account things that arent visible return (dropDown != null) && dropDown.HasVisibleItems; } } /// <include file='doc\ToolStripPopupItem.uex' path='docs/doc[@for="ToolStripDropDownItem.HasDropDown"]/*' /> [Browsable(false)] public bool HasDropDown { get { return dropDown != null; } } /// <include file='doc\ToolStripDropDownItem.uex' path='docs/doc[@for="ToolStripDropDownItem.Pressed"]/*' /> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override bool Pressed { get { // if (dropDown != null) { if (DropDown.AutoClose || !IsInDesignMode || (IsInDesignMode && !IsOnDropDown)){ return DropDown.OwnerItem == this && DropDown.Visible; } } return base.Pressed; } } internal virtual bool OppositeDropDownAlign { get { return false; } } internal virtual void AutoHide(ToolStripItem otherItemBeingSelected) { HideDropDown(); } /// <include file='doc\ToolStripDropDownItem.uex' path='docs/doc[@for="ToolStripDropDownItem.CreateAccessibilityInstance"]/*' /> protected override AccessibleObject CreateAccessibilityInstance() { return new ToolStripDropDownItemAccessibleObject(this); } /// <include file='doc\ToolStripPopupItem.uex' path='docs/doc[@for="ToolStripDropDownItem.CreateDefaultDropDown"]/*' /> protected virtual ToolStripDropDown CreateDefaultDropDown() { // AutoGenerate a Winbar DropDown - set the property so we hook events return new ToolStripDropDown(this, true); } private Rectangle DropDownDirectionToDropDownBounds(ToolStripDropDownDirection dropDownDirection, Rectangle dropDownBounds) { Point offset = Point.Empty; switch (dropDownDirection) { case ToolStripDropDownDirection.AboveLeft: offset.X = - dropDownBounds.Width + this.Width; offset.Y = - dropDownBounds.Height+1; break; case ToolStripDropDownDirection.AboveRight: offset.Y = - dropDownBounds.Height+1; break; case ToolStripDropDownDirection.BelowRight: offset.Y = this.Height-1; break; case ToolStripDropDownDirection.BelowLeft: offset.X = - dropDownBounds.Width + this.Width; offset.Y = this.Height-1; break; case ToolStripDropDownDirection.Right: offset.X = this.Width; if (!IsOnDropDown) { // overlap the toplevel toolstrip offset.X -=1; } break; case ToolStripDropDownDirection.Left: offset.X = - dropDownBounds.Width; break; } Point itemScreenLocation = this.TranslatePoint(Point.Empty, ToolStripPointType.ToolStripItemCoords, ToolStripPointType.ScreenCoords); dropDownBounds.Location = new Point(itemScreenLocation.X + offset.X, itemScreenLocation.Y + offset.Y); dropDownBounds = WindowsFormsUtils.ConstrainToScreenWorkingAreaBounds(dropDownBounds); return dropDownBounds; } private void DropDown_Closed(object sender, ToolStripDropDownClosedEventArgs e) { OnDropDownClosed(EventArgs.Empty); } private void DropDown_Opened(object sender, EventArgs e) { OnDropDownOpened(EventArgs.Empty); } private void DropDown_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { OnDropDownItemClicked(e); } /// <include file='doc\ToolStripDropDownItem.uex' path='docs/doc[@for="ToolStripDropDownItem.Dispose"]/*' /> /// <devdoc> /// Make sure we unhook dropdown events. /// </devdoc> protected override void Dispose(bool disposing) { if (this.dropDown != null) { dropDown.Opened -= new EventHandler(DropDown_Opened); dropDown.Closed -= new ToolStripDropDownClosedEventHandler(DropDown_Closed); dropDown.ItemClicked -= new ToolStripItemClickedEventHandler(DropDown_ItemClicked); if (disposing && dropDown.IsAutoGenerated) { // if we created the dropdown, dispose it and its children. dropDown.Dispose(); dropDown = null; } } base.Dispose(disposing); } private Rectangle GetDropDownBounds(ToolStripDropDownDirection dropDownDirection) { Rectangle dropDownBounds = new Rectangle(Point.Empty, DropDown.GetSuggestedSize()); // calculate the offset from the upper left hand corner of the item. dropDownBounds = DropDownDirectionToDropDownBounds(dropDownDirection, dropDownBounds); // we should make sure we dont obscure the owner item. Rectangle itemScreenBounds = new Rectangle(this.TranslatePoint(Point.Empty, ToolStripPointType.ToolStripItemCoords, ToolStripPointType.ScreenCoords), this.Size); if (Rectangle.Intersect(dropDownBounds, itemScreenBounds).Height > 1) { bool rtl = (RightToLeft == RightToLeft.Yes); // try positioning to the left if (Rectangle.Intersect(dropDownBounds, itemScreenBounds).Width > 1) { dropDownBounds = DropDownDirectionToDropDownBounds(!rtl ? ToolStripDropDownDirection.Right : ToolStripDropDownDirection.Left, dropDownBounds); } // try positioning to the right if (Rectangle.Intersect(dropDownBounds, itemScreenBounds).Width > 1) { dropDownBounds = DropDownDirectionToDropDownBounds(!rtl ? ToolStripDropDownDirection.Left : ToolStripDropDownDirection.Right, dropDownBounds); } } return dropDownBounds; } /// <include file='doc\ToolStripDropDownItem.uex' path='docs/doc[@for="ToolStripDropDownItem.HideDropDown"]/*' /> /// <devdoc> /// Hides the DropDown, if it is visible. /// </devdoc> public void HideDropDown() { // consider - CloseEventArgs to prevent shutting down. OnDropDownHide(EventArgs.Empty); if (this.dropDown != null && this.dropDown.Visible) { DropDown.Visible = false; } } protected override void OnFontChanged(EventArgs e) { base.OnFontChanged(e); if (dropDown != null) { dropDown.OnOwnerItemFontChanged(EventArgs.Empty); } } /// <include file='doc\ToolStripItem.uex' path='docs/doc[@for="ToolStripItem.OnBoundsChanged"]/*' /> protected override void OnBoundsChanged() { base.OnBoundsChanged(); //Reset the Bounds... if (this.dropDown != null && this.dropDown.Visible) { this.dropDown.Bounds = GetDropDownBounds(DropDownDirection); } } protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); if (HasDropDownItems) { // only perform a layout on a visible dropdown - otherwise clear the preferred size cache. if (DropDown.Visible) { LayoutTransaction.DoLayout(DropDown, this, PropertyNames.RightToLeft); } else { CommonProperties.xClearPreferredSizeCache(DropDown); DropDown.LayoutRequired = true; } } } internal override void OnImageScalingSizeChanged(EventArgs e) { base.OnImageScalingSizeChanged(e); if (HasDropDown && DropDown.IsAutoGenerated) { DropDown.DoLayoutIfHandleCreated(new ToolStripItemEventArgs(this)); } } /// <include file='doc\ToolStripDropDownItem.uex' path='docs/doc[@for="ToolStripDropDownItem.OnDropDownHide"]/*' /> /// <devdoc> /// Called as a response to HideDropDown /// </devdoc> protected virtual void OnDropDownHide(EventArgs e) { this.Invalidate(); EventHandler handler = (EventHandler)Events[EventDropDownHide]; if (handler != null) handler(this, e); } /// <include file='doc\ToolStripDropDownItem.uex' path='docs/doc[@for="ToolStripDropDownItem.OnDropDownShow"]/*' /> /// <devdoc> /// Last chance to stick in the DropDown before it is shown. /// </devdoc> protected virtual void OnDropDownShow(EventArgs e) { EventHandler handler = (EventHandler)Events[EventDropDownShow]; if (handler != null) { handler(this, e); } } /// <include file='doc\ToolStripDropDownItem.uex' path='docs/doc[@for="ToolStripDropDownItem.OnDropDownOpened"]/*' /> /// <devdoc> /// called when the default item is clicked /// </devdoc> protected internal virtual void OnDropDownOpened(System.EventArgs e) { // only send the event if we're the thing that currently owns the DropDown. if (DropDown.OwnerItem == this) { EventHandler handler = (EventHandler)Events[EventDropDownOpened]; if (handler != null) handler(this, e); } } /// <include file='doc\ToolStripDropDownItem.uex' path='docs/doc[@for="ToolStripDropDownItem.OnDropDownClosed"]/*' /> /// <devdoc> /// called when the default item is clicked /// </devdoc> protected internal virtual void OnDropDownClosed(System.EventArgs e) { // only send the event if we're the thing that currently owns the DropDown. this.Invalidate(); if (DropDown.OwnerItem == this) { EventHandler handler = (EventHandler)Events[EventDropDownClosed]; if (handler != null) handler(this, e); if (!DropDown.IsAutoGenerated) { DropDown.OwnerItem = null; } } } /// <include file='doc\ToolStripDropDownItem.uex' path='docs/doc[@for="ToolStripDropDownItem.OnDropDownItemClicked"]/*' /> /// <devdoc> /// called when the default item is clicked /// </devdoc> protected internal virtual void OnDropDownItemClicked(ToolStripItemClickedEventArgs e) { // only send the event if we're the thing that currently owns the DropDown. if (DropDown.OwnerItem == this) { ToolStripItemClickedEventHandler handler = (ToolStripItemClickedEventHandler)Events[EventDropDownItemClicked]; if (handler != null) handler(this, e); } } [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] protected internal override bool ProcessCmdKey(ref Message m, Keys keyData) { if (HasDropDownItems) { return DropDown.ProcessCmdKeyInternal(ref m, keyData); } return base.ProcessCmdKey(ref m, keyData); } /// <include file='doc\ToolStripPopupItem.uex' path='docs/doc[@for="ToolStripDropDownItem.ProcessDialogKey"]/*' /> [UIPermission(SecurityAction.LinkDemand, Window=UIPermissionWindow.AllWindows)] protected internal override bool ProcessDialogKey(Keys keyData) { Keys keyCode = (Keys)keyData & Keys.KeyCode; if (HasDropDownItems) { // VSWhidbey 478068: items on the overflow should have the same kind of keyboard handling as a toplevel bool isToplevel = (!IsOnDropDown || IsOnOverflow); if (isToplevel && (keyCode == Keys.Down || keyCode == Keys.Up || keyCode == Keys.Enter || (SupportsSpaceKey && keyCode == Keys.Space))) { Debug.WriteLineIf(ToolStrip.SelectionDebug.TraceVerbose, "[SelectDBG ProcessDialogKey] open submenu from toplevel item"); if (Enabled || DesignMode) { // |__[ * File ]_____| * is where you are. Up or down arrow hit should expand menu this.ShowDropDown(); this.DropDown.SelectNextToolStripItem(null, true); }// else eat the key return true; } else if (!isToplevel) { // if we're on a DropDown - then cascade out. bool menusCascadeRight = (((int)DropDownDirection & 0x0001) == 0); bool forward = ((keyCode == Keys.Enter) || (SupportsSpaceKey && keyCode == Keys.Space)); forward = (forward || (menusCascadeRight && keyCode == Keys.Left) || (!menusCascadeRight && keyCode == Keys.Right)); if (forward) { Debug.WriteLineIf(ToolStrip.SelectionDebug.TraceVerbose, "[SelectDBG ProcessDialogKey] open submenu from NON-toplevel item"); if (Enabled || DesignMode) { this.ShowDropDown(); this.DropDown.SelectNextToolStripItem(null, true); } // else eat the key return true; } } } if (IsOnDropDown) { bool menusCascadeRight = (((int)DropDownDirection & 0x0001) == 0); bool backward = ((menusCascadeRight && keyCode == Keys.Right) || (!menusCascadeRight && keyCode == Keys.Left)); if (backward) { Debug.WriteLineIf(ToolStrip.SelectionDebug.TraceVerbose, "[SelectDBG ProcessDialogKey] close submenu from NON-toplevel item"); // we're on a drop down but we're heading back up the chain. // remember to select the item that displayed this dropdown. ToolStripDropDown parent = GetCurrentParentDropDown(); if (parent != null && !parent.IsFirstDropDown) { // we're walking back up the dropdown chain. parent.SetCloseReason(ToolStripDropDownCloseReason.Keyboard); parent.SelectPreviousToolStrip(); return true; } // else if (parent.IsFirstDropDown) // the base handling (ToolStripDropDown.ProcessArrowKey) will perform auto-expansion of // the previous item in the menu. } } Debug.WriteLineIf(ToolStrip.SelectionDebug.TraceVerbose, "[SelectDBG ProcessDialogKey] ddi calling base"); return base.ProcessDialogKey(keyData); } private ToolStripDropDownDirection RTLTranslateDropDownDirection(ToolStripDropDownDirection dropDownDirection, RightToLeft rightToLeft) { switch (dropDownDirection) { case ToolStripDropDownDirection.AboveLeft: return ToolStripDropDownDirection.AboveRight; case ToolStripDropDownDirection.AboveRight: return ToolStripDropDownDirection.AboveLeft; case ToolStripDropDownDirection.BelowRight: return ToolStripDropDownDirection.BelowLeft; case ToolStripDropDownDirection.BelowLeft: return ToolStripDropDownDirection.BelowRight; case ToolStripDropDownDirection.Right: return ToolStripDropDownDirection.Left; case ToolStripDropDownDirection.Left: return ToolStripDropDownDirection.Right; } Debug.Fail("Why are we here"); // dont expect it to come to this but just in case here are the real defaults. if (IsOnDropDown) { return (rightToLeft == RightToLeft.Yes) ? ToolStripDropDownDirection.Left : ToolStripDropDownDirection.Right; } else { return (rightToLeft == RightToLeft.Yes) ? ToolStripDropDownDirection.BelowLeft : ToolStripDropDownDirection.BelowRight; } } /// <include file='doc\ToolStripDropDownItem.uex' path='docs/doc[@for="ToolStripDropDownItem.ShowDropDown"]/*' /> /// <devdoc> /// Shows the DropDown, if one is set. /// </devdoc> public void ShowDropDown() { this.ShowDropDown(false); } internal void ShowDropDown(bool mousePush) { this.ShowDropDownInternal(); ToolStripDropDownMenu menu = this.dropDown as ToolStripDropDownMenu; if (menu != null) { if (!mousePush) { menu.ResetScrollPosition(); } menu.RestoreScrollPosition(); } } private void ShowDropDownInternal() { if (this.dropDown == null || (!this.dropDown.Visible)) { // VSWhidbey 469145 we want to show if there's no dropdown // or if the dropdown is not visible. OnDropDownShow(EventArgs.Empty); } // the act of setting the drop down visible the first time sets the parent // it seems that GetVisibleCore returns true if your parent is null. if (this.dropDown != null && !this.dropDown.Visible) { if (this.dropDown.IsAutoGenerated && this.DropDownItems.Count <= 0) { return; // this is a no-op for autogenerated drop downs. } if (this.DropDown == this.ParentInternal) { throw new InvalidOperationException(SR.GetString(SR.ToolStripShowDropDownInvalidOperation)); } this.dropDown.OwnerItem = this; this.dropDown.Location = DropDownLocation; this.dropDown.Show(); this.Invalidate(); } } private bool ShouldSerializeDropDown() { return dropDown != null && !dropDown.IsAutoGenerated; } private bool ShouldSerializeDropDownDirection() { return (toolStripDropDownDirection != ToolStripDropDownDirection.Default); } private bool ShouldSerializeDropDownItems() { return (dropDown != null && dropDown.IsAutoGenerated); } } /// <include file='doc\ToolStripDropDownItem.uex' path='docs/doc[@for="ToolStripDropDownItemAccessibleObject"]/*' /> public class ToolStripDropDownItemAccessibleObject : ToolStripItem.ToolStripItemAccessibleObject { private ToolStripDropDownItem owner; /// <include file='doc\ToolStripDropDownItem.uex' path='docs/doc[@for="ToolStripDropDownItemAccessibleObject.ToolStripDropDownItemAccessibleObject"]/*' /> public ToolStripDropDownItemAccessibleObject(ToolStripDropDownItem item) : base(item) { owner = item; } /// <include file='doc\ToolStripDropDownItem.uex' path='docs/doc[@for="ToolStripDropDownItemAccessibleObject.Role"]/*' /> public override AccessibleRole Role { get { AccessibleRole role = Owner.AccessibleRole; if (role != AccessibleRole.Default) { return role; } return AccessibleRole.MenuItem; } } /// <include file='doc\ToolStripItem.uex' path='docs/doc[@for="ToolStripItemAccessibleObject.DoDefaultAction"]/*' /> [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] public override void DoDefaultAction() { ToolStripDropDownItem item = Owner as ToolStripDropDownItem; if (item != null && item.HasDropDownItems) { item.ShowDropDown(); } else { base.DoDefaultAction(); } } public override AccessibleObject GetChild(int index) { if ((owner == null) || !owner.HasDropDownItems) { return null; } return owner.DropDown.AccessibilityObject.GetChild(index); } public override int GetChildCount() { if ((owner == null) || !owner.HasDropDownItems) { return -1; } if (owner.DropDown.LayoutRequired) { LayoutTransaction.DoLayout(owner.DropDown, owner.DropDown, PropertyNames.Items); } return owner.DropDown.AccessibilityObject.GetChildCount(); } } }
using System; using System.Diagnostics; using System.Collections; using System.Runtime.InteropServices; using System.IO; using System.Text; using System.Collections.Generic; using RaptorDB.Common; using System.Collections.Concurrent; namespace RaptorDB { internal class StorageData<T> { public StorageItem<T> meta; public byte[] data; } public class StorageItem<T> { public T key; public string typename; public DateTime date = FastDateTime.Now; public bool isDeleted; public bool isReplicated; public int dataLength; public byte isCompressed; // 0 = no, 1 = MiniLZO } public interface IDocStorage<T> { int RecordCount(); byte[] GetBytes(int rowid, out StorageItem<T> meta); object GetObject(int rowid, out StorageItem<T> meta); StorageItem<T> GetMeta(int rowid); bool GetObject(T key, out object doc); } public enum SF_FORMAT { BSON, JSON } internal struct SplitFile { public long start; public long uptolength; public FileStream file; } internal class StorageFile<T> { FileStream _datawrite; FileStream _recfilewrite; FileStream _recfileread = null; FileStream _dataread = null; private string _filename = ""; private string _recfilename = ""; private long _lastRecordNum = 0; private long _lastWriteOffset = _fileheader.Length; private object _readlock = new object(); private bool _dirty = false; IGetBytes<T> _T = null; ILog _log = LogManager.GetLogger(typeof(StorageFile<T>)); private SF_FORMAT _saveFormat = SF_FORMAT.BSON; // **** change this if storage format changed **** internal static int _CurrentVersion = 2; //private ushort _splitMegaBytes = 0; // 0 = off //private bool _enableSplits = false; private List<SplitFile> _files = new List<SplitFile>(); private List<long> _uptoindexes = new List<long>(); // no splits in view mode private bool _viewmode = false; private SplitFile _lastsplitfile; public static byte[] _fileheader = { (byte)'M', (byte)'G', (byte)'D', (byte)'B', 0, // 4 -- storage file version number, 0 // 5 -- not used }; private static string _splitfileExtension = "00000"; private const int _KILOBYTE = 1024; // record format : // 1 type (0 = raw no meta data, 1 = bson meta, 2 = json meta) // 4 byte meta/data length, // n byte meta serialized data if exists // m byte data (if meta exists then m is in meta.dataLength) /// <summary> /// View data storage mode (no splits, bson save) /// </summary> /// <param name="filename"></param> public StorageFile(string filename) { _viewmode = true; _saveFormat = SF_FORMAT.BSON; // add version number _fileheader[5] = (byte)_CurrentVersion; Initialize(filename, false); } /// <summary> /// /// </summary> /// <param name="filename"></param> /// <param name="format"></param> /// <param name="StorageOnlyMode">= true -> don't create mgrec files (used for backup and replication mode)</param> public StorageFile(string filename, SF_FORMAT format, bool StorageOnlyMode) { _saveFormat = format; if (StorageOnlyMode) _viewmode = true; // no file splits // add version number _fileheader[5] = (byte)_CurrentVersion; Initialize(filename, StorageOnlyMode); } private StorageFile(string filename, bool StorageOnlyMode) { Initialize(filename, StorageOnlyMode); } private void Initialize(string filename, bool StorageOnlyMode) { _T = RDBDataType<T>.ByteHandler(); _filename = filename; // search for mgdat00000 extensions -> split files load if (File.Exists(filename + _splitfileExtension)) { LoadSplitFiles(filename); } if (File.Exists(filename) == false) _datawrite = new FileStream(filename, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite); else _datawrite = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); _dataread = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); if (_datawrite.Length == 0) { // new file _datawrite.Write(_fileheader, 0, _fileheader.Length); _datawrite.Flush(); _lastWriteOffset = _fileheader.Length; } else { long i = _datawrite.Seek(0L, SeekOrigin.End); if (_files.Count == 0) _lastWriteOffset = i; else _lastWriteOffset += i; // add to the splits } if (StorageOnlyMode == false) { // load rec pointers _recfilename = filename.Substring(0, filename.LastIndexOf('.')) + ".mgrec"; if (File.Exists(_recfilename) == false) _recfilewrite = new FileStream(_recfilename, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite); else _recfilewrite = new FileStream(_recfilename, FileMode.Open, FileAccess.Write, FileShare.ReadWrite); _recfileread = new FileStream(_recfilename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); _lastRecordNum = (int)(_recfilewrite.Length / 8); _recfilewrite.Seek(0L, SeekOrigin.End); } } private void LoadSplitFiles(string filename) { _log.Debug("Loading split files..."); _lastWriteOffset = 0; for (int i = 0; ; i++) { string _filename = filename + i.ToString(_splitfileExtension); if (File.Exists(_filename) == false) break; FileStream file = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); SplitFile sf = new SplitFile(); sf.start = _lastWriteOffset; _lastWriteOffset += file.Length; sf.file = file; sf.uptolength = _lastWriteOffset; _files.Add(sf); _uptoindexes.Add(sf.uptolength); } _lastsplitfile = _files[_files.Count - 1]; _log.Debug("Number of split files = " + _files.Count); } public static int GetStorageFileHeaderVersion(string filename) { string fn = filename + _splitfileExtension; // if split files -> load the header from the first file -> mgdat00000 if (File.Exists(fn) == false) fn = filename; // else use the mgdat file if (File.Exists(fn)) { var fs = new FileStream(fn, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); fs.Seek(0L, SeekOrigin.Begin); byte[] b = new byte[_fileheader.Length]; fs.Read(b, 0, _fileheader.Length); fs.Close(); return b[5]; } return _CurrentVersion; } public int Count() { return (int)_lastRecordNum; } public long WriteRawData(byte[] b) { return internalWriteData(null, b, true); } public long Delete(T key) { StorageItem<T> meta = new StorageItem<T>(); meta.key = key; meta.isDeleted = true; return internalWriteData(meta, null, false); } public long DeleteReplicated(T key) { StorageItem<T> meta = new StorageItem<T>(); meta.key = key; meta.isReplicated = true; meta.isDeleted = true; return internalWriteData(meta, null, false); } public long WriteObject(T key, object obj) { StorageItem<T> meta = new StorageItem<T>(); meta.key = key; meta.typename = fastJSON.Reflection.Instance.GetTypeAssemblyName(obj.GetType()); byte[] data; if (_saveFormat == SF_FORMAT.BSON) data = fastBinaryJSON.BJSON.ToBJSON(obj); else data = Helper.GetBytes(fastJSON.JSON.ToJSON(obj)); if(data.Length > (int)Global.CompressDocumentOverKiloBytes*_KILOBYTE) { meta.isCompressed = 1; data = MiniLZO.Compress(data); //MiniLZO } return internalWriteData(meta, data, false); } public long WriteReplicationObject(T key, object obj) { StorageItem<T> meta = new StorageItem<T>(); meta.key = key; meta.isReplicated = true; meta.typename = fastJSON.Reflection.Instance.GetTypeAssemblyName(obj.GetType()); byte[] data; if (_saveFormat == SF_FORMAT.BSON) data = fastBinaryJSON.BJSON.ToBJSON(obj); else data = Helper.GetBytes(fastJSON.JSON.ToJSON(obj)); if (data.Length > (int)Global.CompressDocumentOverKiloBytes * _KILOBYTE) { meta.isCompressed = 1; data = MiniLZO.Compress(data); } return internalWriteData(meta, data, false); } public long WriteData(T key, byte[] data) { StorageItem<T> meta = new StorageItem<T>(); meta.key = key; if (data.Length > (int)Global.CompressDocumentOverKiloBytes * _KILOBYTE) { meta.isCompressed = 1; data = MiniLZO.Compress(data); } return internalWriteData(meta, data, false); } public byte[] ReadBytes(long recnum) { StorageItem<T> meta; return ReadBytes(recnum, out meta); } public object ReadObject(long recnum) { StorageItem<T> meta = null; return ReadObject(recnum, out meta); } public object ReadObject(long recnum, out StorageItem<T> meta) { byte[] b = ReadBytes(recnum, out meta); if (b == null) return null; if (b[0] < 32) return fastBinaryJSON.BJSON.ToObject(b); else return fastJSON.JSON.ToObject(Encoding.ASCII.GetString(b)); } /// <summary> /// used for views only /// </summary> /// <param name="recnum"></param> /// <returns></returns> public byte[] ViewReadRawBytes(long recnum) { // views can't be split if (recnum >= _lastRecordNum) return null; lock (_readlock) { long offset = ComputeOffset(recnum); _dataread.Seek(offset, System.IO.SeekOrigin.Begin); byte[] hdr = new byte[5]; // read header _dataread.Read(hdr, 0, 5); // meta length int len = Helper.ToInt32(hdr, 1); int type = hdr[0]; if (type == 0) { byte[] data = new byte[len]; _dataread.Read(data, 0, len); return data; } return null; } } public void Shutdown() { if (_files.Count > 0) _files.ForEach(s => FlushClose(s.file)); FlushClose(_dataread); FlushClose(_recfileread); FlushClose(_recfilewrite); FlushClose(_datawrite); _dataread = null; _recfileread = null; _recfilewrite = null; _datawrite = null; } public static StorageFile<Guid> ReadForward(string filename) { StorageFile<Guid> sf = new StorageFile<Guid>(filename, true); return sf; } public StorageItem<T> ReadMeta(long rowid) { if (rowid >= _lastRecordNum) return null; lock (_readlock) { int metalen = 0; long off = ComputeOffset(rowid); FileStream fs = GetReadFileStreamWithSeek(off); StorageItem<T> meta = ReadMetaData(fs, out metalen); return meta; } } #region [ private / internal ] private long internalWriteData(StorageItem<T> meta, byte[] data, bool raw) { byte[] metabytes = null; if(!raw){ if (data != null) meta.dataLength = data.Length; metabytes = fastBinaryJSON.BJSON.ToBJSON(meta, new fastBinaryJSON.BJSONParameters { UseExtensions = false }); } lock (_readlock) { _dirty = true; // seek end of file long offset = _lastWriteOffset; if (_viewmode == false && Global.SplitStorageFilesMegaBytes > 0) { // current file size > _splitMegaBytes --> new file if (offset > (long)Global.SplitStorageFilesMegaBytes * 1024 * 1024) CreateNewStorageFile(); } if (raw == false) { // write header info _datawrite.Write(new byte[] { 1 }, 0, 1); // TODO : add json here, write bson for now _datawrite.Write(Helper.GetBytes(metabytes.Length, false), 0, 4); _datawrite.Write(metabytes, 0, metabytes.Length); // update pointer _lastWriteOffset += metabytes.Length + 5; } else { // write header info _datawrite.Write(new byte[] { 0 }, 0, 1); // write raw _datawrite.Write(Helper.GetBytes(data.Length, false), 0, 4); // update pointer _lastWriteOffset += 5; } if (data != null) { // write data block _datawrite.Write(data, 0, data.Length); _lastWriteOffset += data.Length; } // return starting offset -> recno long recno = _lastRecordNum++; if (_recfilewrite != null) _recfilewrite.Write(Helper.GetBytes(offset, false), 0, 8); if (Global.FlushStorageFileImmediately) { _datawrite.Flush(); if (_recfilewrite != null) _recfilewrite.Flush(); } return recno; } } private void CreateNewStorageFile() { _log.Debug("Split limit reached = " + _datawrite.Length); int i = _files.Count; // close files FlushClose(_datawrite); FlushClose(_dataread); long start = 0; if (i > 0) start = _lastsplitfile.uptolength; // last file offset // rename mgdat to mgdat0000n File.Move(_filename, _filename + i.ToString(_splitfileExtension)); FileStream file = new FileStream(_filename + i.ToString(_splitfileExtension), FileMode.Open, FileAccess.Read, FileShare.ReadWrite); SplitFile sf = new SplitFile(); sf.start = start; sf.uptolength = _lastWriteOffset; sf.file = file; _files.Add(sf); _uptoindexes.Add(sf.uptolength); _lastsplitfile = sf; // new mgdat file _datawrite = new FileStream(_filename, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite); _dataread = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); _log.Debug("New storage file created, count = " + _files.Count); } internal byte[] ReadBytes(long recnum, out StorageItem<T> meta) { meta = null; if (recnum >= _lastRecordNum) return null; lock (_readlock) { long off = ComputeOffset(recnum); FileStream fs = GetReadFileStreamWithSeek(off); byte[] data = internalReadBytes(fs, out meta); if (meta.isCompressed > 0) data = MiniLZO.Decompress(data); return data; } } private long ComputeOffset(long recnum) { if (_dirty) { _datawrite.Flush(); _recfilewrite.Flush(); } long off = recnum << 3;// *8L; byte[] b = new byte[8]; _recfileread.Seek(off, SeekOrigin.Begin); _recfileread.Read(b, 0, 8); off = Helper.ToInt64(b, 0); if (off == 0)// kludge off = 6; return off; } private byte[] internalReadBytes(FileStream fs, out StorageItem<T> meta) { int metalen = 0; meta = ReadMetaData(fs, out metalen); if (meta != null) { if (meta.isDeleted == false) { byte[] data = new byte[meta.dataLength]; fs.Read(data, 0, meta.dataLength); return data; } } else { byte[] data = new byte[metalen]; fs.Read(data, 0, metalen); return data; } return null; } private StorageItem<T> ReadMetaData(FileStream fs, out int metasize) { byte[] hdr = new byte[5]; // read header fs.Read(hdr, 0, 5); // meta length int len = Helper.ToInt32(hdr, 1); int type = hdr[0]; if (type > 0) { metasize = len + 5; hdr = new byte[len]; fs.Read(hdr, 0, len); StorageItem<T> meta; if (type == 1) meta = fastBinaryJSON.BJSON.ToObject<StorageItem<T>>(hdr); else { string str = Helper.GetString(hdr, 0, (short)hdr.Length); meta = fastJSON.JSON.ToObject<StorageItem<T>>(str); } return meta; } else { metasize = len; return null; } } private void FlushClose(FileStream st) { if (st != null) { st.Flush(true); st.Close(); } } internal T GetKey(long recnum, out bool deleted) { lock (_readlock) { deleted = false; long off = ComputeOffset(recnum); FileStream fs = GetReadFileStreamWithSeek(off); int metalen = 0; StorageItem<T> meta = ReadMetaData(fs, out metalen); deleted = meta.isDeleted; return meta.key; } } internal int CopyTo(StorageFile<T> storageFile, long startrecord) { FileStream fs; bool inthefiles = false; // copy data here lock (_readlock) { long off = ComputeOffset(startrecord); fs = GetReadFileStreamWithSeek(off); if (fs != _dataread) inthefiles = true; Pump(fs, storageFile._datawrite); } // pump the remainder of the files also if (inthefiles && _files.Count > 0) { long off = ComputeOffset(startrecord); int i = binarysearch(off); i++; // next file stream for (int j = i; j < _files.Count; j++) { lock (_readlock) { fs = _files[j].file; fs.Seek(0L, SeekOrigin.Begin); Pump(fs, storageFile._datawrite); } } // pump the current mgdat lock(_readlock) { _dataread.Seek(0L, SeekOrigin.Begin); Pump(_dataread, storageFile._datawrite); } } return (int)_lastRecordNum; } private static void Pump(Stream input, Stream output) { byte[] bytes = new byte[4096 * 2]; int n; while ((n = input.Read(bytes, 0, bytes.Length)) != 0) output.Write(bytes, 0, n); } internal IEnumerable<StorageData<T>> ReadOnlyEnumerate() { // MGREC files may not exist //// the total number of records //long count = _recfileread.Length >> 3; //for (long i = 0; i < count; i++) //{ // StorageItem<T> meta; // byte[] data = ReadBytes(i, out meta); // StorageData<T> sd = new StorageData<T>(); // sd.meta = meta; // if (meta.dataLength > 0) // sd.data = data; // yield return sd; //} long offset = _fileheader.Length;// start; // skip header long size = _dataread.Length; while (offset < size) { StorageData<T> sd = new StorageData<T>(); lock (_readlock) { _dataread.Seek(offset, SeekOrigin.Begin); int metalen = 0; StorageItem<T> meta = ReadMetaData(_dataread, out metalen); offset += metalen; sd.meta = meta; if (meta.dataLength > 0) { byte[] data = new byte[meta.dataLength]; _dataread.Read(data, 0, meta.dataLength); sd.data = data; } offset += meta.dataLength; } yield return sd; } } private FileStream GetReadFileStreamWithSeek(long offset) { long fileoffset = offset; // search split _files for offset and compute fileoffset in the file if (_files.Count > 0) // we have splits { if (offset < _lastsplitfile.uptolength) // offset is in the list { int i = binarysearch(offset); var f = _files[i]; fileoffset -= f.start; // offset in the file f.file.Seek(fileoffset, SeekOrigin.Begin); return f.file; } else fileoffset -= _lastsplitfile.uptolength; // offset in the mgdat file } // seek to position in file _dataread.Seek(fileoffset, SeekOrigin.Begin); return _dataread; } private int binarysearch(long offset) { //// binary search int low = 0; int high = _files.Count - 1; int midpoint = 0; int lastlower = 0; while (low <= high) { midpoint = low + (high - low) / 2; long k = _uptoindexes[midpoint]; // check to see if value is equal to item in array if (offset == k) return midpoint + 1; else if (offset < k) { high = midpoint - 1; lastlower = midpoint; } else low = midpoint + 1; } return lastlower; } #endregion } }
// Copyright 2015 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 UnityEngine; /// Performs distortion correction on the rendered stereo screen. This script /// and GvrPreRender work together to draw the whole screen in VR Mode. /// There should be exactly one of each component in any GVR-enabled scene. It /// is part of the _GvrCamera_ prefab, which is included in /// _GvrMain_. The GvrViewer script will create one at runtime if the /// scene doesn't already have it, so generally it is not necessary to manually /// add it unless you wish to edit the Camera component that it controls. /// /// In the Unity editor, this script also draws the analog of the UI layer on /// the phone (alignment marker, settings gear, etc). [RequireComponent(typeof(Camera))] [AddComponentMenu("GoogleVR/GvrPostRender")] public class GvrPostRender : MonoBehaviour { // Convenient accessor to the camera component used through this script. public Camera cam { get; private set; } // Distortion mesh parameters. // Size of one eye's distortion mesh grid. The whole mesh is two of these grids side by side. private const int kMeshWidth = 40; private const int kMeshHeight = 40; // Whether to apply distortion in the grid coordinates or in the texture coordinates. private const bool kDistortVertices = true; private Mesh distortionMesh; private Material meshMaterial; // UI Layer parameters. private Material uiMaterial; private float centerWidthPx; private float buttonWidthPx; private float xScale; private float yScale; private Matrix4x4 xfm; void Reset() { #if UNITY_EDITOR // Member variable 'cam' not always initialized when this method called in Editor. // So, we'll just make a local of the same name. var cam = GetComponent<Camera>(); #endif cam.clearFlags = CameraClearFlags.Depth; cam.backgroundColor = Color.magenta; // Should be noticeable if the clear flags change. cam.orthographic = true; cam.orthographicSize = 0.5f; cam.cullingMask = 0; cam.useOcclusionCulling = false; cam.depth = 100; } void Awake() { cam = GetComponent<Camera>(); Reset(); meshMaterial = new Material(Shader.Find("GoogleVR/UnlitTexture")); uiMaterial = new Material(Shader.Find("GoogleVR/SolidColor")); uiMaterial.color = new Color(0.8f, 0.8f, 0.8f); if (!Application.isEditor) { ComputeUIMatrix(); } } #if UNITY_EDITOR private float aspectComparison; void OnPreCull() { // The Game window's aspect ratio may not match the fake device parameters. float realAspect = (float)Screen.width / Screen.height; float fakeAspect = GvrViewer.Instance.Profile.screen.width / GvrViewer.Instance.Profile.screen.height; aspectComparison = fakeAspect / realAspect; cam.orthographicSize = 0.5f * Mathf.Max(1, aspectComparison); } #endif void OnRenderObject() { if (Camera.current != cam) return; GvrViewer.Instance.UpdateState(); var correction = GvrViewer.Instance.DistortionCorrection; RenderTexture stereoScreen = GvrViewer.Instance.StereoScreen; if (stereoScreen == null || correction == GvrViewer.DistortionCorrectionMethod.None) { return; } if (correction == GvrViewer.DistortionCorrectionMethod.Native && GvrViewer.Instance.NativeDistortionCorrectionSupported) { GvrViewer.Instance.PostRender(stereoScreen); } else { if (distortionMesh == null || GvrViewer.Instance.ProfileChanged) { RebuildDistortionMesh(); } meshMaterial.mainTexture = stereoScreen; meshMaterial.SetPass(0); Graphics.DrawMeshNow(distortionMesh, transform.position, transform.rotation); } stereoScreen.DiscardContents(); if (!GvrViewer.Instance.NativeUILayerSupported) { DrawUILayer(); } } private void RebuildDistortionMesh() { distortionMesh = new Mesh(); Vector3[] vertices; Vector2[] tex; ComputeMeshPoints(kMeshWidth, kMeshHeight, kDistortVertices, out vertices, out tex); int[] indices = ComputeMeshIndices(kMeshWidth, kMeshHeight, kDistortVertices); Color[] colors = ComputeMeshColors(kMeshWidth, kMeshHeight, tex, indices, kDistortVertices); distortionMesh.vertices = vertices; distortionMesh.uv = tex; distortionMesh.colors = colors; distortionMesh.triangles = indices; distortionMesh.Optimize(); distortionMesh.UploadMeshData(true); } private static void ComputeMeshPoints(int width, int height, bool distortVertices, out Vector3[] vertices, out Vector2[] tex) { float[] lensFrustum = new float[4]; float[] noLensFrustum = new float[4]; Rect viewport; GvrProfile profile = GvrViewer.Instance.Profile; profile.GetLeftEyeVisibleTanAngles(lensFrustum); profile.GetLeftEyeNoLensTanAngles(noLensFrustum); viewport = profile.GetLeftEyeVisibleScreenRect(noLensFrustum); vertices = new Vector3[2 * width * height]; tex = new Vector2[2 * width * height]; for (int e = 0, vidx = 0; e < 2; e++) { for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++, vidx++) { float u = (float)i / (width - 1); float v = (float)j / (height - 1); float s, t; // The texture coordinates in StereoScreen to read from. if (distortVertices) { // Grid points regularly spaced in StreoScreen, and barrel distorted in the mesh. s = u; t = v; float x = Mathf.Lerp(lensFrustum[0], lensFrustum[2], u); float y = Mathf.Lerp(lensFrustum[3], lensFrustum[1], v); float d = Mathf.Sqrt(x * x + y * y); float r = profile.viewer.distortion.distortInv(d); float p = x * r / d; float q = y * r / d; u = (p - noLensFrustum[0]) / (noLensFrustum[2] - noLensFrustum[0]); v = (q - noLensFrustum[3]) / (noLensFrustum[1] - noLensFrustum[3]); } else { // Grid points regularly spaced in the mesh, and pincushion distorted in // StereoScreen. float p = Mathf.Lerp(noLensFrustum[0], noLensFrustum[2], u); float q = Mathf.Lerp(noLensFrustum[3], noLensFrustum[1], v); float r = Mathf.Sqrt(p * p + q * q); float d = profile.viewer.distortion.distort(r); float x = p * d / r; float y = q * d / r; s = Mathf.Clamp01((x - lensFrustum[0]) / (lensFrustum[2] - lensFrustum[0])); t = Mathf.Clamp01((y - lensFrustum[3]) / (lensFrustum[1] - lensFrustum[3])); } // Convert u,v to mesh screen coordinates. float aspect = profile.screen.width / profile.screen.height; u = (viewport.x + u * viewport.width - 0.5f) * aspect; v = viewport.y + v * viewport.height - 0.5f; vertices[vidx] = new Vector3(u, v, 1); // Adjust s to account for left/right split in StereoScreen. s = (s + e) / 2; tex[vidx] = new Vector2(s, t); } } float w = lensFrustum[2] - lensFrustum[0]; lensFrustum[0] = -(w + lensFrustum[0]); lensFrustum[2] = w - lensFrustum[2]; w = noLensFrustum[2] - noLensFrustum[0]; noLensFrustum[0] = -(w + noLensFrustum[0]); noLensFrustum[2] = w - noLensFrustum[2]; viewport.x = 1 - (viewport.x + viewport.width); } } private static Color[] ComputeMeshColors(int width, int height, Vector2[] tex, int[] indices, bool distortVertices) { Color[] colors = new Color[2 * width * height]; for (int e = 0, vidx = 0; e < 2; e++) { for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++, vidx++) { colors[vidx] = Color.white; if (distortVertices) { if (i == 0 || j == 0 || i == (width - 1) || j == (height - 1)) { colors[vidx] = Color.black; } } else { Vector2 t = tex[vidx]; t.x = Mathf.Abs(t.x * 2 - 1); if (t.x <= 0 || t.y <= 0 || t.x >= 1 || t.y >= 1) { colors[vidx] = Color.black; } } } } } return colors; } private static int[] ComputeMeshIndices(int width, int height, bool distortVertices) { int[] indices = new int[2 * (width - 1) * (height - 1) * 6]; int halfwidth = width / 2; int halfheight = height / 2; for (int e = 0, vidx = 0, iidx = 0; e < 2; e++) { for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++, vidx++) { if (i == 0 || j == 0) continue; // Build a quad. Lower right and upper left quadrants have quads with the triangle // diagonal flipped to get the vignette to interpolate correctly. if ((i <= halfwidth) == (j <= halfheight)) { // Quad diagonal lower left to upper right. indices[iidx++] = vidx; indices[iidx++] = vidx - width; indices[iidx++] = vidx - width - 1; indices[iidx++] = vidx - width - 1; indices[iidx++] = vidx - 1; indices[iidx++] = vidx; } else { // Quad diagonal upper left to lower right. indices[iidx++] = vidx - 1; indices[iidx++] = vidx; indices[iidx++] = vidx - width; indices[iidx++] = vidx - width; indices[iidx++] = vidx - width - 1; indices[iidx++] = vidx - 1; } } } } return indices; } private void DrawUILayer() { bool vrMode = GvrViewer.Instance.VRModeEnabled; if (Application.isEditor) { ComputeUIMatrix(); } uiMaterial.SetPass(0); DrawSettingsButton(); DrawAlignmentMarker(); if (vrMode) { DrawVRBackButton(); } } // The gear has 6 identical sections, each spanning 60 degrees. private const float kAnglePerGearSection = 60; // Half-angle of the span of the outer rim. private const float kOuterRimEndAngle = 12; // Angle between the middle of the outer rim and the start of the inner rim. private const float kInnerRimBeginAngle = 20; // Distance from center to outer rim, normalized so that the entire model // fits in a [-1, 1] x [-1, 1] square. private const float kOuterRadius = 1; // Distance from center to depressed rim, in model units. private const float kMiddleRadius = 0.75f; // Radius of the inner hollow circle, in model units. private const float kInnerRadius = 0.3125f; // Center line thickness in DP. private const float kCenterLineThicknessDp = 4; // Button width in DP. private const int kButtonWidthDp = 28; // Factor to scale the touch area that responds to the touch. private const float kTouchSlopFactor = 1.5f; private static readonly float[] Angles = { 0, kOuterRimEndAngle, kInnerRimBeginAngle, kAnglePerGearSection - kInnerRimBeginAngle, kAnglePerGearSection - kOuterRimEndAngle }; private void ComputeUIMatrix() { centerWidthPx = kCenterLineThicknessDp / 160.0f * Screen.dpi / 2; buttonWidthPx = kButtonWidthDp / 160.0f * Screen.dpi / 2; xScale = buttonWidthPx / Screen.width; yScale = buttonWidthPx / Screen.height; xfm = Matrix4x4.TRS(new Vector3(0.5f, yScale, 0), Quaternion.identity, new Vector3(xScale, yScale, 1)); } private void DrawSettingsButton() { GL.PushMatrix(); GL.LoadOrtho(); GL.MultMatrix(xfm); GL.Begin(GL.TRIANGLE_STRIP); for (int i = 0, n = Angles.Length * 6; i <= n; i++) { float theta = (i / Angles.Length) * kAnglePerGearSection + Angles[i % Angles.Length]; float angle = (90 - theta) * Mathf.Deg2Rad; float x = Mathf.Cos(angle); float y = Mathf.Sin(angle); float mod = Mathf.PingPong(theta, kAnglePerGearSection / 2); float lerp = (mod - kOuterRimEndAngle) / (kInnerRimBeginAngle - kOuterRimEndAngle); float r = Mathf.Lerp(kOuterRadius, kMiddleRadius, lerp); GL.Vertex3(kInnerRadius * x, kInnerRadius * y, 0); GL.Vertex3(r * x, r * y, 0); } GL.End(); GL.PopMatrix(); } private void DrawAlignmentMarker() { int x = Screen.width / 2; int w = (int)centerWidthPx; int h = (int)(2 * kTouchSlopFactor * buttonWidthPx); GL.PushMatrix(); GL.LoadPixelMatrix(0, Screen.width, 0, Screen.height); GL.Begin(GL.QUADS); GL.Vertex3(x - w, h, 0); GL.Vertex3(x - w, Screen.height - h, 0); GL.Vertex3(x + w, Screen.height - h, 0); GL.Vertex3(x + w, h, 0); GL.End(); GL.PopMatrix(); } private void DrawVRBackButton() { } }
// Generated by ProtoGen, Version=2.4.1.555, Culture=neutral, PublicKeyToken=55f7125234beb589. DO NOT EDIT! #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.ProtocolBuffers; using pbc = global::Google.ProtocolBuffers.Collections; using pbd = global::Google.ProtocolBuffers.Descriptors; using scg = global::System.Collections.Generic; namespace Google.ProtocolBuffers.TestProtos.NoGenericService { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class UnitTestNoGenericServicesProtoFile { #region Extension registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { registry.Add(global::Google.ProtocolBuffers.TestProtos.NoGenericService.UnitTestNoGenericServicesProtoFile.TestExtension); } #endregion #region Extensions public const int TestExtensionFieldNumber = 1000; public static pb::GeneratedExtensionBase<int> TestExtension; #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_google_protobuf_no_generic_services_test_TestMessage__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage, global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage.Builder> internal__static_google_protobuf_no_generic_services_test_TestMessage__FieldAccessorTable; #endregion #region Descriptor public static pbd::FileDescriptor Descriptor { get { return descriptor; } } private static pbd::FileDescriptor descriptor; static UnitTestNoGenericServicesProtoFile() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjJnb29nbGUvcHJvdG9idWYvdW5pdHRlc3Rfbm9fZ2VuZXJpY19zZXJ2aWNl", "cy5wcm90bxIoZ29vZ2xlLnByb3RvYnVmLm5vX2dlbmVyaWNfc2VydmljZXNf", "dGVzdBokZ29vZ2xlL3Byb3RvYnVmL2NzaGFycF9vcHRpb25zLnByb3RvIiMK", "C1Rlc3RNZXNzYWdlEgkKAWEYASABKAUqCQjoBxCAgICAAioTCghUZXN0RW51", "bRIHCgNGT08QATKCAQoLVGVzdFNlcnZpY2UScwoDRm9vEjUuZ29vZ2xlLnBy", "b3RvYnVmLm5vX2dlbmVyaWNfc2VydmljZXNfdGVzdC5UZXN0TWVzc2FnZRo1", "Lmdvb2dsZS5wcm90b2J1Zi5ub19nZW5lcmljX3NlcnZpY2VzX3Rlc3QuVGVz", "dE1lc3NhZ2U6TgoOdGVzdF9leHRlbnNpb24SNS5nb29nbGUucHJvdG9idWYu", "bm9fZ2VuZXJpY19zZXJ2aWNlc190ZXN0LlRlc3RNZXNzYWdlGOgHIAEoBUJb", "wj5YCjJHb29nbGUuUHJvdG9jb2xCdWZmZXJzLlRlc3RQcm90b3MuTm9HZW5l", "cmljU2VydmljZRIiVW5pdFRlc3ROb0dlbmVyaWNTZXJ2aWNlc1Byb3RvRmls", "ZQ==")); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_google_protobuf_no_generic_services_test_TestMessage__Descriptor = Descriptor.MessageTypes[0]; internal__static_google_protobuf_no_generic_services_test_TestMessage__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage, global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage.Builder>(internal__static_google_protobuf_no_generic_services_test_TestMessage__Descriptor, new string[] { "A", }); global::Google.ProtocolBuffers.TestProtos.NoGenericService.UnitTestNoGenericServicesProtoFile.TestExtension = pb::GeneratedSingleExtension<int>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.NoGenericService.UnitTestNoGenericServicesProtoFile.Descriptor.Extensions[0]); pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance(); RegisterAllExtensions(registry); global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.RegisterAllExtensions(registry); return registry; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.Descriptor, }, assigner); } #endregion } #region Enums public enum TestEnum { FOO = 1, } #endregion #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class TestMessage : pb::ExtendableMessage<TestMessage, TestMessage.Builder> { private TestMessage() { } private static readonly TestMessage defaultInstance = new TestMessage().MakeReadOnly(); private static readonly string[] _testMessageFieldNames = new string[] { "a" }; private static readonly uint[] _testMessageFieldTags = new uint[] { 8 }; public static TestMessage DefaultInstance { get { return defaultInstance; } } public override TestMessage DefaultInstanceForType { get { return DefaultInstance; } } protected override TestMessage ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::Google.ProtocolBuffers.TestProtos.NoGenericService.UnitTestNoGenericServicesProtoFile.internal__static_google_protobuf_no_generic_services_test_TestMessage__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<TestMessage, TestMessage.Builder> InternalFieldAccessors { get { return global::Google.ProtocolBuffers.TestProtos.NoGenericService.UnitTestNoGenericServicesProtoFile.internal__static_google_protobuf_no_generic_services_test_TestMessage__FieldAccessorTable; } } public const int AFieldNumber = 1; private bool hasA; private int a_; public bool HasA { get { return hasA; } } public int A { get { return a_; } } public override bool IsInitialized { get { if (!ExtensionsAreInitialized) return false; return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _testMessageFieldNames; pb::ExtendableMessage<TestMessage, TestMessage.Builder>.ExtensionWriter extensionWriter = CreateExtensionWriter(this); if (hasA) { output.WriteInt32(1, field_names[0], A); } extensionWriter.WriteUntil(536870912, output); UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasA) { size += pb::CodedOutputStream.ComputeInt32Size(1, A); } size += ExtensionsSerializedSize; size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } public static TestMessage ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static TestMessage ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static TestMessage ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static TestMessage ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static TestMessage ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static TestMessage ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static TestMessage ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static TestMessage ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static TestMessage ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static TestMessage ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private TestMessage MakeReadOnly() { return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(TestMessage prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::ExtendableBuilder<TestMessage, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(TestMessage cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private TestMessage result; private TestMessage PrepareBuilder() { if (resultIsReadOnly) { TestMessage original = result; result = new TestMessage(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override TestMessage MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage.Descriptor; } } public override TestMessage DefaultInstanceForType { get { return global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage.DefaultInstance; } } public override TestMessage BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is TestMessage) { return MergeFrom((TestMessage) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(TestMessage other) { if (other == global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage.DefaultInstance) return this; PrepareBuilder(); if (other.HasA) { A = other.A; } this.MergeExtensionFields(other); this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_testMessageFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _testMessageFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 8: { result.hasA = input.ReadInt32(ref result.a_); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasA { get { return result.hasA; } } public int A { get { return result.A; } set { SetA(value); } } public Builder SetA(int value) { PrepareBuilder(); result.hasA = true; result.a_ = value; return this; } public Builder ClearA() { PrepareBuilder(); result.hasA = false; result.a_ = 0; return this; } } static TestMessage() { object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.NoGenericService.UnitTestNoGenericServicesProtoFile.Descriptor, null); } } #endregion #region Services /* * Service generation is now disabled by default, use the following option to enable: * option (google.protobuf.csharp_file_options).service_generator_type = GENERIC; */ #endregion } #endregion Designer generated code
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #if XMLSERIALIZERGENERATOR namespace Microsoft.XmlSerializer.Generator #else namespace System.Xml.Serialization #endif { using System.IO; using System.Collections; using System.Text; using System; using System.Xml.Schema; using System.Xml; internal class XmlCountingReader : XmlReader, IXmlTextParser, IXmlLineInfo { private XmlReader _innerReader; private int _advanceCount; internal XmlCountingReader(XmlReader xmlReader) { if (xmlReader == null) throw new ArgumentNullException(nameof(xmlReader)); _innerReader = xmlReader; _advanceCount = 0; } internal int AdvanceCount { get { return _advanceCount; } } private void IncrementCount() { if (_advanceCount == Int32.MaxValue) _advanceCount = 0; else _advanceCount++; } // Properties (non-advancing) public override XmlReaderSettings Settings { get { return _innerReader.Settings; } } public override XmlNodeType NodeType { get { return _innerReader.NodeType; } } public override string Name { get { return _innerReader.Name; } } public override string LocalName { get { return _innerReader.LocalName; } } public override string NamespaceURI { get { return _innerReader.NamespaceURI; } } public override string Prefix { get { return _innerReader.Prefix; } } public override bool HasValue { get { return _innerReader.HasValue; } } public override string Value { get { return _innerReader.Value; } } public override int Depth { get { return _innerReader.Depth; } } public override string BaseURI { get { return _innerReader.BaseURI; } } public override bool IsEmptyElement { get { return _innerReader.IsEmptyElement; } } public override bool IsDefault { get { return _innerReader.IsDefault; } } public override char QuoteChar { get { return _innerReader.QuoteChar; } } public override XmlSpace XmlSpace { get { return _innerReader.XmlSpace; } } public override string XmlLang { get { return _innerReader.XmlLang; } } public override IXmlSchemaInfo SchemaInfo { get { return _innerReader.SchemaInfo; } } public override Type ValueType { get { return _innerReader.ValueType; } } public override int AttributeCount { get { return _innerReader.AttributeCount; } } public override string this[int i] { get { return _innerReader[i]; } } public override string this[string name, string namespaceURI] { get { return _innerReader[name, namespaceURI]; } } public override bool EOF { get { return _innerReader.EOF; } } public override ReadState ReadState { get { return _innerReader.ReadState; } } public override XmlNameTable NameTable { get { return _innerReader.NameTable; } } public override bool CanResolveEntity { get { return _innerReader.CanResolveEntity; } } public override bool CanReadBinaryContent { get { return _innerReader.CanReadBinaryContent; } } public override bool CanReadValueChunk { get { return _innerReader.CanReadValueChunk; } } public override bool HasAttributes { get { return _innerReader.HasAttributes; } } // Methods (non-advancing) // Reader tends to under-count rather than over-count public override void Close() { _innerReader.Close(); } public override string GetAttribute(string name) { return _innerReader.GetAttribute(name); } public override string GetAttribute(string name, string namespaceURI) { return _innerReader.GetAttribute(name, namespaceURI); } public override string GetAttribute(int i) { return _innerReader.GetAttribute(i); } public override bool MoveToAttribute(string name) { return _innerReader.MoveToAttribute(name); } public override bool MoveToAttribute(string name, string ns) { return _innerReader.MoveToAttribute(name, ns); } public override void MoveToAttribute(int i) { _innerReader.MoveToAttribute(i); } public override bool MoveToFirstAttribute() { return _innerReader.MoveToFirstAttribute(); } public override bool MoveToNextAttribute() { return _innerReader.MoveToNextAttribute(); } public override bool MoveToElement() { return _innerReader.MoveToElement(); } public override string LookupNamespace(string prefix) { return _innerReader.LookupNamespace(prefix); } public override bool ReadAttributeValue() { return _innerReader.ReadAttributeValue(); } public override void ResolveEntity() { _innerReader.ResolveEntity(); } public override bool IsStartElement() { return _innerReader.IsStartElement(); } public override bool IsStartElement(string name) { return _innerReader.IsStartElement(name); } public override bool IsStartElement(string localname, string ns) { return _innerReader.IsStartElement(localname, ns); } public override XmlReader ReadSubtree() { return _innerReader.ReadSubtree(); } public override XmlNodeType MoveToContent() { return _innerReader.MoveToContent(); } // Methods (advancing) public override bool Read() { IncrementCount(); return _innerReader.Read(); } public override void Skip() { IncrementCount(); _innerReader.Skip(); } public override string ReadInnerXml() { if (_innerReader.NodeType != XmlNodeType.Attribute) IncrementCount(); return _innerReader.ReadInnerXml(); } public override string ReadOuterXml() { if (_innerReader.NodeType != XmlNodeType.Attribute) IncrementCount(); return _innerReader.ReadOuterXml(); } public override object ReadContentAsObject() { IncrementCount(); return _innerReader.ReadContentAsObject(); } public override bool ReadContentAsBoolean() { IncrementCount(); return _innerReader.ReadContentAsBoolean(); } public override DateTime ReadContentAsDateTime() { IncrementCount(); return _innerReader.ReadContentAsDateTime(); } public override double ReadContentAsDouble() { IncrementCount(); return _innerReader.ReadContentAsDouble(); } public override int ReadContentAsInt() { IncrementCount(); return _innerReader.ReadContentAsInt(); } public override long ReadContentAsLong() { IncrementCount(); return _innerReader.ReadContentAsLong(); } public override string ReadContentAsString() { IncrementCount(); return _innerReader.ReadContentAsString(); } public override object ReadContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver) { IncrementCount(); return _innerReader.ReadContentAs(returnType, namespaceResolver); } public override object ReadElementContentAsObject() { IncrementCount(); return _innerReader.ReadElementContentAsObject(); } public override object ReadElementContentAsObject(string localName, string namespaceURI) { IncrementCount(); return _innerReader.ReadElementContentAsObject(localName, namespaceURI); } public override bool ReadElementContentAsBoolean() { IncrementCount(); return _innerReader.ReadElementContentAsBoolean(); } public override bool ReadElementContentAsBoolean(string localName, string namespaceURI) { IncrementCount(); return _innerReader.ReadElementContentAsBoolean(localName, namespaceURI); } public override DateTime ReadElementContentAsDateTime() { IncrementCount(); return _innerReader.ReadElementContentAsDateTime(); } public override DateTime ReadElementContentAsDateTime(string localName, string namespaceURI) { IncrementCount(); return _innerReader.ReadElementContentAsDateTime(localName, namespaceURI); } public override double ReadElementContentAsDouble() { IncrementCount(); return _innerReader.ReadElementContentAsDouble(); } public override double ReadElementContentAsDouble(string localName, string namespaceURI) { IncrementCount(); return _innerReader.ReadElementContentAsDouble(localName, namespaceURI); } public override int ReadElementContentAsInt() { IncrementCount(); return _innerReader.ReadElementContentAsInt(); } public override int ReadElementContentAsInt(string localName, string namespaceURI) { IncrementCount(); return _innerReader.ReadElementContentAsInt(localName, namespaceURI); } public override long ReadElementContentAsLong() { IncrementCount(); return _innerReader.ReadElementContentAsLong(); } public override long ReadElementContentAsLong(string localName, string namespaceURI) { IncrementCount(); return _innerReader.ReadElementContentAsLong(localName, namespaceURI); } public override string ReadElementContentAsString() { IncrementCount(); return _innerReader.ReadElementContentAsString(); } public override string ReadElementContentAsString(string localName, string namespaceURI) { IncrementCount(); return _innerReader.ReadElementContentAsString(localName, namespaceURI); } public override object ReadElementContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver) { IncrementCount(); return _innerReader.ReadElementContentAs(returnType, namespaceResolver); } public override object ReadElementContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver, string localName, string namespaceURI) { IncrementCount(); return _innerReader.ReadElementContentAs(returnType, namespaceResolver, localName, namespaceURI); } public override int ReadContentAsBase64(byte[] buffer, int index, int count) { IncrementCount(); return _innerReader.ReadContentAsBase64(buffer, index, count); } public override int ReadElementContentAsBase64(byte[] buffer, int index, int count) { IncrementCount(); return _innerReader.ReadElementContentAsBase64(buffer, index, count); } public override int ReadContentAsBinHex(byte[] buffer, int index, int count) { IncrementCount(); return _innerReader.ReadContentAsBinHex(buffer, index, count); } public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { IncrementCount(); return _innerReader.ReadElementContentAsBinHex(buffer, index, count); } public override int ReadValueChunk(char[] buffer, int index, int count) { IncrementCount(); return _innerReader.ReadValueChunk(buffer, index, count); } public override string ReadString() { IncrementCount(); return _innerReader.ReadString(); } public override void ReadStartElement() { IncrementCount(); _innerReader.ReadStartElement(); } public override void ReadStartElement(string name) { IncrementCount(); _innerReader.ReadStartElement(name); } public override void ReadStartElement(string localname, string ns) { IncrementCount(); _innerReader.ReadStartElement(localname, ns); } public override string ReadElementString() { IncrementCount(); return _innerReader.ReadElementString(); } public override string ReadElementString(string name) { IncrementCount(); return _innerReader.ReadElementString(name); } public override string ReadElementString(string localname, string ns) { IncrementCount(); return _innerReader.ReadElementString(localname, ns); } public override void ReadEndElement() { IncrementCount(); _innerReader.ReadEndElement(); } public override bool ReadToFollowing(string name) { IncrementCount(); return ReadToFollowing(name); } public override bool ReadToFollowing(string localName, string namespaceURI) { IncrementCount(); return _innerReader.ReadToFollowing(localName, namespaceURI); } public override bool ReadToDescendant(string name) { IncrementCount(); return _innerReader.ReadToDescendant(name); } public override bool ReadToDescendant(string localName, string namespaceURI) { IncrementCount(); return _innerReader.ReadToDescendant(localName, namespaceURI); } public override bool ReadToNextSibling(string name) { IncrementCount(); return _innerReader.ReadToNextSibling(name); } public override bool ReadToNextSibling(string localName, string namespaceURI) { IncrementCount(); return _innerReader.ReadToNextSibling(localName, namespaceURI); } // IDisposable interface protected override void Dispose(bool disposing) { try { if (disposing) { IDisposable disposableReader = _innerReader as IDisposable; if (disposableReader != null) disposableReader.Dispose(); } } finally { base.Dispose(disposing); } } // IXmlTextParser members bool IXmlTextParser.Normalized { get { XmlTextReader xmlTextReader = _innerReader as XmlTextReader; if (xmlTextReader == null) { IXmlTextParser xmlTextParser = _innerReader as IXmlTextParser; return (xmlTextParser == null) ? false : xmlTextParser.Normalized; } else return xmlTextReader.Normalization; } set { XmlTextReader xmlTextReader = _innerReader as XmlTextReader; if (xmlTextReader == null) { IXmlTextParser xmlTextParser = _innerReader as IXmlTextParser; if (xmlTextParser != null) xmlTextParser.Normalized = value; } else xmlTextReader.Normalization = value; } } WhitespaceHandling IXmlTextParser.WhitespaceHandling { get { XmlTextReader xmlTextReader = _innerReader as XmlTextReader; if (xmlTextReader == null) { IXmlTextParser xmlTextParser = _innerReader as IXmlTextParser; return (xmlTextParser == null) ? WhitespaceHandling.None : xmlTextParser.WhitespaceHandling; } else return xmlTextReader.WhitespaceHandling; } set { XmlTextReader xmlTextReader = _innerReader as XmlTextReader; if (xmlTextReader == null) { IXmlTextParser xmlTextParser = _innerReader as IXmlTextParser; if (xmlTextParser != null) xmlTextParser.WhitespaceHandling = value; } else xmlTextReader.WhitespaceHandling = value; } } // IXmlLineInfo members bool IXmlLineInfo.HasLineInfo() { IXmlLineInfo iXmlLineInfo = _innerReader as IXmlLineInfo; return (iXmlLineInfo == null) ? false : iXmlLineInfo.HasLineInfo(); } int IXmlLineInfo.LineNumber { get { IXmlLineInfo iXmlLineInfo = _innerReader as IXmlLineInfo; return (iXmlLineInfo == null) ? 0 : iXmlLineInfo.LineNumber; } } int IXmlLineInfo.LinePosition { get { IXmlLineInfo iXmlLineInfo = _innerReader as IXmlLineInfo; return (iXmlLineInfo == null) ? 0 : iXmlLineInfo.LinePosition; } } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.IO; using NPNF; using NPNF.Core.Users.Tracking; using NPNF.Core.Analytics; using NPNF.Core.Utils; using NPNF.Admin; using NPNF.Core; using System.Text.RegularExpressions; using System.Diagnostics; #if !UNITY_WEBPLAYER using System.Net.NetworkInformation; #endif #if UNITY_EDITOR using UnityEditor; [InitializeOnLoad] #endif public class NPNFSettings : ScriptableObject, INPNFSettings, IAdminSettings { private static NPNFSettings instance; public const string SDK_VERSION = "1.5.6"; private const string OS_MACOSX = "Mac OS X"; private const string USER_ID = "npnfsettings_manager"; private const string npnfSettingsAssetName = "NPNFSettings"; private const string npnfSettingsPath = "NPNF/Resources"; private const string npnfSettingsAssetExtension = ".asset"; private AdminManager mAdmin; private CoroutineQueue mQueue; #if !UNITY_EDITOR [NonSerialized] private GameObject bridgeObject = null; #endif #if !UNITY_EDITOR && UNITY_IPHONE [NonSerialized] public UnityBridgeIOSPlugin bridge; #elif !UNITY_EDITOR && UNITY_ANDROID [NonSerialized] public UnityBridgeAndroidPlugin bridge; #else [NonSerialized] public UnityBridgePlugin bridge; #endif public static NPNFSettings Instance { get { if (instance == null) { instance = Resources.Load(npnfSettingsAssetName) as NPNFSettings; if (instance == null) { // If not found, create the asset object instance = CreateInstance<NPNFSettings>(); #if UNITY_EDITOR string properPath = Path.Combine(Application.dataPath, npnfSettingsPath); if (!Directory.Exists(properPath)) { AssetDatabase.CreateFolder("Assets/NPNF", "Resources"); } string fullPath = Path.Combine(Path.Combine("Assets", npnfSettingsPath), npnfSettingsAssetName + npnfSettingsAssetExtension); AssetDatabase.CreateAsset(instance, fullPath); #endif } instance.Load(); } return instance; } } private void CreateAdminManager() { mAdmin = AdminManager.Create(this, this, USER_ID, mQueue); } public void GetVersions(Action<List<NPNF.Core.Configuration.Version>, NPNFError> callback) { CreateAdminManager(); mAdmin.GetAllVersions((List<NPNF.Core.Configuration.Version> versions, NPNFError error) => { callback(versions, error); }); } // Callback will be called once for each type of validation (app, admin, version) public void VerifyAppSettings(Action<AdminManager.SettingsType, bool> callback) { CreateAdminManager(); mAdmin.VerifyAppSettings((AdminManager.SettingsType type, bool isValid) => { callback(type, isValid); }); } public void VerifyAppKeys(Action<NPNFError> callback) { AdminManager.VerifyKeys(appId, appSecret, isUsingProduction, mQueue, callback); } public void Update() { if (mQueue != null) { mQueue.Update(); } } #region Device Profile private void InitDeviceProfile() { #if !UNITY_EDITOR InitBridge(); #if (UNITY_IPHONE || UNITY_ANDROID) Platform.utController = new UserTrackingController (bridge); NPNFMain.UTController = Platform.utController; NPNF.NPNFBridge.Instance.UnityBridge = bridge; #endif #endif #if UNITY_EDITOR || UNITY_WEBPLAYER || UNITY_STANDALONE DeviceProfile = new DeviceProfile(); DeviceProfile.deviceIdentity["userAgent"] = "UserAgent"; // set mac address string macAddress = GetMacAddress(UnityEngine.Network.player.ipAddress); Dictionary<string, object> deviceIds = DeviceProfile.deviceIdentity[DeviceProfile.IDKEY_DEVICEIDS] as Dictionary<string, object>; deviceIds.Add("macAddress", macAddress); #elif UNITY_IPHONE DeviceProfile = new IOSDeviceProfile(); ((IOSDeviceProfile) DeviceProfile).SetiOSDeviceInfo (bridge.GetIDFA (), bridge.GetIDFV (), bridge.GetUserAgent ()); #elif UNITY_ANDROID DeviceProfile = new AndroidDeviceProfile(); ((AndroidDeviceProfile) DeviceProfile).SetAndroidDeviceInfo (bridge.GetUserAgent ()); #else DeviceProfile = new DeviceProfile(); #endif } private string GetMacAddress(string ipAddress) { #if UNITY_WEBPLAYER return "WEBPLAYER"; #else string os = UnityEngine.SystemInfo.operatingSystem; string macAddress = ""; const string macAddressPattern = @"ether (?<mac>([0-9A-F]{2}[:-]){5}([0-9A-F]{2}))"; string ipAddressPattern = "inet " + ipAddress; Regex macAddrRegex = new Regex(macAddressPattern, RegexOptions.IgnoreCase); if (os.Contains(OS_MACOSX)) { ProcessStartInfo startInfo = new ProcessStartInfo("ifconfig"); startInfo.UseShellExecute = false; startInfo.RedirectStandardInput = true; startInfo.RedirectStandardOutput = true; var proc = new Process(); proc.StartInfo = startInfo; proc.Start(); string line = proc.StandardOutput.ReadLine(); while (line != null) { MatchCollection matches = macAddrRegex.Matches(line); if (matches.Count > 0) { macAddress = matches [0].Groups ["mac"].Value; } if (line.Contains(ipAddressPattern)) break; line = proc.StandardOutput.ReadLine(); } proc.WaitForExit(); } else { // Ref: http://msdn.microsoft.com/en-us/library/system.net.networkinformation.physicaladdress(v=vs.110).aspx NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in nics) { PhysicalAddress address = adapter.GetPhysicalAddress(); if (address != null) { macAddress = address.ToString(); break; } } } macAddress = macAddress.Replace(":", ""); return macAddress; #endif } #if !UNITY_EDITOR private void InitBridge() { if (bridge == null) { bridgeObject = new GameObject(); bridgeObject.name = "NPNFUnityBridgePlugin"; #if UNITY_IPHONE bridgeObject.AddComponent<UnityBridgeIOSPlugin> (); bridge = bridgeObject.GetComponent<UnityBridgeIOSPlugin> (); bridge.Init (bridgeObject.name); #elif UNITY_ANDROID bridgeObject.AddComponent<UnityBridgeAndroidPlugin>(); bridge = bridgeObject.GetComponent<UnityBridgeAndroidPlugin>(); bridge.Init(bridgeObject.name); #endif } } public void AddBridgeComponent<T>() where T:UnityEngine.Component { bridgeObject.AddComponent<T>(); } public T GetBridgeComponent<T>() where T:UnityEngine.Component { return bridgeObject.GetComponent<T>(); } public void RefreshDeviceProfile() { #if UNITY_IPHONE IOSDeviceProfile devProfile = new IOSDeviceProfile (); devProfile.SetiOSDeviceInfo (bridge.GetIDFA (), bridge.GetIDFV (), bridge.GetUserAgent ()); DeviceProfile.deviceIdentity = devProfile.deviceIdentity; #endif #if UNITY_ANDROID AndroidDeviceProfile devProfile = new AndroidDeviceProfile (); devProfile.SetAndroidDeviceInfo (bridge.GetUserAgent ()); DeviceProfile.deviceIdentity = devProfile.deviceIdentity; #endif } #endif #endregion #if UNITY_EDITOR [MenuItem("NPNF/Edit Settings")] public static void Edit() { Selection.activeObject = Instance; } #endif #region App Settings public void Load() { Analytics = new NPNFAnalytics(); mQueue = new CoroutineQueue(); InitDeviceProfile(); } public INPNFAnalytics Analytics { get; set; } public DeviceProfile DeviceProfile { get; private set; } public static bool IsValidVersion() { return NPNF.Core.Configuration.ConfigurationManager.IsPlatformVersionValid(NPNFSettings.SDK_VERSION); } [SerializeField] private string appVersion = ""; public string AppVersion { get { return Instance.appVersion; } set { if (Instance.appVersion != value) { Instance.appVersion = value; DirtyEditor(); } } } [SerializeField] private string appId = ""; public string AppId { get { return Instance.appId; } set { if (Instance.appId != value) { Instance.appId = value; DirtyEditor(); } } } [SerializeField] public string appSecret; public string AppSecret { get { return Instance.appSecret; } set { if (Instance.appSecret != value) { Instance.appSecret = value; DirtyEditor(); } } } [SerializeField] private string adminId = ""; public string AdminId { get { return Instance.adminId; } set { if (Instance.adminId != value) { Instance.adminId = value; DirtyEditor(); } } } [SerializeField] public string adminSecret; public string AdminSecret { get { return Instance.adminSecret; } set { if (Instance.adminSecret != value) { Instance.adminSecret = value; DirtyEditor(); } } } [SerializeField] private string androidGCMSenderID; public string AndroidGCMSenderID { get { return Instance.androidGCMSenderID; } set { if (Instance.androidGCMSenderID != value) { Instance.androidGCMSenderID = value; DirtyEditor(); } } } [SerializeField] private bool isUsingProduction; internal bool IsUsingProduction { get { return Instance.isUsingProduction; } set { if (Instance.isUsingProduction != value) { Instance.isUsingProduction = value; DirtyEditor(); } } } [SerializeField] private string[] clientVersions; public string[] ClientVersions { get { return Instance.clientVersions; } set { if (Instance.clientVersions != value) { Instance.clientVersions = value; DirtyEditor(); } } } [SerializeField] private int selectedVersionIndex; public int SelectedVersionIndex { get { return Instance.selectedVersionIndex; } set { if (Instance.selectedVersionIndex != value) { Instance.selectedVersionIndex = value; DirtyEditor(); } } } private static void DirtyEditor () { #if UNITY_EDITOR EditorUtility.SetDirty(Instance); #endif } #endregion }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Web.Http.Controllers; using System.Web.Http.Description; using System.Xml.XPath; using WebHost.Areas.HelpPage.ModelDescriptions; namespace WebHost.Areas.HelpPage { /// <summary> /// A custom <see cref="IDocumentationProvider"/> that reads the API documentation from an XML documentation file. /// </summary> public class XmlDocumentationProvider : IDocumentationProvider, IModelDocumentationProvider { private List<XPathNavigator> _documentNavigators = new List<XPathNavigator>(); private const string TypeExpression = "/doc/members/member[@name='T:{0}']"; private const string MethodExpression = "/doc/members/member[@name='M:{0}']"; private const string PropertyExpression = "/doc/members/member[@name='P:{0}']"; private const string FieldExpression = "/doc/members/member[@name='F:{0}']"; private const string ParameterExpression = "param[@name='{0}']"; /// <summary> /// Initializes a new instance of the <see cref="XmlDocumentationProvider"/> class. /// </summary> /// <param name="appDataPath">The physical path to App_Data folder.</param> public XmlDocumentationProvider(string appDataPath) { if (appDataPath == null) { throw new ArgumentNullException("appDataPath"); } foreach (var file in Directory.GetFiles(appDataPath, "*.xml")) { XPathDocument xpath = new XPathDocument(Path.Combine(appDataPath, file)); _documentNavigators.Add(xpath.CreateNavigator()); } } /// <summary> /// /// </summary> /// <param name="selectExpression"></param> /// <returns></returns> private XPathNavigator SelectSingleNode(string selectExpression) { foreach (var navigator in _documentNavigators) { var propertyNode = navigator.SelectSingleNode(selectExpression); if (propertyNode != null) return propertyNode; } return null; } /// <summary> /// /// </summary> /// <param name="controllerDescriptor"></param> /// <returns></returns> public string GetDocumentation(HttpControllerDescriptor controllerDescriptor) { XPathNavigator typeNode = GetTypeNode(controllerDescriptor.ControllerType); return GetTagValue(typeNode, "summary"); } /// <summary> /// /// </summary> /// <param name="actionDescriptor"></param> /// <returns></returns> public virtual string GetDocumentation(HttpActionDescriptor actionDescriptor) { XPathNavigator methodNode = GetMethodNode(actionDescriptor); return GetTagValue(methodNode, "summary"); } /// <summary> /// /// </summary> /// <param name="parameterDescriptor"></param> /// <returns></returns> public virtual string GetDocumentation(HttpParameterDescriptor parameterDescriptor) { ReflectedHttpParameterDescriptor reflectedParameterDescriptor = parameterDescriptor as ReflectedHttpParameterDescriptor; if (reflectedParameterDescriptor != null) { XPathNavigator methodNode = GetMethodNode(reflectedParameterDescriptor.ActionDescriptor); if (methodNode != null) { string parameterName = reflectedParameterDescriptor.ParameterInfo.Name; XPathNavigator parameterNode = methodNode.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, ParameterExpression, parameterName)); if (parameterNode != null) { return parameterNode.Value.Trim(); } } } return null; } /// <summary> /// /// </summary> /// <param name="actionDescriptor"></param> /// <returns></returns> public string GetResponseDocumentation(HttpActionDescriptor actionDescriptor) { XPathNavigator methodNode = GetMethodNode(actionDescriptor); return GetTagValue(methodNode, "returns"); } /// <summary> /// /// </summary> /// <param name="member"></param> /// <returns></returns> public string GetDocumentation(MemberInfo member) { string memberName = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(member.DeclaringType), member.Name); string expression = member.MemberType == MemberTypes.Field ? FieldExpression : PropertyExpression; string selectExpression = String.Format(CultureInfo.InvariantCulture, expression, memberName); XPathNavigator propertyNode = SelectSingleNode(selectExpression); return GetTagValue(propertyNode, "summary"); } /// <summary> /// /// </summary> /// <param name="type"></param> /// <returns></returns> public string GetDocumentation(Type type) { XPathNavigator typeNode = GetTypeNode(type); return GetTagValue(typeNode, "summary"); } private XPathNavigator GetMethodNode(HttpActionDescriptor actionDescriptor) { ReflectedHttpActionDescriptor reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor; if (reflectedActionDescriptor != null) { string selectExpression = String.Format(CultureInfo.InvariantCulture, MethodExpression, GetMemberName(reflectedActionDescriptor.MethodInfo)); return SelectSingleNode(selectExpression); } return null; } private static string GetMemberName(MethodInfo method) { string name = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(method.DeclaringType), method.Name); ParameterInfo[] parameters = method.GetParameters(); if (parameters.Length != 0) { string[] parameterTypeNames = parameters.Select(param => GetTypeName(param.ParameterType)).ToArray(); name += String.Format(CultureInfo.InvariantCulture, "({0})", String.Join(",", parameterTypeNames)); } return name; } private static string GetTagValue(XPathNavigator parentNode, string tagName) { if (parentNode != null) { XPathNavigator node = parentNode.SelectSingleNode(tagName); if (node != null) { return node.Value.Trim(); } } return null; } private XPathNavigator GetTypeNode(Type type) { string controllerTypeName = GetTypeName(type); string selectExpression = String.Format(CultureInfo.InvariantCulture, TypeExpression, controllerTypeName); return SelectSingleNode(selectExpression); } private static string GetTypeName(Type type) { string name = type.FullName; if (type.IsGenericType) { // Format the generic type name to something like: Generic{System.Int32,System.String} Type genericType = type.GetGenericTypeDefinition(); Type[] genericArguments = type.GetGenericArguments(); string genericTypeName = genericType.FullName; // Trim the generic parameter counts from the name genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); string[] argumentTypeNames = genericArguments.Select(t => GetTypeName(t)).ToArray(); name = String.Format(CultureInfo.InvariantCulture, "{0}{{{1}}}", genericTypeName, String.Join(",", argumentTypeNames)); } if (type.IsNested) { // Changing the nested type name from OuterType+InnerType to OuterType.InnerType to match the XML documentation syntax. name = name.Replace("+", "."); } return name; } } }
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 Contoso.Provisioning.Cloud.SyncWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Xml; using System.Xml.Linq; using Microsoft.Test.ModuleCore; using System.IO; namespace CoreXml.Test.XLinq { public partial class FunctionalTests : TestModule { public partial class XNodeBuilderTests : XLinqTestCase { public partial class NamespacehandlingWriterSanity : XLinqTestCase { #region helpers private string SaveXElementUsingXmlWriter(XElement elem, NamespaceHandling nsHandling) { StringWriter sw = new StringWriter(); using (XmlWriter w = XmlWriter.Create(sw, new XmlWriterSettings() { NamespaceHandling = nsHandling, OmitXmlDeclaration = true })) { elem.WriteTo(w); } sw.Dispose(); return sw.ToString(); } #endregion //[Variation(Desc = "1 level down", Priority = 0, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:p='nsp'><p:C xmlns:p='nsp'/></p:B></p:A>" })] //[Variation(Desc = "1 level down II.", Priority = 0, Params = new object[] { "<A><p:B xmlns:p='nsp'><p:C xmlns:p='nsp'/></p:B></A>" })] // start at not root node //[Variation(Desc = "2 levels down", Priority = 1, Params = new object[] { "<p:A xmlns:p='nsp'><B><p:C xmlns:p='nsp'/></B></p:A>" })] //[Variation(Desc = "2 levels down II.", Priority = 1, Params = new object[] { "<p:A xmlns:p='nsp'><B><C xmlns:p='nsp'/></B></p:A>" })] //[Variation(Desc = "2 levels down III.", Priority = 1, Params = new object[] { "<A xmlns:p='nsp'><B><p:C xmlns:p='nsp'/></B></A>" })] //[Variation(Desc = "Siblings", Priority = 2, Params = new object[] { "<A xmlns:p='nsp'><p:B xmlns:p='nsp'/><C xmlns:p='nsp'/><p:C xmlns:p='nsp'/></A>" })] //[Variation(Desc = "Children", Priority = 2, Params = new object[] { "<A xmlns:p='nsp'><p:B xmlns:p='nsp'><C xmlns:p='nsp'><p:C xmlns:p='nsp'/></C></p:B></A>" })] //[Variation(Desc = "Xml namespace I.", Priority = 3, Params = new object[] { "<A xmlns:xml='http://www.w3.org/XML/1998/namespace'/>" })] //[Variation(Desc = "Xml namespace II.", Priority = 3, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:p='nsp'><p:C xmlns:p='nsp' xmlns:xml='http://www.w3.org/XML/1998/namespace'/></p:B></p:A>" })] //[Variation(Desc = "Xml namespace III.", Priority = 3, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:xml='http://www.w3.org/XML/1998/namespace' xmlns:p='nsp'><p:C xmlns:p='nsp' xmlns:xml='http://www.w3.org/XML/1998/namespace'/></p:B></p:A>" })] //[Variation(Desc = "Default namespaces", Priority = 1, Params = new object[] { "<A xmlns='nsp'><p:B xmlns:p='nsp'><C xmlns='nsp' /></p:B></A>" })] //[Variation(Desc = "Not used NS declarations", Priority = 2, Params = new object[] { "<A xmlns='nsp' xmlns:u='not-used'><p:B xmlns:p='nsp'><C xmlns:u='not-used' xmlns='nsp' /></p:B></A>" })] //[Variation(Desc = "SameNS, different prefix", Priority = 2, Params = new object[] { "<p:A xmlns:p='nsp'><B xmlns:q='nsp'><p:C xmlns:p='nsp'/></B></p:A>" })] public void testFromTheRootNodeSimple() { string xml = CurrentChild.Params[0] as string; XElement elem = XElement.Parse(xml); // Write using XmlWriter in duplicate namespace decl. removal mode string removedByWriter = SaveXElementUsingXmlWriter(elem, NamespaceHandling.OmitDuplicates); // Remove the namespace decl. duplicates from the Xlinq tree (from a in elem.DescendantsAndSelf().Attributes() where a.IsNamespaceDeclaration && ((a.Name.LocalName == "xml" && (string)a == XNamespace.Xml.NamespaceName) || (from parentDecls in a.Parent.Ancestors().Attributes(a.Name) where parentDecls.IsNamespaceDeclaration && (string)parentDecls == (string)a select parentDecls).Any() ) select a).ToList().Remove(); // Write XElement using XmlWriter without omiting string removedByManual = SaveXElementUsingXmlWriter(elem, NamespaceHandling.Default); ReaderDiff.Compare(removedByWriter, removedByManual); } //[Variation(Desc = "Default ns parent autogenerated", Priority = 1)] public void testFromTheRootNodeTricky() { XElement e = new XElement("{nsp}A", new XElement("{nsp}B", new XAttribute("xmlns", "nsp"))); ReaderDiff.Compare(SaveXElementUsingXmlWriter(e, NamespaceHandling.OmitDuplicates), "<A xmlns='nsp'><B/></A>"); } //[Variation(Desc = "Conflicts: NS redefinition", Priority = 2, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:p='ns-other'><p:C xmlns:p='nsp'><D xmlns:p='nsp'/></p:C></p:B></p:A>", // "<p:A xmlns:p='nsp'><p:B xmlns:p='ns-other'><p:C xmlns:p='nsp'><D/></p:C></p:B></p:A>" })] //[Variation(Desc = "Conflicts: NS redefinition, default NS", Priority = 2, Params = new object[] { "<A xmlns='nsp'><B xmlns='ns-other'><C xmlns='nsp'><D xmlns='nsp'/></C></B></A>", // "<A xmlns='nsp'><B xmlns='ns-other'><C xmlns='nsp'><D/></C></B></A>" })] //[Variation(Desc = "Conflicts: NS redefinition, default NS II.", Priority = 2, Params = new object[] { "<A xmlns=''><B xmlns='ns-other'><C xmlns=''><D xmlns=''/></C></B></A>", // "<A><B xmlns='ns-other'><C xmlns=''><D/></C></B></A>" })] //[Variation(Desc = "Conflicts: NS undeclaration, default NS", Priority = 2, Params = new object[] { "<A xmlns='nsp'><B xmlns=''><C xmlns='nsp'><D xmlns='nsp'/></C></B></A>", // "<A xmlns='nsp'><B xmlns=''><C xmlns='nsp'><D/></C></B></A>" })] public void testConflicts() { XElement e1 = XElement.Parse(CurrentChild.Params[0] as string); ReaderDiff.Compare(SaveXElementUsingXmlWriter(e1, NamespaceHandling.OmitDuplicates), CurrentChild.Params[1] as string); } //[Variation(Desc = "Not from root", Priority = 1)] public void testFromChildNode1() { XElement e = new XElement("root", new XAttribute(XNamespace.Xmlns + "p1", "nsp"), new XElement("{nsp}A", new XElement("{nsp}B", new XAttribute("xmlns", "nsp")))); ReaderDiff.Compare(SaveXElementUsingXmlWriter(e.Element("{nsp}A"), NamespaceHandling.OmitDuplicates), "<p1:A xmlns:p1='nsp'><B xmlns='nsp'/></p1:A>"); } //[Variation(Desc = "Not from root II.", Priority = 1)] public void testFromChildNode2() { XElement e = new XElement("root", new XAttribute(XNamespace.Xmlns + "p1", "nsp"), new XElement("{nsp}A", new XElement("{nsp}B", new XAttribute(XNamespace.Xmlns + "p1", "nsp")))); ReaderDiff.Compare(SaveXElementUsingXmlWriter(e.Element("{nsp}A"), NamespaceHandling.OmitDuplicates), "<p1:A xmlns:p1='nsp'><p1:B/></p1:A>"); } //[Variation(Desc = "Not from root III.", Priority = 2)] public void testFromChildNode3() { XElement e = new XElement("root", new XAttribute(XNamespace.Xmlns + "p1", "nsp"), new XElement("{nsp}A", new XElement("{nsp}B", new XAttribute(XNamespace.Xmlns + "p1", "nsp")))); ReaderDiff.Compare(SaveXElementUsingXmlWriter(e.Descendants("{nsp}B").FirstOrDefault(), NamespaceHandling.OmitDuplicates), "<p1:B xmlns:p1='nsp'/>"); } //[Variation(Desc = "Not from root IV.", Priority = 2)] public void testFromChildNode4() { XElement e = new XElement("root", new XAttribute(XNamespace.Xmlns + "p1", "nsp"), new XElement("{nsp}A", new XElement("{nsp}B"))); ReaderDiff.Compare(SaveXElementUsingXmlWriter(e.Descendants("{nsp}B").FirstOrDefault(), NamespaceHandling.OmitDuplicates), "<p1:B xmlns:p1='nsp'/>"); } //[Variation(Desc = "Write into used reader I.", Priority = 0, Params = new object[] { "<A xmlns:p1='nsp'/>", "<p1:root xmlns:p1='nsp'><A/></p1:root>" })] //[Variation(Desc = "Write into used reader II.", Priority = 2, Params = new object[] { "<p1:A xmlns:p1='nsp'/>", "<p1:root xmlns:p1='nsp'><p1:A/></p1:root>" })] //[Variation(Desc = "Write into used reader III.", Priority = 2, Params = new object[] { "<p1:A xmlns:p1='nsp'><B xmlns:p1='nsp'/></p1:A>", "<p1:root xmlns:p1='nsp'><p1:A><B/></p1:A></p1:root>" })] public void testIntoOpenedWriter() { XElement e = XElement.Parse(CurrentChild.Params[0] as string); StringWriter sw = new StringWriter(); using (XmlWriter w = XmlWriter.Create(sw, new XmlWriterSettings() { NamespaceHandling = NamespaceHandling.OmitDuplicates, OmitXmlDeclaration = true })) { // prepare writer w.WriteStartDocument(); w.WriteStartElement("p1", "root", "nsp"); // write xelement e.WriteTo(w); // close the prep. lines w.WriteEndElement(); w.WriteEndDocument(); } sw.Dispose(); ReaderDiff.Compare(sw.ToString(), CurrentChild.Params[1] as string); } //[Variation(Desc = "Write into used reader I. (def. ns.)", Priority = 0, Params = new object[] { "<A xmlns='nsp'/>", "<root xmlns='nsp'><A/></root>" })] //[Variation(Desc = "Write into used reader II. (def. ns.)", Priority = 2, Params = new object[] { "<A xmlns='ns-other'><B xmlns='nsp'><C xmlns='nsp'/></B></A>", // "<root xmlns='nsp'><A xmlns='ns-other'><B xmlns='nsp'><C/></B></A></root>" })] public void testIntoOpenedWriterDefaultNS() { XElement e = XElement.Parse(CurrentChild.Params[0] as string); StringWriter sw = new StringWriter(); using (XmlWriter w = XmlWriter.Create(sw, new XmlWriterSettings() { NamespaceHandling = NamespaceHandling.OmitDuplicates, OmitXmlDeclaration = true })) { // prepare writer w.WriteStartDocument(); w.WriteStartElement("", "root", "nsp"); // write xelement e.WriteTo(w); // close the prep. lines w.WriteEndElement(); w.WriteEndDocument(); } sw.Dispose(); ReaderDiff.Compare(sw.ToString(), CurrentChild.Params[1] as string); } //[Variation(Desc = "Write into used reader (Xlinq lookup + existing hint in the Writer; different prefix)", // Priority = 2, // Params = new object[] { "<p1:root xmlns:p1='nsp'><p2:B xmlns:p2='nsp'/></p1:root>" })] public void testIntoOpenedWriterXlinqLookup1() { XElement e = new XElement("A", new XAttribute(XNamespace.Xmlns + "p2", "nsp"), new XElement("{nsp}B")); StringWriter sw = new StringWriter(); using (XmlWriter w = XmlWriter.Create(sw, new XmlWriterSettings() { NamespaceHandling = NamespaceHandling.OmitDuplicates, OmitXmlDeclaration = true })) { // prepare writer w.WriteStartDocument(); w.WriteStartElement("p1", "root", "nsp"); // write xelement e.Element("{nsp}B").WriteTo(w); // close the prep. lines w.WriteEndElement(); w.WriteEndDocument(); } sw.Dispose(); ReaderDiff.Compare(sw.ToString(), CurrentChild.Params[0] as string); } //[Variation(Desc = "Write into used reader (Xlinq lookup + existing hint in the Writer; same prefix)", // Priority = 2, // Params = new object[] { "<p1:root xmlns:p1='nsp'><p1:B /></p1:root>" })] public void testIntoOpenedWriterXlinqLookup2() { XElement e = new XElement("A", new XAttribute(XNamespace.Xmlns + "p1", "nsp"), new XElement("{nsp}B")); StringWriter sw = new StringWriter(); using (XmlWriter w = XmlWriter.Create(sw, new XmlWriterSettings() { NamespaceHandling = NamespaceHandling.OmitDuplicates, OmitXmlDeclaration = true })) { // prepare writer w.WriteStartDocument(); w.WriteStartElement("p1", "root", "nsp"); // write xelement e.Element("{nsp}B").WriteTo(w); // close the prep. lines w.WriteEndElement(); w.WriteEndDocument(); } sw.Dispose(); ReaderDiff.Compare(sw.ToString(), CurrentChild.Params[0] as string); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AllReady.Areas.Admin.Features.Events; using AllReady.Areas.Admin.ViewModels.Event; using AllReady.Models; using AllReady.Providers; using Microsoft.Extensions.DependencyInjection; using Moq; using Xunit; namespace AllReady.UnitTest.Areas.Admin.Features.Events { public class EditEventCommandHandlerShould : TestBase { [Fact] public async Task EventDoesNotExist() { var context = ServiceProvider.GetService<AllReadyContext>(); var htb = new Organization { Id = 123, Name = "Humanitarian Toolbox", LogoUrl = "http://www.htbox.org/upload/home/ht-hero.png", WebUrl = "http://www.htbox.org", Campaigns = new List<Campaign>() }; var firePrev = new Campaign { Id = 1, Name = "Neighborhood Fire Prevention Days", ManagingOrganization = htb, TimeZoneId = "Central Standard Time" }; htb.Campaigns.Add(firePrev); context.Organizations.Add(htb); context.SaveChanges(); var vm = new EventEditViewModel { CampaignId = 1, TimeZoneId = "Central Standard Time" }; var query = new EditEventCommand { Event = vm }; var handler = new EditEventCommandHandler(context); var result = await handler.Handle(query); Assert.True(result > 0); var data = context.Events.Count(_ => _.Id == result); Assert.True(data == 1); } [Fact] public async Task ExistingEvent() { var context = ServiceProvider.GetService<AllReadyContext>(); var htb = new Organization { Id = 123, Name = "Humanitarian Toolbox", LogoUrl = "http://www.htbox.org/upload/home/ht-hero.png", WebUrl = "http://www.htbox.org", Campaigns = new List<Campaign>() }; var firePrev = new Campaign { Id = 1, Name = "Neighborhood Fire Prevention Days", ManagingOrganization = htb, TimeZoneId = "Central Standard Time" }; htb.Campaigns.Add(firePrev); var queenAnne = new Event { Id = 100, Name = "Queen Anne Fire Prevention Day", Campaign = firePrev, CampaignId = firePrev.Id, StartDateTime = new DateTime(2015, 7, 4, 10, 0, 0).ToUniversalTime(), EndDateTime = new DateTime(2015, 12, 31, 15, 0, 0).ToUniversalTime(), Location = new Location { Id = 1 }, RequiredSkills = new List<EventSkill>() }; context.Organizations.Add(htb); context.Events.Add(queenAnne); context.SaveChanges(); const string newName = "Some new name value"; var startDateTime = new DateTime(2015, 7, 12, 4, 15, 0); var endDateTime = new DateTime(2015, 12, 7, 15, 10, 0); var vm = new EventEditViewModel { CampaignId = queenAnne.CampaignId, CampaignName = queenAnne.Campaign.Name, Description = queenAnne.Description, EndDateTime = endDateTime, Id = queenAnne.Id, ImageUrl = queenAnne.ImageUrl, Location = null, Name = newName, RequiredSkills = queenAnne.RequiredSkills, TimeZoneId = "Central Standard Time", StartDateTime = startDateTime, OrganizationId = queenAnne.Campaign.ManagingOrganizationId, OrganizationName = queenAnne.Campaign.ManagingOrganization.Name, }; var query = new EditEventCommand { Event = vm }; var handler = new EditEventCommandHandler(context); var result = await handler.Handle(query); Assert.Equal(100, result); // should get back the event id var data = context.Events.Single(_ => _.Id == result); Assert.Equal(newName, data.Name); Assert.Equal(2015, data.StartDateTime.Year); Assert.Equal(7, data.StartDateTime.Month); Assert.Equal(12, data.StartDateTime.Day); Assert.Equal(4, data.StartDateTime.Hour); Assert.Equal(15, data.StartDateTime.Minute); Assert.Equal(2015, data.EndDateTime.Year); Assert.Equal(12, data.EndDateTime.Month); Assert.Equal(7, data.EndDateTime.Day); Assert.Equal(15, data.EndDateTime.Hour); Assert.Equal(10, data.EndDateTime.Minute); } [Fact] public async Task ExistingEventUpdateLocation() { const string seattlePostalCode = "98117"; var seattle = new Location { Id = 12, Address1 = "123 Main Street", Address2 = "Unit 2", City = "Seattle", PostalCode = seattlePostalCode, Country = "USA", State = "WA", Name = "Organizer name", PhoneNumber = "555-555-5555" }; var htb = new Organization { Id = 123, Name = "Humanitarian Toolbox", LogoUrl = "http://www.htbox.org/upload/home/ht-hero.png", WebUrl = "http://www.htbox.org", Campaigns = new List<Campaign>() }; var firePrev = new Campaign { Id = 1, Name = "Neighborhood Fire Prevention Days", ManagingOrganization = htb, TimeZoneId = "Central Standard Time" }; htb.Campaigns.Add(firePrev); var queenAnne = new Event { Id = 100, Name = "Queen Anne Fire Prevention Day", Campaign = firePrev, CampaignId = firePrev.Id, StartDateTime = new DateTime(2015, 7, 4, 10, 0, 0).ToUniversalTime(), EndDateTime = new DateTime(2015, 12, 31, 15, 0, 0).ToUniversalTime(), Location = seattle, RequiredSkills = new List<EventSkill>() }; var context = ServiceProvider.GetService<AllReadyContext>(); context.Locations.Add(seattle); context.Organizations.Add(htb); context.Events.Add(queenAnne); context.SaveChanges(); var newLocation = new Location { Address1 = "123 new address", Address2 = "new suite", PostalCode = "98004", City = "Bellevue", State = "WA", Country = "USA", Name = "New name", PhoneNumber = "New number" }.ToEditModel(); var locationEdit = new EventEditViewModel { CampaignId = queenAnne.CampaignId, CampaignName = queenAnne.Campaign.Name, Description = queenAnne.Description, EndDateTime = queenAnne.EndDateTime, Id = queenAnne.Id, ImageUrl = queenAnne.ImageUrl, Location = newLocation, Name = queenAnne.Name, RequiredSkills = queenAnne.RequiredSkills, TimeZoneId = "Central Standard Time", StartDateTime = queenAnne.StartDateTime, OrganizationId = queenAnne.Campaign.ManagingOrganizationId, OrganizationName = queenAnne.Campaign.ManagingOrganization.Name, }; var query = new EditEventCommand { Event = locationEdit }; var handler = new EditEventCommandHandler(context); var result = await handler.Handle(query); Assert.Equal(100, result); // should get back the event id var data = context.Events.Single(a => a.Id == result); Assert.Equal(data.Location.Address1, newLocation.Address1); Assert.Equal(data.Location.Address2, newLocation.Address2); Assert.Equal(data.Location.City, newLocation.City); Assert.Equal(data.Location.PostalCode, newLocation.PostalCode); Assert.Equal(data.Location.State, newLocation.State); Assert.Equal(data.Location.Country, newLocation.Country); Assert.Equal(data.Location.PhoneNumber, newLocation.PhoneNumber); Assert.Equal(data.Location.Name, newLocation.Name); } [Fact] public async Task ModelIsCreated() { var context = ServiceProvider.GetService<AllReadyContext>(); // Adding an event requires a campaign for a organization ID and an event to match that in the command context.Campaigns.Add(new Campaign { Id = 1, TimeZoneId = "Central Standard Time" }); context.Events.Add(new Event { Id = 1 }); context.SaveChanges(); var sut = new EditEventCommandHandler(context); var actual = await sut.Handle(new EditEventCommand { Event = new EventEditViewModel { CampaignId = 1, Id = 1, TimeZoneId = "Central Standard Time" } }); Assert.Equal(1, actual); } } }
// 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 ExtractVector128SByte1() { var test = new ImmUnaryOpTest__ExtractVector128SByte1(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } 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 ImmUnaryOpTest__ExtractVector128SByte1 { private struct TestStruct { public Vector256<SByte> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref testStruct._fld), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ExtractVector128SByte1 testClass) { var result = Avx.ExtractVector128(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static SByte[] _data = new SByte[Op1ElementCount]; private static Vector256<SByte> _clsVar; private Vector256<SByte> _fld; private SimpleUnaryOpTest__DataTable<SByte, SByte> _dataTable; static ImmUnaryOpTest__ExtractVector128SByte1() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); } public ImmUnaryOpTest__ExtractVector128SByte1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new SimpleUnaryOpTest__DataTable<SByte, SByte>(_data, new SByte[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.ExtractVector128( Unsafe.Read<Vector256<SByte>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.ExtractVector128( Avx.LoadVector256((SByte*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx.ExtractVector128( Avx.LoadAlignedVector256((SByte*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx).GetMethod(nameof(Avx.ExtractVector128), new Type[] { typeof(Vector256<SByte>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<SByte>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.ExtractVector128), new Type[] { typeof(Vector256<SByte>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((SByte*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.ExtractVector128), new Type[] { typeof(Vector256<SByte>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((SByte*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.ExtractVector128( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector256<SByte>>(_dataTable.inArrayPtr); var result = Avx.ExtractVector128(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Avx.LoadVector256((SByte*)(_dataTable.inArrayPtr)); var result = Avx.ExtractVector128(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArrayPtr)); var result = Avx.ExtractVector128(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ExtractVector128SByte1(); var result = Avx.ExtractVector128(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.ExtractVector128(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx.ExtractVector128(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<SByte> firstOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { SByte[] inArray = new SByte[Op1ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != firstOp[16]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != firstOp[i+16]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.ExtractVector128)}<SByte>(Vector256<SByte><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System.Diagnostics; namespace Microsoft.Xml { using System; internal class UTF16Decoder : System.Text.Decoder { private bool _bigEndian; private int _lastByte; private const int CharSize = 2; public UTF16Decoder(bool bigEndian) { _lastByte = -1; _bigEndian = bigEndian; } public override int GetCharCount(byte[] bytes, int index, int count) { return GetCharCount(bytes, index, count, false); } public override int GetCharCount(byte[] bytes, int index, int count, bool flush) { int byteCount = count + ((_lastByte >= 0) ? 1 : 0); if (flush && (byteCount % CharSize != 0)) { throw new ArgumentException(string.Format(ResXml.Enc_InvalidByteInEncoding, new object[1] { -1 }), (string)null); } return byteCount / CharSize; } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { int charCount = GetCharCount(bytes, byteIndex, byteCount); if (_lastByte >= 0) { if (byteCount == 0) { return charCount; } int nextByte = bytes[byteIndex++]; byteCount--; chars[charIndex++] = _bigEndian ? (char)(_lastByte << 8 | nextByte) : (char)(nextByte << 8 | _lastByte); _lastByte = -1; } if ((byteCount & 1) != 0) { _lastByte = bytes[byteIndex + --byteCount]; } // use the fast BlockCopy if possible if (_bigEndian == BitConverter.IsLittleEndian) { int byteEnd = byteIndex + byteCount; if (_bigEndian) { while (byteIndex < byteEnd) { int hi = bytes[byteIndex++]; int lo = bytes[byteIndex++]; chars[charIndex++] = (char)(hi << 8 | lo); } } else { while (byteIndex < byteEnd) { int lo = bytes[byteIndex++]; int hi = bytes[byteIndex++]; chars[charIndex++] = (char)(hi << 8 | lo); } } } else { Buffer.BlockCopy(bytes, byteIndex, chars, charIndex * CharSize, byteCount); } return charCount; } public override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { charsUsed = 0; bytesUsed = 0; if (_lastByte >= 0) { if (byteCount == 0) { completed = true; return; } int nextByte = bytes[byteIndex++]; byteCount--; bytesUsed++; chars[charIndex++] = _bigEndian ? (char)(_lastByte << 8 | nextByte) : (char)(nextByte << 8 | _lastByte); charCount--; charsUsed++; _lastByte = -1; } if (charCount * CharSize < byteCount) { byteCount = charCount * CharSize; completed = false; } else { completed = true; } if (_bigEndian == BitConverter.IsLittleEndian) { int i = byteIndex; int byteEnd = i + (byteCount & ~0x1); if (_bigEndian) { while (i < byteEnd) { int hi = bytes[i++]; int lo = bytes[i++]; chars[charIndex++] = (char)(hi << 8 | lo); } } else { while (i < byteEnd) { int lo = bytes[i++]; int hi = bytes[i++]; chars[charIndex++] = (char)(hi << 8 | lo); } } } else { Buffer.BlockCopy(bytes, byteIndex, chars, charIndex * CharSize, (int)(byteCount & ~0x1)); } charsUsed += byteCount / CharSize; bytesUsed += byteCount; if ((byteCount & 1) != 0) { _lastByte = bytes[byteIndex + byteCount - 1]; } } } internal class SafeAsciiDecoder : Decoder { public SafeAsciiDecoder() { } public override int GetCharCount(byte[] bytes, int index, int count) { return count; } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { int i = byteIndex; int j = charIndex; while (i < byteIndex + byteCount) { chars[j++] = (char)bytes[i++]; } return byteCount; } public override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { if (charCount < byteCount) { byteCount = charCount; completed = false; } else { completed = true; } int i = byteIndex; int j = charIndex; int byteEndIndex = byteIndex + byteCount; while (i < byteEndIndex) { chars[j++] = (char)bytes[i++]; } charsUsed = byteCount; bytesUsed = byteCount; } } internal class Ucs4Encoding : Encoding { internal Ucs4Decoder ucs4Decoder; public override string WebName { get { return this.EncodingName; } } public override Decoder GetDecoder() { return ucs4Decoder; } public override int GetByteCount(char[] chars, int index, int count) { return checked(count * 4); } public override int GetByteCount(char[] chars) { return chars.Length * 4; } public override byte[] GetBytes(string s) { return null; //ucs4Decoder.GetByteCount(chars, index, count); } public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { return 0; } public override int GetMaxByteCount(int charCount) { return 0; } public override int GetCharCount(byte[] bytes, int index, int count) { return ucs4Decoder.GetCharCount(bytes, index, count); } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return ucs4Decoder.GetChars(bytes, byteIndex, byteCount, chars, charIndex); } public override int GetMaxCharCount(int byteCount) { return (byteCount + 3) / 4; } public override int CodePage { get { return 0; } } public override int GetCharCount(byte[] bytes) { return bytes.Length / 4; } public override Encoder GetEncoder() { return null; } internal static Encoding UCS4_Littleendian { get { return new Ucs4Encoding4321(); } } internal static Encoding UCS4_Bigendian { get { return new Ucs4Encoding1234(); } } internal static Encoding UCS4_2143 { get { return new Ucs4Encoding2143(); } } internal static Encoding UCS4_3412 { get { return new Ucs4Encoding3412(); } } } internal class Ucs4Encoding1234 : Ucs4Encoding { public Ucs4Encoding1234() { ucs4Decoder = new Ucs4Decoder1234(); } public override string EncodingName { get { return "ucs-4 (Bigendian)"; } } public override byte[] GetPreamble() { return new byte[4] { 0x00, 0x00, 0xfe, 0xff }; } } internal class Ucs4Encoding4321 : Ucs4Encoding { public Ucs4Encoding4321() { ucs4Decoder = new Ucs4Decoder4321(); } public override string EncodingName { get { return "ucs-4"; } } public override byte[] GetPreamble() { return new byte[4] { 0xff, 0xfe, 0x00, 0x00 }; } } internal class Ucs4Encoding2143 : Ucs4Encoding { public Ucs4Encoding2143() { ucs4Decoder = new Ucs4Decoder2143(); } public override string EncodingName { get { return "ucs-4 (order 2143)"; } } public override byte[] GetPreamble() { return new byte[4] { 0x00, 0x00, 0xff, 0xfe }; } } internal class Ucs4Encoding3412 : Ucs4Encoding { public Ucs4Encoding3412() { ucs4Decoder = new Ucs4Decoder3412(); } public override string EncodingName { get { return "ucs-4 (order 3412)"; } } public override byte[] GetPreamble() { return new byte[4] { 0xfe, 0xff, 0x00, 0x00 }; } } internal abstract class Ucs4Decoder : Decoder { internal byte[] lastBytes = new byte[4]; internal int lastBytesCount = 0; public override int GetCharCount(byte[] bytes, int index, int count) { return (count + lastBytesCount) / 4; } internal abstract int GetFullChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex); public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // finish a character from the bytes that were cached last time int i = lastBytesCount; if (lastBytesCount > 0) { // copy remaining bytes into the cache for (; lastBytesCount < 4 && byteCount > 0; lastBytesCount++) { lastBytes[lastBytesCount] = bytes[byteIndex]; byteIndex++; byteCount--; } // still not enough bytes -> return if (lastBytesCount < 4) { return 0; } // decode 1 character from the byte cache i = GetFullChars(lastBytes, 0, 4, chars, charIndex); Debug.Assert(i == 1); charIndex += i; lastBytesCount = 0; } else { i = 0; } // decode block of byte quadruplets i = GetFullChars(bytes, byteIndex, byteCount, chars, charIndex) + i; // cache remaining bytes that does not make up a character int bytesLeft = (byteCount & 0x3); if (bytesLeft >= 0) { for (int j = 0; j < bytesLeft; j++) { lastBytes[j] = bytes[byteIndex + byteCount - bytesLeft + j]; } lastBytesCount = bytesLeft; } return i; } public override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { bytesUsed = 0; charsUsed = 0; // finish a character from the bytes that were cached last time int i = 0; int lbc = lastBytesCount; if (lbc > 0) { // copy remaining bytes into the cache for (; lbc < 4 && byteCount > 0; lbc++) { lastBytes[lbc] = bytes[byteIndex]; byteIndex++; byteCount--; bytesUsed++; } // still not enough bytes -> return if (lbc < 4) { lastBytesCount = lbc; completed = true; return; } // decode 1 character from the byte cache i = GetFullChars(lastBytes, 0, 4, chars, charIndex); Debug.Assert(i == 1); charIndex += i; charCount -= i; charsUsed = i; lastBytesCount = 0; // if that's all that was requested -> return if (charCount == 0) { completed = (byteCount == 0); return; } } else { i = 0; } // modify the byte count for GetFullChars depending on how many characters were requested if (charCount * 4 < byteCount) { byteCount = charCount * 4; completed = false; } else { completed = true; } bytesUsed += byteCount; // decode block of byte quadruplets charsUsed = GetFullChars(bytes, byteIndex, byteCount, chars, charIndex) + i; // cache remaining bytes that does not make up a character int bytesLeft = (byteCount & 0x3); if (bytesLeft >= 0) { for (int j = 0; j < bytesLeft; j++) { lastBytes[j] = bytes[byteIndex + byteCount - bytesLeft + j]; } lastBytesCount = bytesLeft; } } internal void Ucs4ToUTF16(uint code, char[] chars, int charIndex) { chars[charIndex] = (char)(XmlCharType.SurHighStart + (char)((code >> 16) - 1) + (char)((code >> 10) & 0x3F)); chars[charIndex + 1] = (char)(XmlCharType.SurLowStart + (char)(code & 0x3FF)); } } internal class Ucs4Decoder4321 : Ucs4Decoder { internal override int GetFullChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { uint code; int i, j; byteCount += byteIndex; for (i = byteIndex, j = charIndex; i + 3 < byteCount;) { code = (uint)((bytes[i + 3] << 24) | (bytes[i + 2] << 16) | (bytes[i + 1] << 8) | bytes[i]); if (code > 0x10FFFF) { throw new ArgumentException(string.Format(ResXml.Enc_InvalidByteInEncoding, new object[1] { i }), (string)null); } else if (code > 0xFFFF) { Ucs4ToUTF16(code, chars, j); j++; } else { if (XmlCharType.IsSurrogate((int)code)) { throw new XmlException(ResXml.Xml_InvalidCharInThisEncoding, string.Empty); } else { chars[j] = (char)code; } } j++; i += 4; } return j - charIndex; } }; internal class Ucs4Decoder1234 : Ucs4Decoder { internal override int GetFullChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { uint code; int i, j; byteCount += byteIndex; for (i = byteIndex, j = charIndex; i + 3 < byteCount;) { code = (uint)((bytes[i] << 24) | (bytes[i + 1] << 16) | (bytes[i + 2] << 8) | bytes[i + 3]); if (code > 0x10FFFF) { throw new ArgumentException(string.Format(ResXml.Enc_InvalidByteInEncoding, new object[1] { i }), (string)null); } else if (code > 0xFFFF) { Ucs4ToUTF16(code, chars, j); j++; } else { if (XmlCharType.IsSurrogate((int)code)) { throw new XmlException(ResXml.Xml_InvalidCharInThisEncoding, string.Empty); } else { chars[j] = (char)code; } } j++; i += 4; } return j - charIndex; } } internal class Ucs4Decoder2143 : Ucs4Decoder { internal override int GetFullChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { uint code; int i, j; byteCount += byteIndex; for (i = byteIndex, j = charIndex; i + 3 < byteCount;) { code = (uint)((bytes[i + 1] << 24) | (bytes[i] << 16) | (bytes[i + 3] << 8) | bytes[i + 2]); if (code > 0x10FFFF) { throw new ArgumentException(string.Format(ResXml.Enc_InvalidByteInEncoding, new object[1] { i }), (string)null); } else if (code > 0xFFFF) { Ucs4ToUTF16(code, chars, j); j++; } else { if (XmlCharType.IsSurrogate((int)code)) { throw new XmlException(ResXml.Xml_InvalidCharInThisEncoding, string.Empty); } else { chars[j] = (char)code; } } j++; i += 4; } return j - charIndex; } } internal class Ucs4Decoder3412 : Ucs4Decoder { internal override int GetFullChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { uint code; int i, j; byteCount += byteIndex; for (i = byteIndex, j = charIndex; i + 3 < byteCount;) { code = (uint)((bytes[i + 2] << 24) | (bytes[i + 3] << 16) | (bytes[i] << 8) | bytes[i + 1]); if (code > 0x10FFFF) { throw new ArgumentException(string.Format(ResXml.Enc_InvalidByteInEncoding, new object[1] { i }), (string)null); } else if (code > 0xFFFF) { Ucs4ToUTF16(code, chars, j); j++; } else { if (XmlCharType.IsSurrogate((int)code)) { throw new XmlException(ResXml.Xml_InvalidCharInThisEncoding, string.Empty); } else { chars[j] = (char)code; } } j++; i += 4; } return j - charIndex; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using VersionedRestApi.Examples.Areas.HelpPage.ModelDescriptions; using VersionedRestApi.Examples.Areas.HelpPage.Models; namespace VersionedRestApi.Examples.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.IdentityModel.Claims; using System.IdentityModel.Policy; using System.Runtime; using System.Security.Principal; using System.ServiceModel; using System.Text; namespace System.IdentityModel { internal static class SecurityUtils { public const string Identities = "Identities"; private static IIdentity s_anonymousIdentity; // these should be kept in sync with IIS70 public const string AuthTypeNTLM = "NTLM"; public const string AuthTypeNegotiate = "Negotiate"; public const string AuthTypeKerberos = "Kerberos"; public const string AuthTypeAnonymous = ""; public const string AuthTypeCertMap = "SSL/PCT"; // mapped from a cert public const string AuthTypeBasic = "Basic"; //LogonUser internal static IIdentity AnonymousIdentity { get { if (s_anonymousIdentity == null) s_anonymousIdentity = SecurityUtils.CreateIdentity(String.Empty); return s_anonymousIdentity; } } public static DateTime MaxUtcDateTime { get { // + and - TimeSpan.TicksPerDay is to compensate the DateTime.ParseExact (to localtime) overflow. return new DateTime(DateTime.MaxValue.Ticks - TimeSpan.TicksPerDay, DateTimeKind.Utc); } } internal static IIdentity CreateIdentity(string name, string authenticationType) { return new GenericIdentity(name, authenticationType); } internal static IIdentity CreateIdentity(string name) { return new GenericIdentity(name); } internal static byte[] CloneBuffer(byte[] buffer) { return CloneBuffer(buffer, 0, buffer.Length); } internal static byte[] CloneBuffer(byte[] buffer, int offset, int len) { DiagnosticUtility.DebugAssert(offset >= 0, "Negative offset passed to CloneBuffer."); DiagnosticUtility.DebugAssert(len >= 0, "Negative len passed to CloneBuffer."); DiagnosticUtility.DebugAssert(buffer.Length - offset >= len, "Invalid parameters to CloneBuffer."); byte[] copy = Fx.AllocateByteArray(len); Buffer.BlockCopy(buffer, offset, copy, 0, len); return copy; } internal static bool MatchesBuffer(byte[] src, byte[] dst) { return MatchesBuffer(src, 0, dst, 0); } internal static bool MatchesBuffer(byte[] src, int srcOffset, byte[] dst, int dstOffset) { DiagnosticUtility.DebugAssert(dstOffset >= 0, "Negative dstOffset passed to MatchesBuffer."); DiagnosticUtility.DebugAssert(srcOffset >= 0, "Negative srcOffset passed to MatchesBuffer."); // defensive programming if ((dstOffset < 0) || (srcOffset < 0)) return false; if (src == null || srcOffset >= src.Length) return false; if (dst == null || dstOffset >= dst.Length) return false; if ((src.Length - srcOffset) != (dst.Length - dstOffset)) return false; for (int i = srcOffset, j = dstOffset; i < src.Length; i++, j++) { if (src[i] != dst[j]) return false; } return true; } internal static string ClaimSetToString(ClaimSet claimSet) { StringBuilder sb = new StringBuilder(); sb.AppendLine("ClaimSet ["); for (int i = 0; i < claimSet.Count; i++) { Claim claim = claimSet[i]; if (claim != null) { sb.Append(" "); sb.AppendLine(claim.ToString()); } } string prefix = "] by "; ClaimSet issuer = claimSet; do { issuer = issuer.Issuer; sb.AppendFormat("{0}{1}", prefix, issuer == claimSet ? "Self" : (issuer.Count <= 0 ? "Unknown" : issuer[0].ToString())); prefix = " -> "; } while (issuer.Issuer != issuer); return sb.ToString(); } internal static IIdentity CloneIdentityIfNecessary(IIdentity identity) { if (identity != null) { throw ExceptionHelper.PlatformNotSupported(); } return identity; } internal static ClaimSet CloneClaimSetIfNecessary(ClaimSet claimSet) { if (claimSet != null) { throw ExceptionHelper.PlatformNotSupported(); } return claimSet; } internal static ReadOnlyCollection<ClaimSet> CloneClaimSetsIfNecessary(ReadOnlyCollection<ClaimSet> claimSets) { throw ExceptionHelper.PlatformNotSupported(); } internal static void DisposeClaimSetIfNecessary(ClaimSet claimSet) { throw ExceptionHelper.PlatformNotSupported(); } internal static void DisposeClaimSetsIfNecessary(ReadOnlyCollection<ClaimSet> claimSets) { throw ExceptionHelper.PlatformNotSupported(); } internal static ReadOnlyCollection<IAuthorizationPolicy> CloneAuthorizationPoliciesIfNecessary(ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies) { if (authorizationPolicies != null && authorizationPolicies.Count > 0) { bool clone = false; for (int i = 0; i < authorizationPolicies.Count; ++i) { UnconditionalPolicy policy = authorizationPolicies[i] as UnconditionalPolicy; if (policy != null && policy.IsDisposable) { clone = true; break; } } if (clone) { List<IAuthorizationPolicy> ret = new List<IAuthorizationPolicy>(authorizationPolicies.Count); for (int i = 0; i < authorizationPolicies.Count; ++i) { UnconditionalPolicy policy = authorizationPolicies[i] as UnconditionalPolicy; if (policy != null) { ret.Add(policy.Clone()); } else { ret.Add(authorizationPolicies[i]); } } return new ReadOnlyCollection<IAuthorizationPolicy>(ret); } } return authorizationPolicies; } public static void DisposeAuthorizationPoliciesIfNecessary(ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies) { if (authorizationPolicies != null && authorizationPolicies.Count > 0) { for (int i = 0; i < authorizationPolicies.Count; ++i) { DisposeIfNecessary(authorizationPolicies[i] as UnconditionalPolicy); } } } public static void DisposeIfNecessary(IDisposable obj) { if (obj != null) { obj.Dispose(); } } } internal static class EmptyReadOnlyCollection<T> { public static ReadOnlyCollection<T> Instance = new ReadOnlyCollection<T>(new List<T>()); } }
// 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.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Primitives; using System.Linq; using Xunit; namespace Tests.Integration { public class RecompositionTests { public class Class_OptIn_AllowRecompositionImports { [Import("Value", AllowRecomposition = true)] public int Value { get; set; } } [Fact] public void Import_OptIn_AllowRecomposition() { var container = new CompositionContainer(); var importer = new Class_OptIn_AllowRecompositionImports(); CompositionBatch batch = new CompositionBatch(); batch.AddPart(importer); var valueKey = batch.AddExportedValue("Value", 21); container.Compose(batch); // Initial compose Value should be 21 Assert.Equal(21, importer.Value); // Recompose Value to be 42 batch = new CompositionBatch(); batch.RemovePart(valueKey); batch.AddExportedValue("Value", 42); container.Compose(batch); Assert.Equal(42, importer.Value); } public class Class_OptOut_AllowRecompositionImports { [Import("Value", AllowRecomposition = false)] public int Value { get; set; } } [Fact] public void Import_OptOut_AllowRecomposition() { var container = new CompositionContainer(); var importer = new Class_OptOut_AllowRecompositionImports(); CompositionBatch batch = new CompositionBatch(); batch.AddPart(importer); var valueKey = batch.AddExportedValue("Value", 21); container.Compose(batch); // Initial compose Value should be 21 Assert.Equal(21, importer.Value); // Reset value to ensure it doesn't get set to same value again importer.Value = -21; // Recompose Value to be 42 batch = new CompositionBatch(); batch.RemovePart(valueKey); batch.AddExportedValue("Value", 42); // After rejection batch failures throw ChangeRejectedException to indicate that // the failure did not affect the container Assert.Throws<ChangeRejectedException>(() => { container.Compose(batch); }); Assert.Equal(-21, importer.Value); } public class Class_Default_AllowRecompositionImports { [Import("Value")] public int Value { get; set; } } [Fact] public void Import_Default_AllowRecomposition() { var container = new CompositionContainer(); var importer = new Class_Default_AllowRecompositionImports(); CompositionBatch batch = new CompositionBatch(); batch.AddPart(importer); var valueKey = batch.AddExportedValue("Value", 21); container.Compose(batch); // Initial compose Value should be 21 Assert.Equal(21, importer.Value); // Reset value to ensure it doesn't get set to same value again importer.Value = -21; // Recompose Value to be 42 batch = new CompositionBatch(); batch.RemovePart(valueKey); batch.AddExportedValue("Value", 42); // After rejection batch failures throw ChangeRejectedException to indicate that // the failure did not affect the container Assert.Throws<ChangeRejectedException>(() => { container.Compose(batch); }); Assert.Equal(-21, importer.Value); } public class Class_BothOptInAndOptOutRecompositionImports { [Import("Value", AllowRecomposition = true)] public int RecomposableValue { get; set; } [Import("Value", AllowRecomposition = false)] public int NonRecomposableValue { get; set; } } [Fact] public void Import_BothOptInAndOptOutRecomposition() { var container = new CompositionContainer(); var importer = new Class_BothOptInAndOptOutRecompositionImports(); CompositionBatch batch = new CompositionBatch(); batch.AddPart(importer); var valueKey = batch.AddExportedValue("Value", 21); container.Compose(batch); // Initial compose values should be 21 Assert.Equal(21, importer.RecomposableValue); Assert.Equal(21, importer.NonRecomposableValue); // Reset value to ensure it doesn't get set to same value again importer.NonRecomposableValue = -21; importer.RecomposableValue = -21; // Recompose Value to be 42 batch = new CompositionBatch(); batch.RemovePart(valueKey); batch.AddExportedValue("Value", 42); // After rejection batch failures throw ChangeRejectedException to indicate that // the failure did not affect the container Assert.Throws<ChangeRejectedException>(() => { container.Compose(batch); }); Assert.Equal(-21, importer.NonRecomposableValue); // The batch rejection means that the recomposable value shouldn't change either Assert.Equal(-21, importer.RecomposableValue); } public class Class_MultipleOptInRecompositionImportsWithDifferentContracts { [Import("Value1", AllowRecomposition = true)] public int Value1 { get; set; } [Import("Value2", AllowRecomposition = true)] public int Value2 { get; set; } } [Fact] public void Import_OptInRecomposition_Multlple() { var container = new CompositionContainer(); var importer = new Class_MultipleOptInRecompositionImportsWithDifferentContracts(); CompositionBatch batch = new CompositionBatch(); batch.AddPart(importer); var value1Key = batch.AddExportedValue("Value1", 21); var value2Key = batch.AddExportedValue("Value2", 23); container.Compose(batch); Assert.Equal(21, importer.Value1); Assert.Equal(23, importer.Value2); // Reset value to ensure it doesn't get set to same value again importer.Value1 = -21; importer.Value2 = -23; // Recompose Value to be 42 batch = new CompositionBatch(); batch.RemovePart(value1Key); batch.AddExportedValue("Value1", 42); container.Compose(batch); Assert.Equal(42, importer.Value1); Assert.Equal(-23, importer.Value2); } [PartNotDiscoverable] public class MyName { public MyName(string name) { this.Name = name; } [Export("Name")] public string Name { get; private set; } } [PartNotDiscoverable] public class Spouse { public Spouse(string name) { this.Name = name; } [Export("Friend")] [ExportMetadata("Relationship", "Wife")] public string Name { get; private set; } } [PartNotDiscoverable] public class Child { public Child(string name) { this.Name = name; } [Export("Child")] public string Name { get; private set; } } [PartNotDiscoverable] public class Job { public Job(string name) { this.Name = name; } [Export("Job")] public string Name { get; private set; } } [PartNotDiscoverable] public class Friend { public Friend(string name) { this.Name = name; } [Export("Friend")] public string Name { get; private set; } } public interface IRelationshipView { string Relationship { get; } } [PartNotDiscoverable] public class Me { [Import("Name", AllowRecomposition = true)] public string Name { get; set; } [Import("Job", AllowDefault = true, AllowRecomposition = true)] public string Job { get; set; } [ImportMany("Child")] public string[] Children { get; set; } [ImportMany("Friend")] public Lazy<string, IRelationshipView>[] Relatives { get; set; } [ImportMany("Friend", AllowRecomposition = true)] public string[] Friends { get; set; } } [Fact] public void Recomposition_IntegrationTest() { var container = new CompositionContainer(); var batch = new CompositionBatch(); var me = new Me(); batch.AddPart(me); var namePart = batch.AddPart(new MyName("Blake")); batch.AddPart(new Spouse("Barbara")); batch.AddPart(new Friend("Steve")); batch.AddPart(new Friend("Joyce")); container.Compose(batch); Assert.Equal(me.Name, "Blake"); Assert.Equal(me.Job, null); Assert.Equal(me.Friends.Length, 3); Assert.Equal(me.Relatives.Length, 1); Assert.Equal(me.Children.Length, 0); // Can only have one name Assert.Throws<ChangeRejectedException>(() => container.ComposeParts(new MyName("Blayke"))); batch = new CompositionBatch(); batch.AddPart(new MyName("Blayke")); batch.RemovePart(namePart); container.Compose(batch); Assert.Equal(me.Name, "Blayke"); batch = new CompositionBatch(); var jobPart = batch.AddPart(new Job("Architect")); container.Compose(batch); Assert.Equal(me.Job, "Architect"); batch = new CompositionBatch(); batch.AddPart(new Job("Chimney Sweep")); container.Compose(batch); Assert.True(me.Job == null, "More than one of an optional import should result in the default value"); batch = new CompositionBatch(); batch.RemovePart(jobPart); container.Compose(batch); Assert.Equal(me.Job, "Chimney Sweep"); batch = new CompositionBatch(); // Can only have one spouse because they aren't recomposable Assert.Throws<ChangeRejectedException>(() => container.ComposeParts(new Spouse("Cameron"))); Assert.Equal(me.Relatives.Length, 1); batch = new CompositionBatch(); batch.AddPart(new Friend("Graham")); container.Compose(batch); Assert.Equal(me.Friends.Length, 4); Assert.Equal(me.Relatives.Length, 1); } public class FooWithOptionalImport { private FooWithSimpleImport _optionalImport; [Import(AllowDefault = true, AllowRecomposition = true)] public FooWithSimpleImport OptionalImport { get { return this._optionalImport; } set { if (value != null) { this._optionalImport = value; Assert.True(!string.IsNullOrEmpty(this._optionalImport.SimpleValue), "Value should have it's imports satisfied"); } } } } [Export] public class FooWithSimpleImport { [Import("FooSimpleImport")] public string SimpleValue { get; set; } } [Fact] public void PartsShouldHaveImportsSatisfiedBeforeBeingUsedToSatisfyRecomposableImports() { var container = new CompositionContainer(); var fooOptional = new FooWithOptionalImport(); container.ComposeParts(fooOptional); container.ComposeExportedValue<string>("FooSimpleImport", "NotNullOrEmpty"); container.ComposeParts(new FooWithSimpleImport()); Assert.True(!string.IsNullOrEmpty(fooOptional.OptionalImport.SimpleValue)); } [Export] public class RootImportRecomposable { [Import(AllowDefault = true, AllowRecomposition = true)] public NonSharedImporter Importer { get; set; } } [Export] [PartCreationPolicy(CreationPolicy.NonShared)] public class NonSharedImporter { [Import] public SimpleImport Import { get; set; } } [Export] public class RootImporter { [Import] public SimpleImport Import { get; set; } } [Export] public class SimpleImport { public int Property { get { return 42; } } } [Fact] [ActiveIssue(733533)] public void RemoveCatalogWithNonSharedPartWithRequiredImport() { var typeCatalog = new TypeCatalog(typeof(NonSharedImporter), typeof(SimpleImport)); var aggCatalog = new AggregateCatalog(); var container = new CompositionContainer(aggCatalog); aggCatalog.Catalogs.Add(typeCatalog); aggCatalog.Catalogs.Add(new TypeCatalog(typeof(RootImportRecomposable))); var rootExport = container.GetExport<RootImportRecomposable>(); var root = rootExport.Value; Assert.Equal(42, root.Importer.Import.Property); aggCatalog.Catalogs.Remove(typeCatalog); Assert.Null(root.Importer); } [Fact] [ActiveIssue(734123)] public void GetExportResultShouldBePromise() { var typeCatalog = new TypeCatalog(typeof(RootImporter), typeof(SimpleImport)); var aggCatalog = new AggregateCatalog(); var container = new CompositionContainer(aggCatalog); aggCatalog.Catalogs.Add(typeCatalog); var root = container.GetExport<RootImporter>(); Assert.Throws<ChangeRejectedException>(() => aggCatalog.Catalogs.Remove(typeCatalog) ); var value = root.Value; Assert.Equal(42, value.Import.Property); } [Fact] // [WorkItem(789269)] public void TestRemovingAndReAddingMultipleDefinitionsFromCatalog() { var fixedParts = new TypeCatalog(typeof(RootMultipleImporter), typeof(ExportedService)); var changingParts = new TypeCatalog(typeof(Exporter1), typeof(Exporter2)); var catalog = new AggregateCatalog(); catalog.Catalogs.Add(fixedParts); catalog.Catalogs.Add(changingParts); var container = new CompositionContainer(catalog); var root = container.GetExport<RootMultipleImporter>().Value; Assert.Equal(2, root.Imports.Length); catalog.Catalogs.Remove(changingParts); Assert.Equal(0, root.Imports.Length); catalog.Catalogs.Add(changingParts); Assert.Equal(2, root.Imports.Length); } [Export] public class RootMultipleImporter { [ImportMany(AllowRecomposition = true)] public IExportedInterface[] Imports { get; set; } } public interface IExportedInterface { } [Export(typeof(IExportedInterface))] public class Exporter1 : IExportedInterface { [Import] public ExportedService Service { get; set; } } [Export(typeof(IExportedInterface))] public class Exporter2 : IExportedInterface { [Import] public ExportedService Service { get; set; } } [Export] public class ExportedService { } [Fact] [ActiveIssue(762215)] public void TestPartCreatorResurrection() { var container = new CompositionContainer(new TypeCatalog(typeof(NonDisposableImportsDisposable), typeof(PartImporter<NonDisposableImportsDisposable>))); var exports = container.GetExports<PartImporter<NonDisposableImportsDisposable>>(); Assert.Equal(0, exports.Count()); container.ComposeParts(new DisposablePart()); exports = container.GetExports<PartImporter<NonDisposableImportsDisposable>>(); Assert.Equal(1, exports.Count()); } [Export] public class PartImporter<PartType> { [Import] public PartType Creator { get; set; } } [Export] public class NonDisposableImportsDisposable { [Import] public DisposablePart Part { get; set; } } [Export] public class Part { } [Export] [PartCreationPolicy(CreationPolicy.NonShared)] public class DisposablePart : Part, IDisposable { public bool Disposed { get; private set; } public void Dispose() { Disposed = true; } } } }
using System; using SubSonic.Schema; using SubSonic.DataProviders; using System.Data; namespace Solution.DataAccess.DataModel { /// <summary> /// Table: Shifts /// Primary Key: SHIFT_ID /// </summary> public class ShiftsStructs: DatabaseTable { public ShiftsStructs(IDataProvider provider):base("Shifts",provider){ ClassName = "Shifts"; SchemaName = "dbo"; Columns.Add(new DatabaseColumn("Id", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = false, AutoIncrement = true, IsForeignKey = false, MaxLength = 0, PropertyName = "Id" }); Columns.Add(new DatabaseColumn("SHIFT_ID", this) { IsPrimaryKey = true, DataType = DbType.AnsiString, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 30, PropertyName = "SHIFT_ID" }); Columns.Add(new DatabaseColumn("SHIFT_NAME", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 50, PropertyName = "SHIFT_NAME" }); Columns.Add(new DatabaseColumn("DEPART_ID", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 30, PropertyName = "DEPART_ID" }); Columns.Add(new DatabaseColumn("SHIFT_KIND", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "SHIFT_KIND" }); Columns.Add(new DatabaseColumn("WORK_HRS", this) { IsPrimaryKey = false, DataType = DbType.Decimal, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "WORK_HRS" }); Columns.Add(new DatabaseColumn("NEED_HRS", this) { IsPrimaryKey = false, DataType = DbType.Decimal, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "NEED_HRS" }); Columns.Add(new DatabaseColumn("IS_DEFAULT", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = false, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "IS_DEFAULT" }); Columns.Add(new DatabaseColumn("RULE_ID", this) { IsPrimaryKey = false, DataType = DbType.AnsiString, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 8, PropertyName = "RULE_ID" }); Columns.Add(new DatabaseColumn("CLASS_ID", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "CLASS_ID" }); Columns.Add(new DatabaseColumn("NEED_SIGN_COUNT", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "NEED_SIGN_COUNT" }); Columns.Add(new DatabaseColumn("IS_COMMON", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "IS_COMMON" }); Columns.Add(new DatabaseColumn("AHEAD1", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "AHEAD1" }); Columns.Add(new DatabaseColumn("IN1", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "IN1" }); Columns.Add(new DatabaseColumn("NEEDIN1", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "NEEDIN1" }); Columns.Add(new DatabaseColumn("BOVERTIME1", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "BOVERTIME1" }); Columns.Add(new DatabaseColumn("OUT1", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "OUT1" }); Columns.Add(new DatabaseColumn("DELAY1", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "DELAY1" }); Columns.Add(new DatabaseColumn("NEEDOUT1", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "NEEDOUT1" }); Columns.Add(new DatabaseColumn("EOVERTIME1", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "EOVERTIME1" }); Columns.Add(new DatabaseColumn("REST1", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "REST1" }); Columns.Add(new DatabaseColumn("REST_BEGIN1", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "REST_BEGIN1" }); Columns.Add(new DatabaseColumn("BREAK1", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "BREAK1" }); Columns.Add(new DatabaseColumn("OT1", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "OT1" }); Columns.Add(new DatabaseColumn("EXT1", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "EXT1" }); Columns.Add(new DatabaseColumn("CANOT1", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "CANOT1" }); Columns.Add(new DatabaseColumn("OT_REST1", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "OT_REST1" }); Columns.Add(new DatabaseColumn("OT_REST_BEGIN1", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "OT_REST_BEGIN1" }); Columns.Add(new DatabaseColumn("BASICHRS1", this) { IsPrimaryKey = false, DataType = DbType.Decimal, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "BASICHRS1" }); Columns.Add(new DatabaseColumn("NEEDHRS1", this) { IsPrimaryKey = false, DataType = DbType.Decimal, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "NEEDHRS1" }); Columns.Add(new DatabaseColumn("DAY1", this) { IsPrimaryKey = false, DataType = DbType.Decimal, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "DAY1" }); Columns.Add(new DatabaseColumn("AHEAD2", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "AHEAD2" }); Columns.Add(new DatabaseColumn("IN2", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "IN2" }); Columns.Add(new DatabaseColumn("NEEDIN2", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "NEEDIN2" }); Columns.Add(new DatabaseColumn("BOVERTIME2", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "BOVERTIME2" }); Columns.Add(new DatabaseColumn("OUT2", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "OUT2" }); Columns.Add(new DatabaseColumn("DELAY2", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "DELAY2" }); Columns.Add(new DatabaseColumn("NEEDOUT2", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "NEEDOUT2" }); Columns.Add(new DatabaseColumn("EOVERTIME2", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "EOVERTIME2" }); Columns.Add(new DatabaseColumn("REST2", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "REST2" }); Columns.Add(new DatabaseColumn("REST_BEGIN2", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "REST_BEGIN2" }); Columns.Add(new DatabaseColumn("BREAK2", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "BREAK2" }); Columns.Add(new DatabaseColumn("OT2", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "OT2" }); Columns.Add(new DatabaseColumn("EXT2", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "EXT2" }); Columns.Add(new DatabaseColumn("CANOT2", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "CANOT2" }); Columns.Add(new DatabaseColumn("OT_REST2", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "OT_REST2" }); Columns.Add(new DatabaseColumn("OT_REST_BEGIN2", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "OT_REST_BEGIN2" }); Columns.Add(new DatabaseColumn("BASICHRS2", this) { IsPrimaryKey = false, DataType = DbType.Decimal, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "BASICHRS2" }); Columns.Add(new DatabaseColumn("NEEDHRS2", this) { IsPrimaryKey = false, DataType = DbType.Decimal, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "NEEDHRS2" }); Columns.Add(new DatabaseColumn("DAY2", this) { IsPrimaryKey = false, DataType = DbType.Decimal, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "DAY2" }); Columns.Add(new DatabaseColumn("AHEAD3", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "AHEAD3" }); Columns.Add(new DatabaseColumn("IN3", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "IN3" }); Columns.Add(new DatabaseColumn("NEEDIN3", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "NEEDIN3" }); Columns.Add(new DatabaseColumn("BOVERTIME3", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "BOVERTIME3" }); Columns.Add(new DatabaseColumn("OUT3", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "OUT3" }); Columns.Add(new DatabaseColumn("DELAY3", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "DELAY3" }); Columns.Add(new DatabaseColumn("NEEDOUT3", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "NEEDOUT3" }); Columns.Add(new DatabaseColumn("EOVERTIME3", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "EOVERTIME3" }); Columns.Add(new DatabaseColumn("REST3", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "REST3" }); Columns.Add(new DatabaseColumn("REST_BEGIN3", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "REST_BEGIN3" }); Columns.Add(new DatabaseColumn("BREAK3", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "BREAK3" }); Columns.Add(new DatabaseColumn("OT3", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "OT3" }); Columns.Add(new DatabaseColumn("EXT3", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "EXT3" }); Columns.Add(new DatabaseColumn("CANOT3", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "CANOT3" }); Columns.Add(new DatabaseColumn("OT_REST3", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "OT_REST3" }); Columns.Add(new DatabaseColumn("OT_REST_BEGIN3", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "OT_REST_BEGIN3" }); Columns.Add(new DatabaseColumn("BASICHRS3", this) { IsPrimaryKey = false, DataType = DbType.Decimal, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "BASICHRS3" }); Columns.Add(new DatabaseColumn("NEEDHRS3", this) { IsPrimaryKey = false, DataType = DbType.Decimal, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "NEEDHRS3" }); Columns.Add(new DatabaseColumn("DAY3", this) { IsPrimaryKey = false, DataType = DbType.Decimal, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "DAY3" }); Columns.Add(new DatabaseColumn("AHEAD4", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "AHEAD4" }); Columns.Add(new DatabaseColumn("IN4", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "IN4" }); Columns.Add(new DatabaseColumn("NEEDIN4", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "NEEDIN4" }); Columns.Add(new DatabaseColumn("BOVERTIME4", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "BOVERTIME4" }); Columns.Add(new DatabaseColumn("OUT4", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "OUT4" }); Columns.Add(new DatabaseColumn("DELAY4", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "DELAY4" }); Columns.Add(new DatabaseColumn("NEEDOUT4", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "NEEDOUT4" }); Columns.Add(new DatabaseColumn("EOVERTIME4", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "EOVERTIME4" }); Columns.Add(new DatabaseColumn("REST4", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "REST4" }); Columns.Add(new DatabaseColumn("REST_BEGIN4", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "REST_BEGIN4" }); Columns.Add(new DatabaseColumn("BREAK4", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "BREAK4" }); Columns.Add(new DatabaseColumn("OT4", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "OT4" }); Columns.Add(new DatabaseColumn("EXT4", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "EXT4" }); Columns.Add(new DatabaseColumn("CANOT4", this) { IsPrimaryKey = false, DataType = DbType.Int16, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "CANOT4" }); Columns.Add(new DatabaseColumn("OT_REST4", this) { IsPrimaryKey = false, DataType = DbType.Int32, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "OT_REST4" }); Columns.Add(new DatabaseColumn("OT_REST_BEGIN4", this) { IsPrimaryKey = false, DataType = DbType.DateTime, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "OT_REST_BEGIN4" }); Columns.Add(new DatabaseColumn("BASICHRS4", this) { IsPrimaryKey = false, DataType = DbType.Decimal, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "BASICHRS4" }); Columns.Add(new DatabaseColumn("NEEDHRS4", this) { IsPrimaryKey = false, DataType = DbType.Decimal, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "NEEDHRS4" }); Columns.Add(new DatabaseColumn("DAY4", this) { IsPrimaryKey = false, DataType = DbType.Decimal, IsNullable = true, AutoIncrement = false, IsForeignKey = false, MaxLength = 0, PropertyName = "DAY4" }); } public IColumn Id{ get{ return this.GetColumn("Id"); } } public IColumn SHIFT_ID{ get{ return this.GetColumn("SHIFT_ID"); } } public IColumn SHIFT_NAME{ get{ return this.GetColumn("SHIFT_NAME"); } } public IColumn DEPART_ID{ get{ return this.GetColumn("DEPART_ID"); } } public IColumn SHIFT_KIND{ get{ return this.GetColumn("SHIFT_KIND"); } } public IColumn WORK_HRS{ get{ return this.GetColumn("WORK_HRS"); } } public IColumn NEED_HRS{ get{ return this.GetColumn("NEED_HRS"); } } public IColumn IS_DEFAULT{ get{ return this.GetColumn("IS_DEFAULT"); } } public IColumn RULE_ID{ get{ return this.GetColumn("RULE_ID"); } } public IColumn CLASS_ID{ get{ return this.GetColumn("CLASS_ID"); } } public IColumn NEED_SIGN_COUNT{ get{ return this.GetColumn("NEED_SIGN_COUNT"); } } public IColumn IS_COMMON{ get{ return this.GetColumn("IS_COMMON"); } } public IColumn AHEAD1{ get{ return this.GetColumn("AHEAD1"); } } public IColumn IN1{ get{ return this.GetColumn("IN1"); } } public IColumn NEEDIN1{ get{ return this.GetColumn("NEEDIN1"); } } public IColumn BOVERTIME1{ get{ return this.GetColumn("BOVERTIME1"); } } public IColumn OUT1{ get{ return this.GetColumn("OUT1"); } } public IColumn DELAY1{ get{ return this.GetColumn("DELAY1"); } } public IColumn NEEDOUT1{ get{ return this.GetColumn("NEEDOUT1"); } } public IColumn EOVERTIME1{ get{ return this.GetColumn("EOVERTIME1"); } } public IColumn REST1{ get{ return this.GetColumn("REST1"); } } public IColumn REST_BEGIN1{ get{ return this.GetColumn("REST_BEGIN1"); } } public IColumn BREAK1{ get{ return this.GetColumn("BREAK1"); } } public IColumn OT1{ get{ return this.GetColumn("OT1"); } } public IColumn EXT1{ get{ return this.GetColumn("EXT1"); } } public IColumn CANOT1{ get{ return this.GetColumn("CANOT1"); } } public IColumn OT_REST1{ get{ return this.GetColumn("OT_REST1"); } } public IColumn OT_REST_BEGIN1{ get{ return this.GetColumn("OT_REST_BEGIN1"); } } public IColumn BASICHRS1{ get{ return this.GetColumn("BASICHRS1"); } } public IColumn NEEDHRS1{ get{ return this.GetColumn("NEEDHRS1"); } } public IColumn DAY1{ get{ return this.GetColumn("DAY1"); } } public IColumn AHEAD2{ get{ return this.GetColumn("AHEAD2"); } } public IColumn IN2{ get{ return this.GetColumn("IN2"); } } public IColumn NEEDIN2{ get{ return this.GetColumn("NEEDIN2"); } } public IColumn BOVERTIME2{ get{ return this.GetColumn("BOVERTIME2"); } } public IColumn OUT2{ get{ return this.GetColumn("OUT2"); } } public IColumn DELAY2{ get{ return this.GetColumn("DELAY2"); } } public IColumn NEEDOUT2{ get{ return this.GetColumn("NEEDOUT2"); } } public IColumn EOVERTIME2{ get{ return this.GetColumn("EOVERTIME2"); } } public IColumn REST2{ get{ return this.GetColumn("REST2"); } } public IColumn REST_BEGIN2{ get{ return this.GetColumn("REST_BEGIN2"); } } public IColumn BREAK2{ get{ return this.GetColumn("BREAK2"); } } public IColumn OT2{ get{ return this.GetColumn("OT2"); } } public IColumn EXT2{ get{ return this.GetColumn("EXT2"); } } public IColumn CANOT2{ get{ return this.GetColumn("CANOT2"); } } public IColumn OT_REST2{ get{ return this.GetColumn("OT_REST2"); } } public IColumn OT_REST_BEGIN2{ get{ return this.GetColumn("OT_REST_BEGIN2"); } } public IColumn BASICHRS2{ get{ return this.GetColumn("BASICHRS2"); } } public IColumn NEEDHRS2{ get{ return this.GetColumn("NEEDHRS2"); } } public IColumn DAY2{ get{ return this.GetColumn("DAY2"); } } public IColumn AHEAD3{ get{ return this.GetColumn("AHEAD3"); } } public IColumn IN3{ get{ return this.GetColumn("IN3"); } } public IColumn NEEDIN3{ get{ return this.GetColumn("NEEDIN3"); } } public IColumn BOVERTIME3{ get{ return this.GetColumn("BOVERTIME3"); } } public IColumn OUT3{ get{ return this.GetColumn("OUT3"); } } public IColumn DELAY3{ get{ return this.GetColumn("DELAY3"); } } public IColumn NEEDOUT3{ get{ return this.GetColumn("NEEDOUT3"); } } public IColumn EOVERTIME3{ get{ return this.GetColumn("EOVERTIME3"); } } public IColumn REST3{ get{ return this.GetColumn("REST3"); } } public IColumn REST_BEGIN3{ get{ return this.GetColumn("REST_BEGIN3"); } } public IColumn BREAK3{ get{ return this.GetColumn("BREAK3"); } } public IColumn OT3{ get{ return this.GetColumn("OT3"); } } public IColumn EXT3{ get{ return this.GetColumn("EXT3"); } } public IColumn CANOT3{ get{ return this.GetColumn("CANOT3"); } } public IColumn OT_REST3{ get{ return this.GetColumn("OT_REST3"); } } public IColumn OT_REST_BEGIN3{ get{ return this.GetColumn("OT_REST_BEGIN3"); } } public IColumn BASICHRS3{ get{ return this.GetColumn("BASICHRS3"); } } public IColumn NEEDHRS3{ get{ return this.GetColumn("NEEDHRS3"); } } public IColumn DAY3{ get{ return this.GetColumn("DAY3"); } } public IColumn AHEAD4{ get{ return this.GetColumn("AHEAD4"); } } public IColumn IN4{ get{ return this.GetColumn("IN4"); } } public IColumn NEEDIN4{ get{ return this.GetColumn("NEEDIN4"); } } public IColumn BOVERTIME4{ get{ return this.GetColumn("BOVERTIME4"); } } public IColumn OUT4{ get{ return this.GetColumn("OUT4"); } } public IColumn DELAY4{ get{ return this.GetColumn("DELAY4"); } } public IColumn NEEDOUT4{ get{ return this.GetColumn("NEEDOUT4"); } } public IColumn EOVERTIME4{ get{ return this.GetColumn("EOVERTIME4"); } } public IColumn REST4{ get{ return this.GetColumn("REST4"); } } public IColumn REST_BEGIN4{ get{ return this.GetColumn("REST_BEGIN4"); } } public IColumn BREAK4{ get{ return this.GetColumn("BREAK4"); } } public IColumn OT4{ get{ return this.GetColumn("OT4"); } } public IColumn EXT4{ get{ return this.GetColumn("EXT4"); } } public IColumn CANOT4{ get{ return this.GetColumn("CANOT4"); } } public IColumn OT_REST4{ get{ return this.GetColumn("OT_REST4"); } } public IColumn OT_REST_BEGIN4{ get{ return this.GetColumn("OT_REST_BEGIN4"); } } public IColumn BASICHRS4{ get{ return this.GetColumn("BASICHRS4"); } } public IColumn NEEDHRS4{ get{ return this.GetColumn("NEEDHRS4"); } } public IColumn DAY4{ get{ return this.GetColumn("DAY4"); } } } }
// 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. #if DJANGO_HTML_EDITOR using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.PythonTools.Django.Analysis; using Microsoft.PythonTools.Interpreter; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudio.Text; using Microsoft.PythonTools.Django.TemplateParsing.DjangoBlocks; using Microsoft.PythonTools.Django.TemplateParsing; using TestUtilities; using Classification = Microsoft.PythonTools.Django.TemplateParsing.Classification; namespace DjangoTests { [TestClass] public class DjangoTemplateParserTests { #region Filter parser tests [TestMethod, Priority(UnitTestPriority.P0)] public void FilterRegexTests() { var testCases = new[] { new { Got = ("100"), Expected = DjangoVariable.Number("100", 0) }, new { Got = ("100.0"), Expected = DjangoVariable.Number("100.0", 0) }, new { Got = ("+100"), Expected = DjangoVariable.Number("+100", 0) }, new { Got = ("-100"), Expected = DjangoVariable.Number("-100", 0) }, new { Got = ("'fob'"), Expected = DjangoVariable.Constant("'fob'", 0) }, new { Got = ("\"fob\""), Expected = DjangoVariable.Constant("\"fob\"", 0) }, new { Got = ("fob"), Expected = DjangoVariable.Variable("fob", 0) }, new { Got = ("fob.oar"), Expected = DjangoVariable.Variable("fob.oar", 0) }, new { Got = ("fob|oar"), Expected = DjangoVariable.Variable("fob", 0, new DjangoFilter("oar", 4)) }, new { Got = ("fob|oar|baz"), Expected = DjangoVariable.Variable("fob", 0, new DjangoFilter("oar", 4), new DjangoFilter("baz", 8)) }, new { Got = ("fob|oar:'fob'"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Constant("oar", 4, "'fob'", 8)) }, new { Got = ("fob|oar:42"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Number("oar", 4, "42", 8)) }, new { Got = ("fob|oar:\"fob\""), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Constant("oar", 4, "\"fob\"", 8)) }, new { Got = ("fob|oar:100"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Number("oar", 4, "100", 8)) }, new { Got = ("fob|oar:100.0"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Number("oar", 4, "100.0", 8)) }, new { Got = ("fob|oar:+100.0"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Number("oar", 4, "+100.0", 8)) }, new { Got = ("fob|oar:-100.0"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Number("oar", 4, "-100.0", 8)) }, new { Got = ("fob|oar:baz.quox"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Variable("oar", 4, "baz.quox", 8)) }, new { Got = ("fob|oar:baz"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Variable("oar", 4, "baz", 8)) }, new { Got = ("{{ 100 }}"), Expected = DjangoVariable.Number("100", 3) }, new { Got = ("{{ 100.0 }}"), Expected = DjangoVariable.Number("100.0", 3) }, new { Got = ("{{ +100 }}"), Expected = DjangoVariable.Number("+100", 3) }, new { Got = ("{{ -100 }}"), Expected = DjangoVariable.Number("-100", 3) }, new { Got = ("{{ 'fob' }}"), Expected = DjangoVariable.Constant("'fob'", 3) }, new { Got = ("{{ \"fob\" }}"), Expected = DjangoVariable.Constant("\"fob\"", 3) }, new { Got = ("{{ fob }}"), Expected = DjangoVariable.Variable("fob", 3) }, new { Got = ("{{ fob.oar }}"), Expected = DjangoVariable.Variable("fob.oar", 3) }, new { Got = ("{{ fob|oar }}"), Expected = DjangoVariable.Variable("fob", 3, new DjangoFilter("oar", 7)) }, new { Got = ("{{ fob|oar|baz }}"), Expected = DjangoVariable.Variable("fob", 3, new DjangoFilter("oar", 7), new DjangoFilter("baz", 11)) }, new { Got = ("{{ fob|oar:'fob' }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Constant("oar", 7, "'fob'", 11)) }, new { Got = ("{{ fob|oar:42 }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Number("oar", 7, "42", 11)) }, new { Got = ("{{ fob|oar:\"fob\" }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Constant("oar", 7, "\"fob\"", 11)) }, new { Got = ("{{ fob|oar:100 }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Number("oar", 7, "100", 11)) }, new { Got = ("{{ fob|oar:100.0 }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Number("oar", 7, "100.0", 11)) }, new { Got = ("{{ fob|oar:+100.0 }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Number("oar", 7, "+100.0", 11)) }, new { Got = ("{{ fob|oar:-100.0 }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Number("oar", 7, "-100.0", 11)) }, new { Got = ("{{ fob|oar:baz.quox }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Variable("oar", 7, "baz.quox", 11)) }, new { Got = ("{{ fob|oar:baz }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Variable("oar", 7, "baz", 11)) }, }; foreach (var testCase in testCases) { Console.WriteLine(testCase.Got); var got = DjangoVariable.Parse(testCase.Got); ValidateFilter(testCase.Expected, got); } } internal void ValidateFilter(DjangoVariable got, DjangoVariable expected) { Assert.AreEqual(expected.Expression.Value, got.Expression.Value); Assert.AreEqual(expected.Expression.Kind, got.Expression.Kind); Assert.AreEqual(expected.ExpressionStart, got.ExpressionStart); Assert.AreEqual(expected.Filters.Length, got.Filters.Length); for (int i = 0; i < expected.Filters.Length; i++) { if (expected.Filters[i].Arg == null) { Assert.AreEqual(null, got.Filters[i].Arg); } else { Assert.AreEqual(expected.Filters[i].Arg.Value, got.Filters[i].Arg.Value); Assert.AreEqual(expected.Filters[i].Arg.Kind, got.Filters[i].Arg.Kind); Assert.AreEqual(expected.Filters[i].ArgStart, got.Filters[i].ArgStart); } Assert.AreEqual(expected.Filters[i].Filter, got.Filters[i].Filter); } } #endregion #region Block parser tests [TestMethod, Priority(UnitTestPriority.P0)] public void BlockParserTests() { var testCases = new[] { new { Got = ("for x in "), Expected = (DjangoBlock)new DjangoForBlock(new BlockParseInfo("for", "x in ", 0), 6, null, 9, -1, new[] { new Tuple<string, int>("x", 4) }), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 9, Expected = new[] { "fob", "oar" } }, new { Position = 4, Expected = new string[0] } } }, new { Got = ("for x in oar"), Expected = (DjangoBlock)new DjangoForBlock(new BlockParseInfo("for", "x in oar", 0), 6, DjangoVariable.Variable("oar", 9), 12, -1, new[] { new Tuple<string, int>("x", 4) }), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 9, Expected = new[] { "fob", "oar" } }, new { Position = 4, Expected = new string[0] } } }, new { Got = ("for x in b"), Expected = (DjangoBlock)new DjangoForBlock(new BlockParseInfo("for", "x in b", 0), 6, DjangoVariable.Variable("b", 9), 10, -1, new[] { new Tuple<string, int>("x", 4) }), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 10, Expected = new [] { "fob", "oar" } }, new { Position = 4, Expected = new string[0] } } }, new { Got = ("autoescape"), Expected = (DjangoBlock)new DjangoAutoEscapeBlock(new BlockParseInfo("autoescape", "", 0), -1, -1), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 10, Expected = new[] { "on", "off" } } } }, new { Got = ("autoescape on"), Expected = (DjangoBlock)new DjangoAutoEscapeBlock(new BlockParseInfo("autoescape", " on", 0), 11, 2), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 10, Expected = new string[0] } } }, new { Got = ("comment"), Expected = (DjangoBlock)new DjangoArgumentlessBlock(new BlockParseInfo("comment", "", 0)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 0, Expected = new string[0] } } }, new { Got = ("spaceless"), Expected = (DjangoBlock)new DjangoSpacelessBlock(new BlockParseInfo("spaceless", "", 0)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 0, Expected = new string[0] } } }, new { Got = ("filter "), Expected = (DjangoBlock)new DjangoFilterBlock(new BlockParseInfo("filter", " ", 0), DjangoVariable.Variable("", 7)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 7, Expected = new [] { "cut", "lower" } } } }, new { Got = ("ifequal "), Expected = (DjangoBlock)new DjangoIfOrIfNotEqualBlock(new BlockParseInfo("ifequal", " ", 0), DjangoVariable.Variable("", 8)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 8, Expected = new [] { "fob", "oar" } } } }, new { Got = ("ifequal fob "), Expected = (DjangoBlock)new DjangoIfOrIfNotEqualBlock(new BlockParseInfo("ifequal", " fob ", 0), DjangoVariable.Variable("fob", 8)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 12, Expected = new [] { "fob", "oar" } } } }, new { Got = ("if "), Expected = (DjangoBlock)new DjangoIfBlock(new BlockParseInfo("if", " ", 0)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 3, Expected = new [] { "fob", "oar", "not" } } } }, new { Got = ("if fob "), Expected = (DjangoBlock)new DjangoIfBlock(new BlockParseInfo("if", " fob ", 0), new BlockClassification(new Span(3, 3), Classification.Identifier)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 7, Expected = new [] { "and", "or" } } } }, new { Got = ("if fob and "), Expected = (DjangoBlock)new DjangoIfBlock(new BlockParseInfo("if", " fob and ", 0), new BlockClassification(new Span(3, 3), Classification.Identifier), new BlockClassification(new Span(7, 3), Classification.Keyword)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 11, Expected = new [] { "fob", "oar", "not" } } } }, new { Got = ("firstof "), Expected = (DjangoBlock)new DjangoMultiVariableArgumentBlock(new BlockParseInfo("firstof", " ", 0)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 8, Expected = new [] { "fob", "oar" } } } }, new { Got = ("firstof fob|"), Expected = (DjangoBlock)new DjangoMultiVariableArgumentBlock(new BlockParseInfo("firstof", " fob|", 0), DjangoVariable.Variable("fob", 8)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 12, Expected = new [] { "cut", "lower" } } } }, new { Got = ("spaceless "), Expected = (DjangoBlock)new DjangoSpacelessBlock(new BlockParseInfo("spaceless", " ", 0)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 10, Expected = new string[0] } } }, new { Got = ("widthratio "), Expected = (DjangoBlock)new DjangoWidthRatioBlock(new BlockParseInfo("widthratio", " ", 0)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 11, Expected = new [] { "fob", "oar" } } } }, new { Got = ("templatetag "), Expected = (DjangoBlock)new DjangoTemplateTagBlock(new BlockParseInfo("templatetag", " ", 0), 11, null), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 11, Expected = new [] { "openblock", "closeblock", "openvariable", "closevariable", "openbrace", "closebrace", "opencomment", "closecomment" } } } }, new { Got = ("templatetag open"), Expected = (DjangoBlock)new DjangoTemplateTagBlock(new BlockParseInfo("templatetag", " open", 0), 11, null), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 15, Expected = new [] { "openblock", "openvariable", "openbrace", "opencomment" } } } }, new { Got = ("templatetag openblock "), Expected = (DjangoBlock)new DjangoTemplateTagBlock(new BlockParseInfo("templatetag", " openblock ", 0), 11, "openblock"), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 22, Expected = new string[0] } } }, new { Got = ("url "), Expected = (DjangoBlock)new DjangoUrlBlock(new BlockParseInfo("url", " ", 0), Array.Empty<BlockClassification>()), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 4, Expected = new[] { "'fob:oar-url'", "'cut:lower-url'" } } } }, new { Got = ("url 'fob:oar-url' "), Expected = (DjangoBlock)new DjangoUrlBlock(new BlockParseInfo("url", " 'fob:oar-url' ", 0), new[] { new BlockClassification(new Span(4, 13), Classification.Identifier) }, "fob:oar-url"), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 18, Expected = new[] { "as", "fob", "oar", "param1=", "param2=" } } } }, new { Got = ("url 'fob:oar-url' param2=fob "), Expected = (DjangoBlock)new DjangoUrlBlock(new BlockParseInfo("url", " 'fob:oar-url' param2=fob ", 0), new[] { new BlockClassification(new Span(4, 13), Classification.Identifier), new BlockClassification(new Span(18, 10), Classification.Identifier) }, "fob:oar-url", new[] { "param2" }), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 29, Expected = new[] { "as", "fob", "oar", "param1=" } } } } }; foreach (var testCase in testCases) { Console.WriteLine(testCase.Got); var got = DjangoBlock.Parse(testCase.Got); ValidateBlock(testCase.Expected, got); foreach (var completionCase in testCase.Completions) { var completions = new HashSet<string>(got.GetCompletions(testCase.Context, completionCase.Position).Select(x => x.DisplayText)); Assert.AreEqual(completionCase.Expected.Length, completions.Count); var expected = new HashSet<string>(completionCase.Expected); foreach (var value in completions) { Assert.IsTrue(expected.Contains(value)); } } } } private static Dictionary<Type, Action<DjangoBlock, DjangoBlock>> _blockValidators = MakeBlockValidators(); private static Dictionary<Type, Action<DjangoBlock, DjangoBlock>> MakeBlockValidators() { return new Dictionary<Type, Action<DjangoBlock, DjangoBlock>>() { { typeof(DjangoForBlock), ValidateForBlock }, { typeof(DjangoAutoEscapeBlock), ValidateAutoEscape }, { typeof(DjangoArgumentlessBlock), ValidateArgumentless }, { typeof(DjangoFilterBlock), ValidateFilter }, { typeof(DjangoIfOrIfNotEqualBlock), ValidateIfOrIfNotEqualBlock}, { typeof(DjangoIfBlock), ValidateIfBlock}, { typeof(DjangoMultiVariableArgumentBlock), ValidateMultiArgumentBlock}, { typeof(DjangoSpacelessBlock), ValidateSpacelessBlock}, { typeof(DjangoTemplateTagBlock), ValidateTemplateTagBlock }, { typeof(DjangoWidthRatioBlock), ValidateWidthRatioBlock }, { typeof(DjangoUrlBlock), ValidateUrlBlock } }; } private static void ValidateWidthRatioBlock(DjangoBlock expected, DjangoBlock got) { var withExpected = (DjangoWidthRatioBlock)expected; var withGot = (DjangoWidthRatioBlock)got; Assert.AreEqual(withExpected.ParseInfo.Start, withGot.ParseInfo.Start); Assert.AreEqual(withExpected.ParseInfo.Command, withGot.ParseInfo.Command); Assert.AreEqual(withExpected.ParseInfo.Args, withGot.ParseInfo.Args); } private static void ValidateTemplateTagBlock(DjangoBlock expected, DjangoBlock got) { var tempTagExpected = (DjangoTemplateTagBlock)expected; var tempTagGot = (DjangoTemplateTagBlock)got; Assert.AreEqual(tempTagExpected.ParseInfo.Start, tempTagGot.ParseInfo.Start); Assert.AreEqual(tempTagExpected.ParseInfo.Command, tempTagGot.ParseInfo.Command); Assert.AreEqual(tempTagExpected.ParseInfo.Args, tempTagGot.ParseInfo.Args); } private static void ValidateSpacelessBlock(DjangoBlock expected, DjangoBlock got) { var spacelessExpected = (DjangoSpacelessBlock)expected; var spacelessGot = (DjangoSpacelessBlock)got; Assert.AreEqual(spacelessExpected.ParseInfo.Start, spacelessGot.ParseInfo.Start); Assert.AreEqual(spacelessExpected.ParseInfo.Command, spacelessGot.ParseInfo.Command); Assert.AreEqual(spacelessExpected.ParseInfo.Args, spacelessGot.ParseInfo.Args); } private static void ValidateMultiArgumentBlock(DjangoBlock expected, DjangoBlock got) { var maExpected = (DjangoMultiVariableArgumentBlock)expected; var maGot = (DjangoMultiVariableArgumentBlock)got; Assert.AreEqual(maExpected.ParseInfo.Start, maGot.ParseInfo.Start); Assert.AreEqual(maExpected.ParseInfo.Command, maGot.ParseInfo.Command); Assert.AreEqual(maExpected.ParseInfo.Args, maGot.ParseInfo.Args); } private static void ValidateIfBlock(DjangoBlock expected, DjangoBlock got) { var ifExpected = (DjangoIfBlock)expected; var ifGot = (DjangoIfBlock)got; Assert.AreEqual(ifExpected.ParseInfo.Start, ifGot.ParseInfo.Start); Assert.AreEqual(ifExpected.ParseInfo.Command, ifGot.ParseInfo.Command); Assert.AreEqual(ifExpected.ParseInfo.Args, ifGot.ParseInfo.Args); Assert.AreEqual(ifExpected.Args.Length, ifGot.Args.Length); for (int i = 0; i < ifExpected.Args.Length; i++) { Assert.AreEqual(ifExpected.Args[i], ifGot.Args[i]); } } private static void ValidateIfOrIfNotEqualBlock(DjangoBlock expected, DjangoBlock got) { var ifExpected = (DjangoIfOrIfNotEqualBlock)expected; var ifGot = (DjangoIfOrIfNotEqualBlock)got; Assert.AreEqual(ifExpected.ParseInfo.Start, ifGot.ParseInfo.Start); Assert.AreEqual(ifExpected.ParseInfo.Command, ifGot.ParseInfo.Command); Assert.AreEqual(ifExpected.ParseInfo.Args, ifGot.ParseInfo.Args); } private static void ValidateFilter(DjangoBlock expected, DjangoBlock got) { var filterExpected = (DjangoFilterBlock)expected; var filterGot = (DjangoFilterBlock)got; Assert.AreEqual(filterExpected.ParseInfo.Start, filterGot.ParseInfo.Start); Assert.AreEqual(filterExpected.ParseInfo.Command, filterGot.ParseInfo.Command); Assert.AreEqual(filterExpected.ParseInfo.Args, filterGot.ParseInfo.Args); } private static void ValidateForBlock(DjangoBlock expected, DjangoBlock got) { var forExpected = (DjangoForBlock)expected; var forGot = (DjangoForBlock)got; Assert.AreEqual(forExpected.ParseInfo.Start, forGot.ParseInfo.Start); Assert.AreEqual(forExpected.InStart, forGot.InStart); } private static void ValidateAutoEscape(DjangoBlock expected, DjangoBlock got) { var aeExpected = (DjangoAutoEscapeBlock)expected; var aeGot = (DjangoAutoEscapeBlock)got; Assert.AreEqual(aeExpected.ParseInfo.Start, aeGot.ParseInfo.Start); Assert.AreEqual(aeExpected.ParseInfo.Command, aeGot.ParseInfo.Command); Assert.AreEqual(aeExpected.ParseInfo.Args, aeGot.ParseInfo.Args); } private static void ValidateArgumentless(DjangoBlock expected, DjangoBlock got) { var aeExpected = (DjangoArgumentlessBlock)expected; var aeGot = (DjangoArgumentlessBlock)got; Assert.AreEqual(aeExpected.ParseInfo.Start, aeGot.ParseInfo.Start); Assert.AreEqual(aeExpected.ParseInfo.Command, aeGot.ParseInfo.Command); Assert.AreEqual(aeExpected.ParseInfo.Args, aeGot.ParseInfo.Args); } private static void ValidateUrlBlock(DjangoBlock expected, DjangoBlock got) { var urlExpected = (DjangoUrlBlock)expected; var urlGot = (DjangoUrlBlock)got; Assert.AreEqual(urlExpected.ParseInfo.Start, urlGot.ParseInfo.Start); Assert.AreEqual(urlExpected.ParseInfo.Command, urlGot.ParseInfo.Command); Assert.AreEqual(urlExpected.ParseInfo.Args, urlGot.ParseInfo.Args); Assert.AreEqual(urlExpected.Args.Length, urlGot.Args.Length); for (int i = 0; i < urlExpected.Args.Length; i++) { Assert.AreEqual(urlExpected.Args[i], urlGot.Args[i]); } } private void ValidateBlock(DjangoBlock expected, DjangoBlock got) { Assert.AreEqual(expected.GetType(), got.GetType()); _blockValidators[expected.GetType()](expected, got); } #endregion #region Template tokenizer tests [TestMethod, Priority(UnitTestPriority.P0)] public void TestSimpleVariable() { var code = @"<html> <head><title></title></head> <body> {{ content }} </body> </html>"; TokenizerTest(code, new TemplateToken(TemplateTokenKind.Text, 0, 49), new TemplateToken(TemplateTokenKind.Variable, 50, 62), new TemplateToken(TemplateTokenKind.Text, 63, 82) ); } [TestMethod, Priority(UnitTestPriority.P0)] //UnitTestPriority.CORE_UNIT_TEST = 0 public void TestEmbeddedWrongClose() { var code = @"<html> <head><title></title></head> <body> {{ content %} }} </body> </html>"; TokenizerTest(code, new TemplateToken(TemplateTokenKind.Text, 0, 49), new TemplateToken(TemplateTokenKind.Variable, 50, 65), new TemplateToken(TemplateTokenKind.Text, 66, 85) ); } [TestMethod, Priority(UnitTestPriority.P0)] public void SingleTrailingChar() { foreach (var code in new[] { "{{fob}}\n", "{{fob}}a" }) { TokenizerTest(code, new TemplateToken(TemplateTokenKind.Variable, 0, 6), new TemplateToken(TemplateTokenKind.Text, 7, 7) ); } } // struct TemplateTokenResult { public readonly TemplateToken Token; public readonly char? Start, End; public TemplateTokenResult(TemplateToken token, char? start = null, char? end = null) { Token = token; Start = start; End = end; } public static implicit operator TemplateTokenResult(TemplateToken token) { return new TemplateTokenResult(token); } } [TestMethod, Priority(UnitTestPriority.P0)] public void TestSimpleBlock() { var code = @"<html> <head><title></title></head> <body> {% block %} </body> </html>"; TokenizerTest(code, new TemplateToken(TemplateTokenKind.Text, 0, 49), new TemplateToken(TemplateTokenKind.Block, 50, 60), new TemplateToken(TemplateTokenKind.Text, 61, code.Length - 1)); } [TestMethod, Priority(UnitTestPriority.P0)] public void TestSimpleComment() { var code = @"<html> <head><title></title></head> <body> {# comment #} </body> </html>"; TokenizerTest(code, new TemplateToken(TemplateTokenKind.Text, 0, 49), new TemplateToken(TemplateTokenKind.Comment, 50, 62), new TemplateToken(TemplateTokenKind.Text, 63, code.Length - 1)); } [TestMethod, Priority(UnitTestPriority.P0)] public void TestUnclosedVariable() { var code = @"<html> <head><title></title></head> <body> {{ content </body> </html>"; TokenizerTest(code, /*unclosed*/true, new TemplateToken(TemplateTokenKind.Text, 0, 49), new TemplateToken(TemplateTokenKind.Variable, 50, 80, isClosed: false) ); } [TestMethod, Priority(UnitTestPriority.P0)] public void TestTextStartAndEnd() { var code = @"<html> <head><title></title></head> <body> <p>{{ content }}</p> </body> </html>"; TokenizerTest(code, new TemplateTokenResult( new TemplateToken(TemplateTokenKind.Text, 0, code.IndexOf("<p>") + 2), '<', '>' ), new TemplateToken(TemplateTokenKind.Variable, code.IndexOf("<p>") + 3, code.IndexOf("</p>") - 1), new TemplateTokenResult( new TemplateToken(TemplateTokenKind.Text, code.IndexOf("</p>"), code.Length - 1), '<', '>' ) ); } [TestMethod, Priority(UnitTestPriority.P0)] public void TestUnclosedComment() { var code = @"<html> <head><title></title></head> <body> {# content </body> </html>"; TokenizerTest(code, /*unclosed*/true, new TemplateToken(TemplateTokenKind.Text, 0, 49), new TemplateToken(TemplateTokenKind.Comment, 50, 80, isClosed: false) ); } [TestMethod, Priority(UnitTestPriority.P0)] public void TestUnclosedBlock() { var code = @"<html> <head><title></title></head> <body> {% content </body> </html>"; TokenizerTest(code, /*unclosed*/true, new TemplateToken(TemplateTokenKind.Text, 0, 49), new TemplateToken(TemplateTokenKind.Block, 50, 80, isClosed: false) ); } private void TokenizerTest(string text, params TemplateTokenResult[] expected) { TokenizerTest(text, false, expected); } private void TokenizerTest(string text, bool unclosed, params TemplateTokenResult[] expected) { var tokenizer = new TemplateTokenizer(new StringReader(text)); var tokens = tokenizer.GetTokens().ToArray(); bool passed = false; try { Assert.AreEqual(expected.Length, tokens.Length); Assert.AreEqual(0, tokens[0].Start); Assert.AreEqual(text.Length - 1, tokens[tokens.Length - 1].End); for (int i = 0; i < expected.Length; i++) { var expectedToken = expected[i].Token; Assert.AreEqual(expectedToken.Kind, tokens[i].Kind); Assert.AreEqual(expectedToken.Start, tokens[i].Start); Assert.AreEqual(expectedToken.End, tokens[i].End); switch (expectedToken.Kind) { case TemplateTokenKind.Block: case TemplateTokenKind.Comment: case TemplateTokenKind.Variable: Assert.AreEqual('{', text[expectedToken.Start]); if (!unclosed) { Assert.AreEqual('}', text[expectedToken.End]); } break; } if (expected[i].Start != null) { Assert.AreEqual(expected[i].Start, text[expectedToken.Start]); } if (expected[i].End != null) { Assert.AreEqual(expected[i].End, text[expectedToken.End]); } } passed = true; } finally { if (!passed) { List<string> res = new List<string>(); for (int i = 0; i < tokens.Length; i++) { res.Add( String.Format("new TemplateToken(TemplateTokenKind.{0}, {1}, {2})", tokens[i].Kind, tokens[i].Start, tokens[i].End ) ); } Console.WriteLine(String.Join(",\r\n", res)); } } } #endregion } class TestCompletionContext : IDjangoCompletionContext { private readonly string[] _variables; private readonly Dictionary<string, TagInfo> _filters; internal static TestCompletionContext Simple = new TestCompletionContext(new[] { "fob", "oar" }, new[] { "cut", "lower" }); public TestCompletionContext(string[] variables, string[] filters) { _variables = variables; _filters = new Dictionary<string, TagInfo>(); foreach (var filter in filters) { _filters[filter] = new TagInfo("", null); } } #region IDjangoCompletionContext Members public Dictionary<string, TagInfo> Filters { get { return _filters; } } public string[] Variables { get { return _variables; } } public DjangoUrl[] Urls { get { return new[] { new DjangoUrl("fob:oar-url", "^fob/(?P<param1>[0-9]+)/(?P<param2>[0-9]+)/([0-9]+)$"), new DjangoUrl("cut:lower-url", "^cut/$") }; } } public Dictionary<string, PythonMemberType> GetMembers(string name) { return new Dictionary<string, PythonMemberType>(); } #endregion } } #endif
/* * Copyright (c) 2007-2008, openmetaverse.org * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization; namespace OpenMetaverse { /// <summary> /// Exception class to identify inventory exceptions /// </summary> public class InventoryException : Exception { public InventoryException(string message) : base(message) { } } /// <summary> /// Responsible for maintaining inventory structure. Inventory constructs nodes /// and manages node children as is necessary to maintain a coherant hirarchy. /// Other classes should not manipulate or create InventoryNodes explicitly. When /// A node's parent changes (when a folder is moved, for example) simply pass /// Inventory the updated InventoryFolder and it will make the appropriate changes /// to its internal representation. /// </summary> public class Inventory { /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<InventoryObjectUpdatedEventArgs> m_InventoryObjectUpdated; ///<summary>Raises the InventoryObjectUpdated Event</summary> /// <param name="e">A InventoryObjectUpdatedEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnInventoryObjectUpdated(InventoryObjectUpdatedEventArgs e) { EventHandler<InventoryObjectUpdatedEventArgs> handler = m_InventoryObjectUpdated; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_InventoryObjectUpdatedLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<InventoryObjectUpdatedEventArgs> InventoryObjectUpdated { add { lock (m_InventoryObjectUpdatedLock) { m_InventoryObjectUpdated += value; } } remove { lock (m_InventoryObjectUpdatedLock) { m_InventoryObjectUpdated -= value; } } } /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<InventoryObjectRemovedEventArgs> m_InventoryObjectRemoved; ///<summary>Raises the InventoryObjectRemoved Event</summary> /// <param name="e">A InventoryObjectRemovedEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnInventoryObjectRemoved(InventoryObjectRemovedEventArgs e) { EventHandler<InventoryObjectRemovedEventArgs> handler = m_InventoryObjectRemoved; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_InventoryObjectRemovedLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<InventoryObjectRemovedEventArgs> InventoryObjectRemoved { add { lock (m_InventoryObjectRemovedLock) { m_InventoryObjectRemoved += value; } } remove { lock (m_InventoryObjectRemovedLock) { m_InventoryObjectRemoved -= value; } } } /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<InventoryObjectAddedEventArgs> m_InventoryObjectAdded; ///<summary>Raises the InventoryObjectAdded Event</summary> /// <param name="e">A InventoryObjectAddedEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnInventoryObjectAdded(InventoryObjectAddedEventArgs e) { EventHandler<InventoryObjectAddedEventArgs> handler = m_InventoryObjectAdded; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_InventoryObjectAddedLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<InventoryObjectAddedEventArgs> InventoryObjectAdded { add { lock (m_InventoryObjectAddedLock) { m_InventoryObjectAdded += value; } } remove { lock (m_InventoryObjectAddedLock) { m_InventoryObjectAdded -= value; } } } /// <summary> /// The root folder of this avatars inventory /// </summary> public InventoryFolder RootFolder { get { return RootNode.Data as InventoryFolder; } set { UpdateNodeFor(value); _RootNode = Items[value.UUID]; } } /// <summary> /// The default shared library folder /// </summary> public InventoryFolder LibraryFolder { get { return LibraryRootNode.Data as InventoryFolder; } set { UpdateNodeFor(value); _LibraryRootNode = Items[value.UUID]; } } private InventoryNode _LibraryRootNode; private InventoryNode _RootNode; /// <summary> /// The root node of the avatars inventory /// </summary> public InventoryNode RootNode { get { return _RootNode; } } /// <summary> /// The root node of the default shared library /// </summary> public InventoryNode LibraryRootNode { get { return _LibraryRootNode; } } public UUID Owner { get { return _Owner; } } private UUID _Owner; private GridClient Client; //private InventoryManager Manager; public Dictionary<UUID, InventoryNode> Items = new Dictionary<UUID, InventoryNode>(); public Inventory(GridClient client, InventoryManager manager) : this(client, manager, client.Self.AgentID) { } public Inventory(GridClient client, InventoryManager manager, UUID owner) { Client = client; //Manager = manager; _Owner = owner; if (owner == UUID.Zero) Logger.Log("Inventory owned by nobody!", Helpers.LogLevel.Warning, Client); Items = new Dictionary<UUID, InventoryNode>(); } public List<InventoryBase> GetContents(InventoryFolder folder) { return GetContents(folder.UUID); } /// <summary> /// Returns the contents of the specified folder /// </summary> /// <param name="folder">A folder's UUID</param> /// <returns>The contents of the folder corresponding to <code>folder</code></returns> /// <exception cref="InventoryException">When <code>folder</code> does not exist in the inventory</exception> public List<InventoryBase> GetContents(UUID folder) { InventoryNode folderNode; if (!Items.TryGetValue(folder, out folderNode)) throw new InventoryException("Unknown folder: " + folder); lock (folderNode.Nodes.SyncRoot) { List<InventoryBase> contents = new List<InventoryBase>(folderNode.Nodes.Count); foreach (InventoryNode node in folderNode.Nodes.Values) { contents.Add(node.Data); } return contents; } } /// <summary> /// Updates the state of the InventoryNode and inventory data structure that /// is responsible for the InventoryObject. If the item was previously not added to inventory, /// it adds the item, and updates structure accordingly. If it was, it updates the /// InventoryNode, changing the parent node if <code>item.parentUUID</code> does /// not match <code>node.Parent.Data.UUID</code>. /// /// You can not set the inventory root folder using this method /// </summary> /// <param name="item">The InventoryObject to store</param> public void UpdateNodeFor(InventoryBase item) { lock (Items) { InventoryNode itemParent = null; if (item.ParentUUID != UUID.Zero && !Items.TryGetValue(item.ParentUUID, out itemParent)) { // OK, we have no data on the parent, let's create a fake one. InventoryFolder fakeParent = new InventoryFolder(item.ParentUUID); fakeParent.DescendentCount = 1; // Dear god, please forgive me. itemParent = new InventoryNode(fakeParent); Items[item.ParentUUID] = itemParent; // Unfortunately, this breaks the nice unified tree // while we're waiting for the parent's data to come in. // As soon as we get the parent, the tree repairs itself. //Logger.DebugLog("Attempting to update inventory child of " + // item.ParentUUID.ToString() + " when we have no local reference to that folder", Client); if (Client.Settings.FETCH_MISSING_INVENTORY) { // Fetch the parent List<UUID> fetchreq = new List<UUID>(1); fetchreq.Add(item.ParentUUID); } } InventoryNode itemNode; if (Items.TryGetValue(item.UUID, out itemNode)) // We're updating. { InventoryNode oldParent = itemNode.Parent; // Handle parent change if (oldParent == null || itemParent == null || itemParent.Data.UUID != oldParent.Data.UUID) { if (oldParent != null) { lock (oldParent.Nodes.SyncRoot) oldParent.Nodes.Remove(item.UUID); } if (itemParent != null) { lock (itemParent.Nodes.SyncRoot) itemParent.Nodes[item.UUID] = itemNode; } } itemNode.Parent = itemParent; if (m_InventoryObjectUpdated != null) { OnInventoryObjectUpdated(new InventoryObjectUpdatedEventArgs(itemNode.Data, item)); } itemNode.Data = item; } else // We're adding. { itemNode = new InventoryNode(item, itemParent); Items.Add(item.UUID, itemNode); if (m_InventoryObjectAdded != null) { OnInventoryObjectAdded(new InventoryObjectAddedEventArgs(item)); } } } } public InventoryNode GetNodeFor(UUID uuid) { return Items[uuid]; } /// <summary> /// Removes the InventoryObject and all related node data from Inventory. /// </summary> /// <param name="item">The InventoryObject to remove.</param> public void RemoveNodeFor(InventoryBase item) { lock (Items) { InventoryNode node; if (Items.TryGetValue(item.UUID, out node)) { if (node.Parent != null) lock (node.Parent.Nodes.SyncRoot) node.Parent.Nodes.Remove(item.UUID); Items.Remove(item.UUID); if (m_InventoryObjectRemoved != null) { OnInventoryObjectRemoved(new InventoryObjectRemovedEventArgs(item)); } } // In case there's a new parent: InventoryNode newParent; if (Items.TryGetValue(item.ParentUUID, out newParent)) { lock (newParent.Nodes.SyncRoot) newParent.Nodes.Remove(item.UUID); } } } /// <summary> /// Used to find out if Inventory contains the InventoryObject /// specified by <code>uuid</code>. /// </summary> /// <param name="uuid">The UUID to check.</param> /// <returns>true if inventory contains uuid, false otherwise</returns> public bool Contains(UUID uuid) { return Items.ContainsKey(uuid); } public bool Contains(InventoryBase obj) { return Contains(obj.UUID); } /// <summary> /// Saves the current inventory structure to a cache file /// </summary> /// <param name="filename">Name of the cache file to save to</param> public void SaveToDisk(string filename) { try { using (Stream stream = File.Open(filename, FileMode.Create)) { BinaryFormatter bformatter = new BinaryFormatter(); lock (Items) { Logger.Log("Caching " + Items.Count.ToString() + " inventory items to " + filename, Helpers.LogLevel.Info); foreach (KeyValuePair<UUID, InventoryNode> kvp in Items) { bformatter.Serialize(stream, kvp.Value); } } } } catch (Exception e) { Logger.Log("Error saving inventory cache to disk :"+e.Message,Helpers.LogLevel.Error); } } /// <summary> /// Loads in inventory cache file into the inventory structure. Note only valid to call after login has been successful. /// </summary> /// <param name="filename">Name of the cache file to load</param> /// <returns>The number of inventory items sucessfully reconstructed into the inventory node tree</returns> public int RestoreFromDisk(string filename) { List<InventoryNode> nodes = new List<InventoryNode>(); int item_count = 0; try { if (!File.Exists(filename)) return -1; using (Stream stream = File.Open(filename, FileMode.Open)) { BinaryFormatter bformatter = new BinaryFormatter(); while (stream.Position < stream.Length) { OpenMetaverse.InventoryNode node = (InventoryNode)bformatter.Deserialize(stream); nodes.Add(node); item_count++; } } } catch (Exception e) { Logger.Log("Error accessing inventory cache file :" + e.Message, Helpers.LogLevel.Error); return -1; } Logger.Log("Read " + item_count.ToString() + " items from inventory cache file", Helpers.LogLevel.Info); item_count = 0; List<InventoryNode> del_nodes = new List<InventoryNode>(); //nodes that we have processed and will delete List<UUID> dirty_folders = new List<UUID>(); // Tainted folders that we will not restore items into // Because we could get child nodes before parents we must itterate around and only add nodes who have // a parent already in the list because we must update both child and parent to link together // But sometimes we have seen orphin nodes due to bad/incomplete data when caching so we have an emergency abort route int stuck = 0; while (nodes.Count != 0 && stuck<5) { foreach (InventoryNode node in nodes) { InventoryNode pnode; if (node.ParentID == UUID.Zero) { //We don't need the root nodes "My Inventory" etc as they will already exist for the correct // user of this cache. del_nodes.Add(node); item_count--; } else if(Items.TryGetValue(node.Data.UUID,out pnode)) { //We already have this it must be a folder if (node.Data is InventoryFolder) { InventoryFolder cache_folder = (InventoryFolder)node.Data; InventoryFolder server_folder = (InventoryFolder)pnode.Data; if (cache_folder.Version != server_folder.Version) { Logger.DebugLog("Inventory Cache/Server version mismatch on " + node.Data.Name + " " + cache_folder.Version.ToString() + " vs " + server_folder.Version.ToString()); pnode.NeedsUpdate = true; dirty_folders.Add(node.Data.UUID); } else { pnode.NeedsUpdate = false; } del_nodes.Add(node); } } else if (Items.TryGetValue(node.ParentID, out pnode)) { if (node.Data != null) { // If node is folder, and it does not exist in skeleton, mark it as // dirty and don't process nodes that belong to it if (node.Data is InventoryFolder && !(Items.ContainsKey(node.Data.UUID))) { dirty_folders.Add(node.Data.UUID); } //Only add new items, this is most likely to be run at login time before any inventory //nodes other than the root are populated. Don't add non existing folders. if (!Items.ContainsKey(node.Data.UUID) && !dirty_folders.Contains(pnode.Data.UUID) && !(node.Data is InventoryFolder)) { Items.Add(node.Data.UUID, node); node.Parent = pnode; //Update this node with its parent pnode.Nodes.Add(node.Data.UUID, node); // Add to the parents child list item_count++; } } del_nodes.Add(node); } } if (del_nodes.Count == 0) stuck++; else stuck = 0; //Clean up processed nodes this loop around. foreach (InventoryNode node in del_nodes) nodes.Remove(node); del_nodes.Clear(); } Logger.Log("Reassembled " + item_count.ToString() + " items from inventory cache file", Helpers.LogLevel.Info); return item_count; } #region Operators /// <summary> /// By using the bracket operator on this class, the program can get the /// InventoryObject designated by the specified uuid. If the value for the corresponding /// UUID is null, the call is equivelant to a call to <code>RemoveNodeFor(this[uuid])</code>. /// If the value is non-null, it is equivelant to a call to <code>UpdateNodeFor(value)</code>, /// the uuid parameter is ignored. /// </summary> /// <param name="uuid">The UUID of the InventoryObject to get or set, ignored if set to non-null value.</param> /// <returns>The InventoryObject corresponding to <code>uuid</code>.</returns> public InventoryBase this[UUID uuid] { get { InventoryNode node = Items[uuid]; return node.Data; } set { if (value != null) { // Log a warning if there is a UUID mismatch, this will cause problems if (value.UUID != uuid) Logger.Log("Inventory[uuid]: uuid " + uuid.ToString() + " is not equal to value.UUID " + value.UUID.ToString(), Helpers.LogLevel.Warning, Client); UpdateNodeFor(value); } else { InventoryNode node; if (Items.TryGetValue(uuid, out node)) { RemoveNodeFor(node.Data); } } } } #endregion Operators } #region EventArgs classes public class InventoryObjectUpdatedEventArgs : EventArgs { private readonly InventoryBase m_OldObject; private readonly InventoryBase m_NewObject; public InventoryBase OldObject { get { return m_OldObject; } } public InventoryBase NewObject { get { return m_NewObject; } } public InventoryObjectUpdatedEventArgs(InventoryBase oldObject, InventoryBase newObject) { this.m_OldObject = oldObject; this.m_NewObject = newObject; } } public class InventoryObjectRemovedEventArgs : EventArgs { private readonly InventoryBase m_Obj; public InventoryBase Obj { get { return m_Obj; } } public InventoryObjectRemovedEventArgs(InventoryBase obj) { this.m_Obj = obj; } } public class InventoryObjectAddedEventArgs : EventArgs { private readonly InventoryBase m_Obj; public InventoryBase Obj { get { return m_Obj; } } public InventoryObjectAddedEventArgs(InventoryBase obj) { this.m_Obj = obj; } } #endregion EventArgs }
namespace Microsoft.Protocols.TestSuites.MS_ADMINS { using System; using System.Text; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; /// <summary> /// A class contains all helper methods used in test case level. /// </summary> public static class TestSuiteBase { /// <summary> /// A random generator using current time seeds. /// </summary> private static Random random; /// <summary> /// A ITestSite instance /// </summary> private static ITestSite testSite; /// <summary> /// A method used to initialize the TestSuiteBase with specified ITestSite instance. /// </summary> /// <param name="site">A parameter represents ITestSite instance.</param> public static void Initialize(ITestSite site) { testSite = site; } /// <summary> /// A method is used to get a unique site title. /// </summary> /// <returns>A return value represents the unique site title that is combined with the object name and time stamp</returns> public static string GenerateUniqueSiteTitle() { return Common.GenerateResourceName(testSite, "SiteTitle"); } /// <summary> /// A method is used to generate owner name. /// </summary> /// <returns>A return value represents the unique owner name that is combined with the object name and time stamp</returns> public static string GenerateUniqueOwnerName() { return Common.GenerateResourceName(testSite, "OwnerName"); } /// <summary> /// A method is used to generate portal name. /// </summary> /// <returns>A return value represents the unique portal name that is combined with the Object name and time stamp</returns> public static string GenerateUniquePortalName() { return Common.GenerateResourceName(testSite, "PortalName"); } /// <summary> /// This method is used to random generate an integer in the specified range. /// </summary> /// <param name="minValue">The inclusive lower bound of the random number returned.</param> /// <param name="maxValue">The exclusive upper bound of the random number returned.</param> /// <returns>A 32-bit signed integer greater than or equal to minValue and less than maxValue</returns> public static int GenerateRandomNumber(int minValue, int maxValue) { random = new Random((int)DateTime.Now.Ticks); return random.Next(minValue, maxValue); } /// <summary> /// This method is used to generate random string in the range A-Z with the specified string size. /// </summary> /// <param name="size">A parameter represents the generated string size.</param> /// <returns>Returns the random generated string.</returns> public static string GenerateRandomString(int size) { random = new Random((int)DateTime.Now.Ticks); StringBuilder builder = new StringBuilder(); char ch; for (int i = 0; i < size; i++) { int intIndex = Convert.ToInt32(Math.Floor((26 * random.NextDouble()) + 65)); ch = Convert.ToChar(intIndex); builder.Append(ch); } return builder.ToString(); } /// <summary> /// This method is used to generate random e-mail with the specified size. /// </summary> /// <param name="size">A parameter represents the generated e-mail size.</param> /// <returns>Returns the random generated e-mail.</returns> public static string GenerateEmail(int size) { string returnValue = string.Empty; string suffix = "@contoso.com"; if (size > suffix.Length) { returnValue = GenerateRandomString(size - suffix.Length) + suffix; } else { returnValue = "a" + suffix; } return returnValue; } /// <summary> /// This method is used to generate random portal url with the specified size. /// </summary> /// <param name="size">A parameter represents the generated portal url size.</param> /// <returns>Returns the random generated portal url.</returns> public static string GeneratePortalUrl(int size) { string returnValue = string.Empty; string suffix = ".com"; string prefix = "www."; if (size > prefix.Length + suffix.Length) { returnValue = prefix + GenerateRandomString(size - prefix.Length - suffix.Length) + suffix; } else { returnValue = prefix + "a" + suffix; } return returnValue; } /// <summary> /// This method is used to generate random url without port number which includes [TransportType]://[SUTComputerName]. /// </summary> /// <param name="size">A parameter represents the random string size.</param> /// <returns>Returns the random generated url.</returns> public static string GenerateUrlWithoutPort(int size) { string returnValue = string.Empty; string subSite = "/sites/"; string prefix = Common.GetConfigurationPropertyValue("TransportType", testSite) + "://" + Common.GetConfigurationPropertyValue("SUTComputerName", testSite); if (size > subSite.Length) { returnValue = prefix + subSite + GenerateRandomString(size - subSite.Length); } else { returnValue = prefix + subSite + "a"; } return returnValue; } /// <summary> /// This method is used to generate a url prefix with port number. The format should be "HTTP://[SUTComputerName]:[HTTPPortNumber]/sites/" or "HTTPS://[SUTComputerName]:[HTTPSPortNumber]/sites/". /// </summary> /// <returns>Returns the generated url prefix.</returns> public static string GenerateUrlPrefixWithPortNumber() { string returnValue = string.Empty; TransportProtocol transport = Common.GetConfigurationPropertyValue<TransportProtocol>("TransportType", testSite); switch (transport) { case TransportProtocol.HTTP: returnValue = Common.GetConfigurationPropertyValue("UrlWithHTTPPortNumber", testSite); break; case TransportProtocol.HTTPS: returnValue = Common.GetConfigurationPropertyValue("UrlWithHTTPSPortNumber", testSite); break; default: testSite.Assume.Fail("Unaccepted transport type: {0}.", transport); break; } return returnValue; } /// <summary> /// This method is used to generate a url prefix with admin port number. The format should be "HTTP://[SUTComputerName]:[AdminHTTPPortNumber]/sites/" or "HTTPS://[SUTComputerName]:[AdminHTTPSPortNumber]/sites/". /// </summary> /// <returns>Returns the generated url prefix.</returns> public static string GenerateUrlPrefixWithAdminPort() { string returnValue = string.Empty; TransportProtocol transport = Common.GetConfigurationPropertyValue<TransportProtocol>("TransportType", testSite); switch (transport) { case TransportProtocol.HTTP: returnValue = Common.GetConfigurationPropertyValue("UrlWithAdminHTTPPort", testSite); break; case TransportProtocol.HTTPS: returnValue = Common.GetConfigurationPropertyValue("UrlWithAdminHTTPSPort", testSite); break; default: testSite.Assume.Fail("Unaccepted transport type: {0}.", transport); break; } return returnValue; } } }
/* This file is licensed to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Text; using System.Xml; using Org.XmlUnit.Diff; using NUnit.Framework; namespace Org.XmlUnit.Builder { [TestFixture] public class DiffBuilderTest { [Test] public void TestDiff_withoutIgnoreWhitespaces_shouldFail() { // prepare testData string controlXml = "<a><b>Test Value</b></a>"; string testXml = "<a>\n <b>\n Test Value\n </b>\n</a>"; // run test var myDiff = DiffBuilder.Compare(Input.FromString(controlXml).Build()) .WithTest(Input.FromString(testXml).Build()) .Build(); // validate result Assert.IsTrue(myDiff.HasDifferences(), myDiff.ToString()); } [Test] public void TestDiff_withIgnoreWhitespaces_shouldSucceed() { // prepare testData string controlXml = "<a><b>Test Value</b></a>"; string testXml = "<a>\n <b>\n Test Value\n </b>\n</a>"; // run test var myDiff = DiffBuilder.Compare(Input.FromString(controlXml).Build()) .WithTest(Input.FromString(testXml).Build()) .IgnoreWhitespace() .Build(); // validate result Assert.IsFalse(myDiff.HasDifferences(), "XML similar " + myDiff.ToString()); } [Test] public void TestDiff_withoutNormalizeWhitespaces_shouldFail() { // prepare testData string controlXml = "<a><b>Test Value</b></a>"; string testXml = "<a>\n <b>\n Test Value\n </b>\n</a>"; // run test var myDiff = DiffBuilder.Compare(Input.FromString(controlXml).Build()) .WithTest(Input.FromString(testXml).Build()) .Build(); // validate result Assert.IsTrue(myDiff.HasDifferences(), myDiff.ToString()); } [Test] public void TestDiff_withNormalizeWhitespaces_shouldSucceed() { // prepare testData string controlXml = "<a><b>Test Value</b></a>"; string testXml = "<a>\n <b>\n Test\nValue\n </b>\n</a>"; // run test var myDiff = DiffBuilder.Compare(Input.FromString(controlXml).Build()) .WithTest(Input.FromString(testXml).Build()) .NormalizeWhitespace() .Build(); // validate result Assert.IsFalse(myDiff.HasDifferences(), "XML similar " + myDiff.ToString()); } [Test] public void TestDiff_withNormalizeAndIgnoreWhitespaces_shouldSucceed() { // prepare testData string controlXml = "<a><b>Test Value</b></a>"; string testXml = "<a>\n <b>\n Test\n Value\n </b>\n</a>"; // run test var myDiff = DiffBuilder.Compare(Input.FromString(controlXml).Build()) .WithTest(Input.FromString(testXml).Build()) .NormalizeWhitespace() .IgnoreWhitespace() .Build(); // validate result Assert.IsFalse(myDiff.HasDifferences(), "XML similar " + myDiff.ToString()); } [Test] public void TestDiff_withCheckForIdentical_shouldFail() { // prepare testData string controlXml = "<a>Test Value</a>"; string testXml = "<a><![CDATA[Test Value]]></a>"; // run test var myDiff = DiffBuilder.Compare(Input.FromString(controlXml).Build()) .WithTest(Input.FromString(testXml).Build()) .CheckForIdentical() .Build(); // validate result Assert.IsTrue(myDiff.HasDifferences(), myDiff.ToString()); } [Test] public void TestDiff_withCheckForSimilar_shouldSucceed() { // prepare testData string controlXml = "<a>Test Value</a>"; string testXml = "<a><![CDATA[Test Value]]></a>"; // run test var myDiff = DiffBuilder.Compare(Input.FromString(controlXml).Build()) .WithTest(Input.FromString(testXml).Build()) .CheckForSimilar() .Build(); // validate result Assert.IsFalse(myDiff.HasDifferences(), "XML similar " + myDiff.ToString()); } [Test] public void TestDiff_withoutIgnoreComments_shouldFail() { // prepare testData string controlXml = "<a><b><!-- A comment -->Test Value</b></a>"; string testXml = "<a><b><!-- An other comment -->Test Value</b></a>"; // run test var myDiff = DiffBuilder.Compare(Input.FromString(controlXml).Build()) .WithTest(Input.FromString(testXml).Build()) .Build(); // validate result Assert.IsTrue(myDiff.HasDifferences(), myDiff.ToString()); } [Test] public void TestDiff_withIgnoreComments_shouldSucceed() { // prepare testData string controlXml = "<a><b><!-- A comment -->Test Value</b></a>"; string testXml = "<a><b><!-- An other comment -->Test Value</b></a>"; // run test var myDiff = DiffBuilder.Compare(Input.FromString(controlXml).Build()) .WithTest(Input.FromString(testXml).Build()) .IgnoreComments() .Build(); // validate result Assert.IsFalse(myDiff.HasDifferences(), "XML similar " + myDiff.ToString()); } [TestCase("1.0")] [TestCase("2.0")] public void TestDiff_withIgnoreCommentsUsingVersion_shouldSucceed(string xsltVersion) { // prepare testData string controlXml = "<a><b><!-- A comment -->Test Value</b></a>"; string testXml = "<a><b><!-- An other comment -->Test Value</b></a>"; // run test var myDiff = DiffBuilder.Compare(Input.FromString(controlXml).Build()) .WithTest(Input.FromString(testXml).Build()) .IgnoreCommentsUsingXSLTVersion(xsltVersion) .Build(); // validate result Assert.IsFalse(myDiff.HasDifferences(), "XML similar " + myDiff.ToString()); } [Test] public void TestDiff_fromCombinedSourceAndstring_shouldSucceed() { // prepare testData string controlXml = "<a><b>Test Value</b></a>"; // run test var myDiff = DiffBuilder.Compare(Input.FromString(controlXml).Build()) .WithTest(controlXml) .Build(); // validate result Assert.IsFalse(myDiff.HasDifferences(), "XML similar " + myDiff.ToString()); } [Test] public void TestDiff_fromBuilder_shouldSucceed() { // prepare testData string controlXml = "<a><b>Test Value</b></a>"; // run test var myDiff = DiffBuilder.Compare(Input.FromString(controlXml)) .WithTest(Input.FromString(controlXml)) .Build(); // validate result Assert.IsFalse(myDiff.HasDifferences(), "XML similar " + myDiff.ToString()); } [Test] public void TestDiff_fromByteArray_shouldSucceed() { // prepare testData byte[] controlXml = Encoding.UTF8.GetBytes("<a><b>Test Value</b></a>"); // run test var myDiff = DiffBuilder.Compare(controlXml).WithTest(controlXml).Build(); // validate result Assert.IsFalse(myDiff.HasDifferences(), "XML similar " + myDiff.ToString()); } [Test] public void TestDiff_fromStream_shouldSucceed() { // prepare testData using (FileStream fs = new FileStream(TestResources.ANIMAL_FILE, FileMode.Open, FileAccess.Read)) { using (StreamReader r = new StreamReader(TestResources.ANIMAL_FILE)) { // run test var myDiff = DiffBuilder.Compare(fs).WithTest(r).Build(); // validate result Assert.IsFalse(myDiff.HasDifferences(), "XML similar " + myDiff.ToString()); } } } [Test] public void TestDiff_withComparisonListener_shouldCallListener() { // prepare testData string control = "<a><b attr=\"abc\"></b></a>"; string test = "<a><b attr=\"xyz\"></b></a>"; List<Difference> diffs = new List<Difference>(); ComparisonListener comparisonListener = (comparison, outcome) => { diffs.Add(new Difference(comparison, outcome)); }; // run test var myDiff = DiffBuilder.Compare(control).WithTest(test) .WithComparisonListeners(comparisonListener) .Build(); // validate result Assert.IsTrue(myDiff.HasDifferences(), myDiff.ToString()); Assert.That(diffs.Count, Is.GreaterThan(1)); } [Test] public void TestDiff_withDifferenceListener_shouldCallListener() { // prepare testData string control = "<a><b attr=\"abc\"></b></a>"; string test = "<a><b attr=\"xyz\"></b></a>"; List<Difference> diffs = new List<Difference>(); ComparisonListener comparisonListener = (comparison, outcome) => { diffs.Add(new Difference(comparison, outcome)); }; // run test var myDiff = DiffBuilder.Compare(control).WithTest(test) .WithDifferenceListeners(comparisonListener) .Build(); // validate result Assert.IsTrue(myDiff.HasDifferences(), myDiff.ToString()); Assert.That(diffs.Count, Is.EqualTo(1)); Assert.That(diffs[0].Result, Is.EqualTo(ComparisonResult.DIFFERENT)); Assert.That(diffs[0].Comparison.Type, Is.EqualTo(ComparisonType.ATTR_VALUE)); } [Test] public void TestDiff_withDifferenceEvaluator_shouldSucceed() { // prepare testData string control = "<a><b attr=\"abc\"></b></a>"; string test = "<a><b attr=\"xyz\"></b></a>"; // run test var myDiff = DiffBuilder.Compare(control).WithTest(test) .WithDifferenceEvaluator(IgnoreAttributeDifferenceEvaluator("attr")) .Build(); // validate result Assert.IsFalse(myDiff.HasDifferences(), myDiff.ToString()); } [Test] public void TestDiff_withDifferenceEvaluator_shouldNotInterfereWithSimilar() { // prepare testData string control = "<a><b><![CDATA[abc]]></b></a>"; string test = "<a><b>abc</b></a>"; // run test var myDiff = DiffBuilder.Compare(control).WithTest(test) .WithDifferenceEvaluator( DifferenceEvaluators.Chain(DifferenceEvaluators.Default, IgnoreAttributeDifferenceEvaluator("attr"))) .CheckForSimilar() .Build(); // validate result Assert.IsFalse(myDiff.HasDifferences(), myDiff.ToString()); } [Test] public void TestDiff_withCustomDifferenceEvaluator_shouldNotEvaluateSimilar() { // prepare testData string control = "<a><b><![CDATA[abc]]></b></a>"; string test = "<a><b>abc</b></a>"; // run test var myDiff = DiffBuilder.Compare(control).WithTest(test) .WithDifferenceEvaluator(IgnoreAttributeDifferenceEvaluator("attr")) .CheckForSimilar() .Build(); // validate result Assert.IsTrue(myDiff.HasDifferences(), myDiff.ToString()); IEnumerator<Difference> e = myDiff.Differences.GetEnumerator(); Assert.IsTrue(e.MoveNext()); Assert.That(e.Current.Result, Is.EqualTo(ComparisonResult.DIFFERENT)); } private DifferenceEvaluator IgnoreAttributeDifferenceEvaluator(string attributeName) { return (comparison, outcome) => { XmlAttribute attr = comparison.ControlDetails.Target as XmlAttribute; if (attr != null && attr.Name == attributeName) { return ComparisonResult.EQUAL; } return outcome; }; } [Test] public void TestDiff_withDefaultComparisonController_shouldReturnAllDifferences() { // prepare testData string control = "<a><b attr1=\"abc\" attr2=\"def\"></b></a>"; string test = "<a><b attr1=\"uvw\" attr2=\"xyz\"></b></a>"; // run test var myDiff = DiffBuilder.Compare(control).WithTest(test) .Build(); // validate result Assert.IsTrue(myDiff.HasDifferences()); Assert.That(myDiff.Differences.Count(), Is.EqualTo(2)); } [Test] public void TestDiff_withStopWhenDifferentComparisonController_shouldReturnOnlyFirstDifference() { // prepare testData string control = "<a><b attr1=\"abc\" attr2=\"def\"></b></a>"; string test = "<a><b attr1=\"uvw\" attr2=\"xyz\"></b></a>"; // run test var myDiff = DiffBuilder.Compare(control).WithTest(test) .WithComparisonController(ComparisonControllers.StopWhenDifferent) .Build(); // validate result Assert.IsTrue(myDiff.HasDifferences()); Assert.That(myDiff.Differences.Count(), Is.EqualTo(1)); } [Test] public void TestDiff_withAttributeDifferences() { // prepare testData string control = "<a><b attr1=\"abc\" attr2=\"def\"></b></a>"; string test = "<a><b attr1=\"uvw\" attr2=\"def\"></b></a>"; // run test var myDiff = DiffBuilder.Compare(control).WithTest(test) .WithComparisonController(ComparisonControllers.StopWhenDifferent) .Build(); // validate result Assert.IsTrue(myDiff.HasDifferences()); Assert.That(myDiff.Differences.Count(), Is.EqualTo(1)); // run test var myDiffWithFilter = DiffBuilder.Compare(control).WithTest(test) .WithAttributeFilter(a => "attr1" != a.Name) .WithComparisonController(ComparisonControllers.StopWhenDifferent) .Build(); // validate result Assert.IsFalse(myDiffWithFilter.HasDifferences()); } [Test] public void TestDiff_withExtraNodes() { // prepare testData string control = "<a><b></b><c/></a>"; string test = "<a><b></b><c/><d/></a>"; // run test var myDiff = DiffBuilder.Compare(control).WithTest(test) .WithComparisonController(ComparisonControllers.StopWhenDifferent) .Build(); // validate result Assert.IsTrue(myDiff.HasDifferences()); Assert.That(myDiff.Differences.Count(), Is.EqualTo(1)); // run test var myDiffWithFilter = DiffBuilder.Compare(control).WithTest(test) .WithNodeFilter(n => "d" != n.Name) .WithComparisonController(ComparisonControllers.StopWhenDifferent) .Build(); // validate result Assert.IsFalse(myDiffWithFilter.HasDifferences()); } [Test] public void UsesCustomComparisonFormatter() { string control = "<a><b></b><c/></a>"; string test = "<a><b></b><c/><d/></a>"; var myDiff = DiffBuilder.Compare(control).WithTest(test) .WithComparisonController(ComparisonControllers.StopWhenDifferent) .WithComparisonFormatter(new DummyComparisonFormatter()) .Build(); Assert.AreEqual("foo", myDiff.ToString()); } [Test] public void UsesCustomComparisonFormatterForDifferences() { string control = "<a><b></b><c/></a>"; string test = "<a><b></b><c/><d/></a>"; var myDiff = DiffBuilder.Compare(control).WithTest(test) .WithComparisonController(ComparisonControllers.StopWhenDifferent) .WithComparisonFormatter(new DummyComparisonFormatter()) .Build(); Assert.AreEqual("foo (DIFFERENT)", myDiff.Differences.First().ToString()); } [Test] [Ignore("Looks as if XmlDocument stripped ECW by itself")] public void TestDiff_withoutIgnoreElementContentWhitespaces_shouldFail() { // prepare testData string controlXml = "<a><b>Test Value</b></a>"; string testXml = "<a>\n <b>Test Value</b>\n</a>"; // run test var myDiff = DiffBuilder.Compare(Input.FromString(controlXml).Build()) .WithTest(Input.FromString(testXml).Build()) .Build(); // validate result Assert.IsTrue(myDiff.HasDifferences(), myDiff.ToString()); } [Test] public void TestDiff_withIgnoreElementContentWhitespaces_shouldSucceed() { // prepare testData string controlXml = "<a><b>Test Value</b></a>"; string testXml = "<a>\n <b>Test Value</b>\n</a>"; // run test var myDiff = DiffBuilder.Compare(Input.FromString(controlXml).Build()) .WithTest(Input.FromString(testXml).Build()) .IgnoreElementContentWhitespace() .Build(); // validate result Assert.IsFalse(myDiff.HasDifferences(), "XML similar " + myDiff.ToString()); } internal class DummyComparisonFormatter : IComparisonFormatter { public string GetDescription(Comparison difference) { return "foo"; } public string GetDetails(Comparison.Detail details, ComparisonType type, bool formatXml) { return "bar"; } } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Linq; using FluentAssertions; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.TestFramework; using Microsoft.DotNet.Tools.Test.Utilities; using NuGet.Frameworks; using NuGet.ProjectModel; using NuGet.Versioning; using Xunit; using Microsoft.DotNet.Tools.Tests.Utilities; namespace Microsoft.DotNet.Tests { public class GivenAProjectToolsCommandResolver : TestBase { private static readonly NuGetFramework s_toolPackageFramework = NuGetFrameworks.NetCoreApp21; private const string TestProjectName = "AppWithToolDependency"; [Fact] public void ItReturnsNullWhenCommandNameIsNull() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = null, CommandArguments = new string[] { "" }, ProjectDirectory = "/some/directory" }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void ItReturnsNullWhenProjectDirectoryIsNull() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "command", CommandArguments = new string[] { "" }, ProjectDirectory = null }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void ItReturnsNullWhenProjectDirectoryDoesNotContainAProjectFile() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var projectDirectory = TestAssets.CreateTestDirectory(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "command", CommandArguments = new string[] { "" }, ProjectDirectory = projectDirectory.Root.FullName }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void ItReturnsNullWhenCommandNameDoesNotExistInProjectTools() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "nonexistent-command", CommandArguments = null, ProjectDirectory = testInstance.Root.FullName }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void ItReturnsACommandSpecWithDOTNETAsFileNameAndCommandNameInArgsWhenCommandNameExistsInProjectTools() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = null, ProjectDirectory = testInstance.Root.FullName }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); var commandFile = Path.GetFileNameWithoutExtension(result.Path); commandFile.Should().Be("dotnet"); result.Args.Should().Contain(commandResolverArguments.CommandName); } [Fact] public void ItEscapesCommandArgumentsWhenReturningACommandSpec() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = new[] { "arg with space" }, ProjectDirectory = testInstance.Root.FullName }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull("Because the command is a project tool dependency"); result.Args.Should().Contain("\"arg with space\""); } [Fact] public void ItReturnsACommandSpecWithArgsContainingCommandPathWhenReturningACommandSpecAndCommandArgumentsAreNull() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = null, ProjectDirectory = testInstance.Root.FullName }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); var commandPath = result.Args.Trim('"'); commandPath.Should().Contain("dotnet-portable.dll"); } [Fact] public void ItReturnsACommandSpecWithArgsContainingCommandPathWhenInvokingAToolReferencedWithADifferentCasing() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-prefercliruntime", CommandArguments = null, ProjectDirectory = testInstance.Root.FullName }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); var commandPath = result.Args.Trim('"'); commandPath.Should().Contain("dotnet-prefercliruntime.dll"); } [Fact] public void ItWritesADepsJsonFileNextToTheLockfile() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = null, ProjectDirectory = testInstance.Root.FullName }; var repoDirectoriesProvider = new RepoDirectoriesProvider(); var nugetPackagesRoot = repoDirectoriesProvider.NugetPackages; var toolPathCalculator = new ToolPathCalculator(nugetPackagesRoot); var lockFilePath = toolPathCalculator.GetLockFilePath( "dotnet-portable", new NuGetVersion("1.0.0"), s_toolPackageFramework); var directory = Path.GetDirectoryName(lockFilePath); var depsJsonFile = Directory .EnumerateFiles(directory) .FirstOrDefault(p => Path.GetFileName(p).EndsWith(FileNameSuffixes.DepsJson)); if (depsJsonFile != null) { File.Delete(depsJsonFile); } var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); new DirectoryInfo(directory) .Should().HaveFilesMatching("*.deps.json", SearchOption.TopDirectoryOnly); } [Fact] public void GenerateDepsJsonMethodDoesntOverwriteWhenDepsFileAlreadyExists() { var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var repoDirectoriesProvider = new RepoDirectoriesProvider(); var nugetPackagesRoot = repoDirectoriesProvider.NugetPackages; var toolPathCalculator = new ToolPathCalculator(nugetPackagesRoot); var lockFilePath = toolPathCalculator.GetLockFilePath( "dotnet-portable", new NuGetVersion("1.0.0"), s_toolPackageFramework); var lockFile = new LockFileFormat().Read(lockFilePath); // NOTE: We must not use the real deps.json path here as it will interfere with tests running in parallel. var depsJsonFile = Path.GetTempFileName(); File.WriteAllText(depsJsonFile, "temp"); var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); projectToolsCommandResolver.GenerateDepsJsonFile( lockFile, s_toolPackageFramework, depsJsonFile, new SingleProjectInfo("dotnet-portable", "1.0.0", Enumerable.Empty<ResourceAssemblyInfo>()), GetToolDepsJsonGeneratorProject()); File.ReadAllText(depsJsonFile).Should().Be("temp"); File.Delete(depsJsonFile); } [Fact] public void ItAddsFxVersionAsAParamWhenTheToolHasThePrefercliruntimeFile() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get("MSBuildTestApp") .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-prefercliruntime", CommandArguments = null, ProjectDirectory = testInstance.Root.FullName }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); result.Args.Should().Contain("--fx-version 2.1.0"); } [Fact] public void ItDoesNotAddFxVersionAsAParamWhenTheToolDoesNotHaveThePrefercliruntimeFile() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = null, ProjectDirectory = testInstance.Root.FullName }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); result.Args.Should().NotContain("--fx-version"); } [Fact] public void ItFindsToolsLocatedInTheNuGetFallbackFolder() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get("AppWithFallbackFolderToolDependency") .CreateInstance() .WithSourceFiles() .WithNuGetConfig(new RepoDirectoriesProvider().TestPackages); var testProjectDirectory = testInstance.Root.FullName; var fallbackFolder = Path.Combine(testProjectDirectory, "fallbackFolder"); PopulateFallbackFolder(testProjectDirectory, fallbackFolder); var nugetConfig = UseNuGetConfigWithFallbackFolder(testInstance, fallbackFolder); new RestoreCommand() .WithWorkingDirectory(testProjectDirectory) .Execute($"--configfile {nugetConfig}") .Should() .Pass(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-fallbackfoldertool", CommandArguments = null, ProjectDirectory = testProjectDirectory }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); var commandPath = result.Args.Trim('"'); commandPath.Should().Contain(Path.Combine( fallbackFolder, "dotnet-fallbackfoldertool", "1.0.0", "lib", "netcoreapp2.1", "dotnet-fallbackfoldertool.dll")); } [Fact] public void ItShowsAnErrorWhenTheToolDllIsNotFound() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get("AppWithFallbackFolderToolDependency") .CreateInstance() .WithSourceFiles() .WithNuGetConfig(new RepoDirectoriesProvider().TestPackages); var testProjectDirectory = testInstance.Root.FullName; var fallbackFolder = Path.Combine(testProjectDirectory, "fallbackFolder"); PopulateFallbackFolder(testProjectDirectory, fallbackFolder); var nugetConfig = UseNuGetConfigWithFallbackFolder(testInstance, fallbackFolder); new RestoreCommand() .WithWorkingDirectory(testProjectDirectory) .Execute($"--configfile {nugetConfig}") .Should() .Pass(); Directory.Delete(Path.Combine(fallbackFolder, "dotnet-fallbackfoldertool"), true); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-fallbackfoldertool", CommandArguments = null, ProjectDirectory = testProjectDirectory }; Action action = () => projectToolsCommandResolver.Resolve(commandResolverArguments); action.ShouldThrow<GracefulException>().WithMessage( string.Format(LocalizableStrings.CommandAssembliesNotFound, "dotnet-fallbackfoldertool")); } private void PopulateFallbackFolder(string testProjectDirectory, string fallbackFolder) { var nugetConfigPath = Path.Combine(testProjectDirectory, "NuGet.Config"); new RestoreCommand() .WithWorkingDirectory(testProjectDirectory) .Execute($"--configfile {nugetConfigPath} --packages {fallbackFolder}") .Should() .Pass(); Directory.Delete(Path.Combine(fallbackFolder, ".tools"), true); } private string UseNuGetConfigWithFallbackFolder(TestAssetInstance testInstance, string fallbackFolder) { var nugetConfig = testInstance.Root.GetFile("NuGet.Config").FullName; File.WriteAllText( nugetConfig, $@"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <fallbackPackageFolders> <add key=""MachineWide"" value=""{fallbackFolder}""/> </fallbackPackageFolders> </configuration> "); return nugetConfig; } private ProjectToolsCommandResolver SetupProjectToolsCommandResolver() { Environment.SetEnvironmentVariable( Constants.MSBUILD_EXE_PATH, Path.Combine(new RepoDirectoriesProvider().Stage2Sdk, "MSBuild.dll")); var packagedCommandSpecFactory = new PackagedCommandSpecFactoryWithCliRuntime(); var projectToolsCommandResolver = new ProjectToolsCommandResolver(packagedCommandSpecFactory, new EnvironmentProvider()); return projectToolsCommandResolver; } private string GetToolDepsJsonGeneratorProject() { // When using the product, the ToolDepsJsonGeneratorProject property is used to get this path, but for testing // we'll hard code the path inside the SDK since we don't have a project to evaluate here return Path.Combine(new RepoDirectoriesProvider().Stage2Sdk, "Sdks", "Microsoft.NET.Sdk", "targets", "GenerateDeps", "GenerateDeps.proj"); } } }
// // BaseTool.cs // // Author: // Jonathan Pobst <monkey@jpobst.com> // // Copyright (c) 2010 Jonathan Pobst // // 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 Cairo; using Gtk; using Gdk; using System.IO; using Mono.Unix; using Mono.Addins; using System.Collections.Generic; namespace Pinta.Core { public delegate void MouseHandler (double x, double y, Gdk.ModifierType state); [TypeExtensionPoint] public abstract class BaseTool { public const int DEFAULT_BRUSH_WIDTH = 2; protected static Cairo.Point point_empty = new Cairo.Point (-500, -500); protected ToggleToolButton tool_item; protected ToolItem tool_label; protected ToolItem tool_image; protected ToolItem tool_sep; protected ToolBarDropDownButton antialiasing_button; private ToolBarItem aaOn, aaOff; protected ToolBarDropDownButton alphablending_button; public event MouseHandler MouseMoved; public event MouseHandler MousePressed; public event MouseHandler MouseReleased; public Cursor CurrentCursor { get; private set; } protected BaseTool () { CurrentCursor = DefaultCursor; PintaCore.Workspace.ActiveDocumentChanged += Workspace_ActiveDocumentChanged; } static BaseTool () { Gtk.IconFactory fact = new Gtk.IconFactory (); fact.Add ("Toolbar.AntiAliasingEnabledIcon.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Toolbar.AntiAliasingEnabledIcon.png"))); fact.Add ("Toolbar.AntiAliasingDisabledIcon.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Toolbar.AntiAliasingDisabledIcon.png"))); fact.Add ("Toolbar.BlendingEnabledIcon.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Toolbar.BlendingEnabledIcon.png"))); fact.Add ("Toolbar.BlendingOverwriteIcon.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Toolbar.BlendingOverwriteIcon.png"))); fact.Add ("Tools.FreeformShape.png", new Gtk.IconSet (PintaCore.Resources.GetIcon ("Tools.FreeformShape.png"))); fact.AddDefault (); } public virtual string Name { get { throw new ApplicationException ("Tool didn't override Name"); } } public virtual string Icon { get { throw new ApplicationException ("Tool didn't override Icon"); } } public virtual string ToolTip { get { throw new ApplicationException ("Tool didn't override ToolTip"); } } public virtual string StatusBarText { get { return string.Empty; } } public virtual ToggleToolButton ToolItem { get { if (tool_item == null) tool_item = CreateToolButton (); return tool_item; } } public virtual bool Enabled { get { return true; } } public virtual Gdk.Cursor DefaultCursor { get { return null; } } public virtual Gdk.Key ShortcutKey { get { return (Gdk.Key)0; } } //Whether or not the tool is an editable ShapeTool. public bool IsEditableShapeTool = false; public virtual bool UseAntialiasing { get { return (antialiasing_button != null) && ShowAntialiasingButton && (bool)antialiasing_button.SelectedItem.Tag; } set { if (!ShowAntialiasingButton || antialiasing_button == null) return; antialiasing_button.SelectedItem = value ? aaOn : aaOff; } } public virtual bool UseAlphaBlending { get { return ShowAlphaBlendingButton && (bool)alphablending_button.SelectedItem.Tag; } } public virtual int Priority { get { return 75; } } public virtual bool CursorChangesOnZoom { get { return false; } } protected virtual bool ShowAntialiasingButton { get { return false; } } protected virtual bool ShowAlphaBlendingButton { get { return false; } } #region Public Methods public void DoMouseMove (object o, MotionNotifyEventArgs args, Cairo.PointD point) { if (MouseMoved != null) MouseMoved (point.X, point.Y, args.Event.State); OnMouseMove (o, args, point); } public void DoBuildToolBar (Toolbar tb) { OnBuildToolBar (tb); BuildRasterizationToolItems (tb); } public void DoClearToolBar (Toolbar tb) { OnClearToolBar (tb); } public void DoMouseDown (DrawingArea canvas, ButtonPressEventArgs args, Cairo.PointD point) { if (MousePressed != null) MousePressed (point.X, point.Y, args.Event.State); OnMouseDown (canvas, args, point); } public void DoMouseUp (DrawingArea canvas, ButtonReleaseEventArgs args, Cairo.PointD point) { if (MouseReleased != null) MouseReleased (point.X, point.Y, args.Event.State); OnMouseUp (canvas, args, point); } public void DoCommit () { OnCommit (); } public void DoAfterSave() { AfterSave(); } public void DoActivated () { OnActivated (); } public void DoDeactivated (BaseTool newTool) { OnDeactivated(newTool); } // Return true if the key was consumed. public void DoKeyPress (DrawingArea canvas, KeyPressEventArgs args) { OnKeyDown (canvas, args); } public void DoKeyRelease (DrawingArea canvas, KeyReleaseEventArgs args) { OnKeyUp (canvas, args); } public virtual bool TryHandlePaste (Clipboard cb) { return false; } public virtual bool TryHandleCut (Clipboard cb) { return false; } public virtual bool TryHandleCopy (Clipboard cb) { return false; } public virtual bool TryHandleUndo () { return false; } public virtual bool TryHandleRedo () { return false; } public virtual void AfterUndo() { } public virtual void AfterRedo() { } #endregion #region Protected Methods protected virtual void OnMouseMove (object o, Gtk.MotionNotifyEventArgs args, Cairo.PointD point) { } protected virtual void BuildRasterizationToolItems (Toolbar tb) { if (ShowAlphaBlendingButton || ShowAntialiasingButton) tb.AppendItem (new SeparatorToolItem ()); if (ShowAntialiasingButton) BuildAntialiasingTool (tb); if (ShowAlphaBlendingButton) BuildAlphaBlending(tb); AfterBuildRasterization(); } protected virtual void AfterBuildRasterization() { } protected virtual void OnBuildToolBar (Toolbar tb) { if (tool_label == null) tool_label = new ToolBarLabel (string.Format (" {0}: ", Catalog.GetString ("Tool"))); tb.AppendItem (tool_label); if (tool_image == null) tool_image = new ToolBarImage (Icon); tb.AppendItem (tool_image); if (tool_sep == null) tool_sep = new SeparatorToolItem (); tb.AppendItem (tool_sep); } protected virtual void OnClearToolBar (Toolbar tb) { while (tb.NItems > 0) tb.Remove (tb.Children[tb.NItems - 1]); } protected virtual void OnMouseDown (DrawingArea canvas, Gtk.ButtonPressEventArgs args, Cairo.PointD point) { } protected virtual void OnMouseUp (DrawingArea canvas, Gtk.ButtonReleaseEventArgs args, Cairo.PointD point) { } protected virtual void OnKeyDown (DrawingArea canvas, Gtk.KeyPressEventArgs args) { } protected virtual void OnKeyUp (DrawingArea canvas, Gtk.KeyReleaseEventArgs args) { } /// <summary> /// This is called whenever a menu option is called, for /// tools that are in a temporary state while being used, and /// need to commit their work when another option is selected. /// </summary> protected virtual void OnCommit () { } protected virtual void AfterSave() { } protected virtual void OnActivated () { SetCursor (DefaultCursor); } protected virtual void OnDeactivated(BaseTool newTool) { SetCursor (null); } protected virtual ToggleToolButton CreateToolButton () { Gtk.Image i2 = new Gtk.Image (PintaCore.Resources.GetIcon (Icon)); i2.Show (); ToggleToolButton tool_item = new ToggleToolButton (); tool_item.IconWidget = i2; tool_item.Show (); tool_item.Label = Name; if (ShortcutKey != (Gdk.Key)0) tool_item.TooltipText = string.Format ("{0}\n{2}: {1}\n\n{3}", Name, ShortcutKey.ToString ().ToUpperInvariant (), Catalog.GetString ("Shortcut key"), StatusBarText); else tool_item.TooltipText = Name; return tool_item; } public void SetCursor (Gdk.Cursor cursor) { CurrentCursor = cursor; if (PintaCore.Workspace.HasOpenDocuments && PintaCore.Workspace.ActiveWorkspace.Canvas.GdkWindow != null) PintaCore.Workspace.ActiveWorkspace.Canvas.GdkWindow.Cursor = cursor; } /// <summary> /// Create a cursor icon with a shape that visually represents the tool's thickness. /// </summary> /// <param name="imgName">A string containing the name of the tool's icon image to use.</param> /// <param name="shape">The shape to draw.</param> /// <param name="shapeWidth">The width of the shape.</param> /// <param name="imgToShapeX">The horizontal distance between the image's top-left corner and the shape center.</param> /// <param name="imgToShapeY">The verical distance between the image's top-left corner and the shape center.</param> /// <param name="shapeX">The X position in the returned Pixbuf that will be the center of the shape.</param> /// <param name="shapeY">The Y position in the returned Pixbuf that will be the center of the shape.</param> /// <returns>The new cursor icon with an shape that represents the tool's thickness.</returns> protected Gdk.Pixbuf CreateIconWithShape(string imgName, CursorShape shape, int shapeWidth, int imgToShapeX, int imgToShapeY, out int shapeX, out int shapeY) { Gdk.Pixbuf img = PintaCore.Resources.GetIcon(imgName); double zoom = 1d; if (PintaCore.Workspace.HasOpenDocuments) { zoom = Math.Min(30d, PintaCore.Workspace.ActiveDocument.Workspace.Scale); } shapeWidth = (int)Math.Min(800d, ((double)shapeWidth) * zoom); int halfOfShapeWidth = shapeWidth / 2; // Calculate bounding boxes around the both image and shape // relative to the image top-left corner. Gdk.Rectangle imgBBox = new Gdk.Rectangle(0, 0, img.Width, img.Height); Gdk.Rectangle shapeBBox = new Gdk.Rectangle( imgToShapeX - halfOfShapeWidth, imgToShapeY - halfOfShapeWidth, shapeWidth, shapeWidth); // Inflate shape bounding box to allow for anti-aliasing shapeBBox.Inflate(2, 2); // To determine required size of icon, // find union of the image and shape bounding boxes // (still relative to image top-left corner) Gdk.Rectangle iconBBox = imgBBox.Union (shapeBBox); // Image top-left corner in icon co-ordinates int imgX = imgBBox.Left - iconBBox.Left; int imgY = imgBBox.Top - iconBBox.Top; // Shape center point in icon co-ordinates shapeX = imgToShapeX - iconBBox.Left; shapeY = imgToShapeY - iconBBox.Top; using (ImageSurface i = new ImageSurface (Format.ARGB32, iconBBox.Width, iconBBox.Height)) { using (Context g = new Context (i)) { // Don't show shape if shapeWidth less than 3, if (shapeWidth > 3) { int diam = Math.Max (1, shapeWidth - 2); Cairo.Rectangle shapeRect = new Cairo.Rectangle (shapeX - halfOfShapeWidth, shapeY - halfOfShapeWidth, diam, diam); Cairo.Color outerColor = new Cairo.Color (255, 255, 255, 0.75); Cairo.Color innerColor = new Cairo.Color (0, 0, 0); switch (shape) { case CursorShape.Ellipse: g.DrawEllipse (shapeRect, outerColor, 2); shapeRect = shapeRect.Inflate (-1, -1); g.DrawEllipse (shapeRect, innerColor, 1); break; case CursorShape.Rectangle: g.DrawRectangle (shapeRect, outerColor, 1); shapeRect = shapeRect.Inflate (-1, -1); g.DrawRectangle (shapeRect, innerColor, 1); break; } } // Draw the image g.DrawPixbuf (img, new Cairo.Point (imgX, imgY)); } return CairoExtensions.ToPixbuf (i); } } #endregion #region Private Methods private void BuildAlphaBlending (Toolbar tb) { if (alphablending_button != null) { tb.AppendItem (alphablending_button); return; } alphablending_button = new ToolBarDropDownButton (); alphablending_button.AddItem (Catalog.GetString ("Normal Blending"), "Toolbar.BlendingEnabledIcon.png", true); alphablending_button.AddItem (Catalog.GetString ("Overwrite"), "Toolbar.BlendingOverwriteIcon.png", false); tb.AppendItem (alphablending_button); } private void BuildAntialiasingTool (Toolbar tb) { if (antialiasing_button != null) { tb.AppendItem (antialiasing_button); return; } antialiasing_button = new ToolBarDropDownButton (); aaOn = antialiasing_button.AddItem (Catalog.GetString ("Antialiasing On"), "Toolbar.AntiAliasingEnabledIcon.png", true); aaOff = antialiasing_button.AddItem (Catalog.GetString ("Antialiasing Off"), "Toolbar.AntiAliasingDisabledIcon.png", false); tb.AppendItem (antialiasing_button); } private void Workspace_ActiveDocumentChanged (object sender, EventArgs e) { if (PintaCore.Tools.CurrentTool == this) SetCursor (DefaultCursor); } #endregion } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Testing; using osu.Framework.Utils; using osu.Game.Online.API; using osu.Game.Online.API.Requests.Responses; using osu.Game.Overlays; using osu.Game.Overlays.BeatmapSet.Scores; using osu.Game.Rulesets.Osu.Mods; using osu.Game.Scoring; using osu.Game.Users; using osuTK.Graphics; using APIUser = osu.Game.Online.API.Requests.Responses.APIUser; namespace osu.Game.Tests.Visual.Online { public class TestSceneScoresContainer : OsuTestScene { [Cached] private readonly OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Blue); private TestScoresContainer scoresContainer; [SetUpSteps] public void SetUp() => Schedule(() => { Child = new Container { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, RelativeSizeAxes = Axes.Both, Width = 0.8f, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Black, }, scoresContainer = new TestScoresContainer { Beatmap = { Value = CreateAPIBeatmap() } } } }; }); [Test] public void TestNoUserBest() { AddStep("Scores with no user best", () => { var allScores = createScores(); allScores.UserScore = null; scoresContainer.Scores = allScores; }); AddUntilStep("wait for scores displayed", () => scoresContainer.ChildrenOfType<ScoreTableRowBackground>().Any()); AddAssert("no user best displayed", () => scoresContainer.ChildrenOfType<DrawableTopScore>().Count() == 1); AddStep("Load null scores", () => scoresContainer.Scores = null); AddUntilStep("wait for scores not displayed", () => !scoresContainer.ChildrenOfType<ScoreTableRowBackground>().Any()); AddAssert("no best score displayed", () => !scoresContainer.ChildrenOfType<DrawableTopScore>().Any()); AddStep("Load only one score", () => { var allScores = createScores(); allScores.Scores.RemoveRange(1, allScores.Scores.Count - 1); scoresContainer.Scores = allScores; }); AddUntilStep("wait for scores not displayed", () => scoresContainer.ChildrenOfType<ScoreTableRowBackground>().Count() == 1); AddAssert("no best score displayed", () => scoresContainer.ChildrenOfType<DrawableTopScore>().Count() == 1); } [Test] public void TestUserBest() { AddStep("Load scores with personal best", () => { var allScores = createScores(); allScores.UserScore = createUserBest(); scoresContainer.Scores = allScores; }); AddUntilStep("wait for scores displayed", () => scoresContainer.ChildrenOfType<ScoreTableRowBackground>().Any()); AddAssert("best score displayed", () => scoresContainer.ChildrenOfType<DrawableTopScore>().Count() == 2); AddStep("Load scores with personal best (null position)", () => { var allScores = createScores(); var userBest = createUserBest(); userBest.Position = null; allScores.UserScore = userBest; scoresContainer.Scores = allScores; }); AddUntilStep("wait for scores displayed", () => scoresContainer.ChildrenOfType<ScoreTableRowBackground>().Any()); AddAssert("best score displayed", () => scoresContainer.ChildrenOfType<DrawableTopScore>().Count() == 2); AddStep("Load scores with personal best (first place)", () => { var allScores = createScores(); allScores.UserScore = new APIScoreWithPosition { Score = allScores.Scores.First(), Position = 1, }; scoresContainer.Scores = allScores; }); AddUntilStep("wait for scores displayed", () => scoresContainer.ChildrenOfType<ScoreTableRowBackground>().Any()); AddAssert("best score displayed", () => scoresContainer.ChildrenOfType<DrawableTopScore>().Count() == 1); AddStep("Scores with no user best", () => { var allScores = createScores(); allScores.UserScore = null; scoresContainer.Scores = allScores; }); AddUntilStep("best score not displayed", () => scoresContainer.ChildrenOfType<DrawableTopScore>().Count() == 1); } private int onlineID = 1; private APIScoresCollection createScores() { var scores = new APIScoresCollection { Scores = new List<APIScore> { new APIScore { Date = DateTimeOffset.Now, OnlineID = onlineID++, User = new APIUser { Id = 6602580, Username = @"waaiiru", Country = new Country { FullName = @"Spain", FlagName = @"ES", }, }, Mods = new[] { new APIMod { Acronym = new OsuModDoubleTime().Acronym }, new APIMod { Acronym = new OsuModHidden().Acronym }, new APIMod { Acronym = new OsuModFlashlight().Acronym }, new APIMod { Acronym = new OsuModHardRock().Acronym }, }, Rank = ScoreRank.XH, PP = 200, MaxCombo = 1234, TotalScore = 1234567890, Accuracy = 1, }, new APIScore { Date = DateTimeOffset.Now, OnlineID = onlineID++, User = new APIUser { Id = 4608074, Username = @"Skycries", Country = new Country { FullName = @"Brazil", FlagName = @"BR", }, }, Mods = new[] { new APIMod { Acronym = new OsuModDoubleTime().Acronym }, new APIMod { Acronym = new OsuModHidden().Acronym }, new APIMod { Acronym = new OsuModFlashlight().Acronym }, }, Rank = ScoreRank.S, PP = 190, MaxCombo = 1234, TotalScore = 1234789, Accuracy = 0.9997, }, new APIScore { Date = DateTimeOffset.Now, OnlineID = onlineID++, User = new APIUser { Id = 1014222, Username = @"eLy", Country = new Country { FullName = @"Japan", FlagName = @"JP", }, }, Mods = new[] { new APIMod { Acronym = new OsuModDoubleTime().Acronym }, new APIMod { Acronym = new OsuModHidden().Acronym }, }, Rank = ScoreRank.B, PP = 180, MaxCombo = 1234, TotalScore = 12345678, Accuracy = 0.9854, }, new APIScore { Date = DateTimeOffset.Now, OnlineID = onlineID++, User = new APIUser { Id = 1541390, Username = @"Toukai", Country = new Country { FullName = @"Canada", FlagName = @"CA", }, }, Mods = new[] { new APIMod { Acronym = new OsuModDoubleTime().Acronym }, }, Rank = ScoreRank.C, PP = 170, MaxCombo = 1234, TotalScore = 1234567, Accuracy = 0.8765, }, new APIScore { Date = DateTimeOffset.Now, OnlineID = onlineID++, User = new APIUser { Id = 7151382, Username = @"Mayuri Hana", Country = new Country { FullName = @"Thailand", FlagName = @"TH", }, }, Rank = ScoreRank.D, PP = 160, MaxCombo = 1234, TotalScore = 123456, Accuracy = 0.6543, }, } }; foreach (var s in scores.Scores) { s.Statistics = new Dictionary<string, int> { { "count_300", RNG.Next(2000) }, { "count_100", RNG.Next(2000) }, { "count_50", RNG.Next(2000) }, { "count_miss", RNG.Next(2000) } }; } return scores; } private APIScoreWithPosition createUserBest() => new APIScoreWithPosition { Score = new APIScore { Date = DateTimeOffset.Now, OnlineID = onlineID++, User = new APIUser { Id = 7151382, Username = @"Mayuri Hana", Country = new Country { FullName = @"Thailand", FlagName = @"TH", }, }, Rank = ScoreRank.D, PP = 160, MaxCombo = 1234, TotalScore = 123456, Accuracy = 0.6543, }, Position = 1337, }; private class TestScoresContainer : ScoresContainer { public new APIScoresCollection Scores { set => base.Scores = value; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Drawing.Drawing2D; using System.Security.Permissions; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; using System.Collections; using System.Drawing.Design; using Aga.Controls.Tree.NodeControls; using System.Drawing.Imaging; using System.Diagnostics; using System.Threading; using Aga.Controls.Threading; namespace Aga.Controls.Tree { public partial class TreeViewAdv : Control { private const int LeftMargin = 7; internal const int ItemDragSensivity = 4; private readonly int _columnHeaderHeight; private const int DividerWidth = 9; private const int DividerCorrectionGap = -2; private Pen _linePen; private Pen _markPen; private bool _suspendUpdate; private bool _needFullUpdate; private bool _fireSelectionEvent; private NodePlusMinus _plusMinus; private Control _currentEditor; private EditableControl _currentEditorOwner; private ToolTip _toolTip; private DrawContext _measureContext; private TreeColumn _hotColumn = null; private IncrementalSearch _search; private List<TreeNodeAdv> _expandingNodes = new List<TreeNodeAdv>(); private AbortableThreadPool _threadPool = new AbortableThreadPool(); #region Public Events [Category("Action")] public event ItemDragEventHandler ItemDrag; private void OnItemDrag(MouseButtons buttons, object item) { if (ItemDrag != null) ItemDrag(this, new ItemDragEventArgs(buttons, item)); } [Category("Behavior")] public event EventHandler<TreeNodeAdvMouseEventArgs> NodeMouseClick; private void OnNodeMouseClick(TreeNodeAdvMouseEventArgs args) { if (NodeMouseClick != null) NodeMouseClick(this, args); } [Category("Behavior")] public event EventHandler<TreeNodeAdvMouseEventArgs> NodeMouseDoubleClick; private void OnNodeMouseDoubleClick(TreeNodeAdvMouseEventArgs args) { if (NodeMouseDoubleClick != null) NodeMouseDoubleClick(this, args); } [Category("Behavior")] public event EventHandler<TreeColumnEventArgs> ColumnWidthChanged; internal void OnColumnWidthChanged(TreeColumn column) { if (ColumnWidthChanged != null) ColumnWidthChanged(this, new TreeColumnEventArgs(column)); } [Category("Behavior")] public event EventHandler<TreeColumnEventArgs> ColumnReordered; internal void OnColumnReordered(TreeColumn column) { if (ColumnReordered != null) ColumnReordered(this, new TreeColumnEventArgs(column)); } [Category("Behavior")] public event EventHandler<TreeColumnEventArgs> ColumnClicked; internal void OnColumnClicked(TreeColumn column) { if (ColumnClicked != null) ColumnClicked(this, new TreeColumnEventArgs(column)); } [Category("Behavior")] public event EventHandler SelectionChanged; internal void OnSelectionChanged() { if (SuspendSelectionEvent) _fireSelectionEvent = true; else { _fireSelectionEvent = false; if (SelectionChanged != null) SelectionChanged(this, EventArgs.Empty); } } [Category("Behavior")] public event EventHandler<TreeViewAdvEventArgs> Collapsing; private void OnCollapsing(TreeNodeAdv node) { if (Collapsing != null) Collapsing(this, new TreeViewAdvEventArgs(node)); } [Category("Behavior")] public event EventHandler<TreeViewAdvEventArgs> Collapsed; private void OnCollapsed(TreeNodeAdv node) { if (Collapsed != null) Collapsed(this, new TreeViewAdvEventArgs(node)); } [Category("Behavior")] public event EventHandler<TreeViewAdvEventArgs> Expanding; private void OnExpanding(TreeNodeAdv node) { if (Expanding != null) Expanding(this, new TreeViewAdvEventArgs(node)); } [Category("Behavior")] public event EventHandler<TreeViewAdvEventArgs> Expanded; private void OnExpanded(TreeNodeAdv node) { if (Expanded != null) Expanded(this, new TreeViewAdvEventArgs(node)); } [Category("Behavior")] public event EventHandler GridLineStyleChanged; private void OnGridLineStyleChanged() { if (GridLineStyleChanged != null) GridLineStyleChanged(this, EventArgs.Empty); } #endregion public TreeViewAdv() { InitializeComponent(); SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.Selectable , true); if (Application.RenderWithVisualStyles) _columnHeaderHeight = 24; else _columnHeaderHeight = 17; //BorderStyle = BorderStyle.Fixed3D; _hScrollBar.Height = SystemInformation.HorizontalScrollBarHeight; _vScrollBar.Width = SystemInformation.VerticalScrollBarWidth; _rowLayout = new FixedRowHeightLayout(this, RowHeight); _rowMap = new List<TreeNodeAdv>(); _selection = new List<TreeNodeAdv>(); _readonlySelection = new ReadOnlyCollection<TreeNodeAdv>(_selection); _columns = new TreeColumnCollection(this); _toolTip = new ToolTip(); _measureContext = new DrawContext(); _measureContext.Font = Font; _measureContext.Graphics = Graphics.FromImage(new Bitmap(1, 1)); Input = new NormalInputState(this); _search = new IncrementalSearch(this); CreateNodes(); CreatePens(); ArrangeControls(); _plusMinus = new NodePlusMinus(); _controls = new NodeControlsCollection(this); Font = _font; ExpandingIcon.IconChanged += ExpandingIconChanged; } void ExpandingIconChanged(object sender, EventArgs e) { if (IsHandleCreated) Invoke(new MethodInvoker(DrawIcons)); } private void DrawIcons() { Graphics gr = Graphics.FromHwnd(this.Handle); int firstRowY = _rowLayout.GetRowBounds(FirstVisibleRow).Y; DrawContext context = new DrawContext(); context.Graphics = gr; for (int i = 0; i < _expandingNodes.Count; i++) { foreach (NodeControlInfo info in GetNodeControls(_expandingNodes[i])) if (info.Control is ExpandingIcon) { Rectangle rect = info.Bounds; rect.X -= OffsetX; rect.Y -= firstRowY; context.Bounds = rect; info.Control.Draw(info.Node, context); } } gr.Dispose(); } #region Public Methods public TreePath GetPath(TreeNodeAdv node) { if (node == _root) return TreePath.Empty; else { Stack<object> stack = new Stack<object>(); while (node != _root && node != null) { stack.Push(node.Tag); node = node.Parent; } return new TreePath(stack.ToArray()); } } public TreeNodeAdv GetNodeAt(Point point) { NodeControlInfo info = GetNodeControlInfoAt(point); return info.Node; } public NodeControlInfo GetNodeControlInfoAt(Point point) { if (point.X < 0 || point.Y < 0) return NodeControlInfo.Empty; int row = _rowLayout.GetRowAt(point); if (row < RowCount && row >= 0) return GetNodeControlInfoAt(RowMap[row], point); else return NodeControlInfo.Empty; } private NodeControlInfo GetNodeControlInfoAt(TreeNodeAdv node, Point point) { Rectangle rect = _rowLayout.GetRowBounds(FirstVisibleRow); point.Y += (rect.Y - ColumnHeaderHeight); point.X += OffsetX; foreach (NodeControlInfo info in GetNodeControls(node)) if (info.Bounds.Contains(point)) return info; if (FullRowSelect) return new NodeControlInfo(null, Rectangle.Empty, node); else return NodeControlInfo.Empty; } public void BeginUpdate() { _suspendUpdate = true; SuspendSelectionEvent = true; } public void EndUpdate() { _suspendUpdate = false; if (_needFullUpdate) FullUpdate(); else UpdateView(); SuspendSelectionEvent = false; } public void ExpandAll() { _root.ExpandAll(); } public void CollapseAll() { _root.CollapseAll(); } /// <summary> /// Expand all parent nodes, andd scroll to the specified node /// </summary> public void EnsureVisible(TreeNodeAdv node) { if (node == null) throw new ArgumentNullException("node"); if (!IsMyNode(node)) throw new ArgumentException(); TreeNodeAdv parent = node.Parent; while (parent != _root) { parent.IsExpanded = true; parent = parent.Parent; } ScrollTo(node); } /// <summary> /// Make node visible, scroll if needed. All parent nodes of the specified node must be expanded /// </summary> /// <param name="node"></param> public void ScrollTo(TreeNodeAdv node) { if (node == null) throw new ArgumentNullException("node"); if (!IsMyNode(node)) throw new ArgumentException(); if (node.Row < 0) CreateRowMap(); int row = -1; if (node.Row < FirstVisibleRow) row = node.Row; else { int pageStart = _rowLayout.GetRowBounds(FirstVisibleRow).Top; int rowBottom = _rowLayout.GetRowBounds(node.Row).Bottom; if (rowBottom > pageStart + DisplayRectangle.Height - ColumnHeaderHeight) row = _rowLayout.GetFirstRow(node.Row); } if (row >= _vScrollBar.Minimum && row <= _vScrollBar.Maximum) _vScrollBar.Value = row; } public void ClearSelection() { BeginUpdate(); try { ClearSelectionInternal(); } finally { EndUpdate(); } } internal void ClearSelectionInternal() { while (Selection.Count > 0) Selection[0].IsSelected = false; } #endregion protected override void OnSizeChanged(EventArgs e) { ArrangeControls(); SafeUpdateScrollBars(); base.OnSizeChanged(e); } private void ArrangeControls() { int hBarSize = _hScrollBar.Height; int vBarSize = _vScrollBar.Width; Rectangle clientRect = ClientRectangle; _hScrollBar.SetBounds(clientRect.X, clientRect.Bottom - hBarSize, clientRect.Width - vBarSize, hBarSize); _vScrollBar.SetBounds(clientRect.Right - vBarSize, clientRect.Y, vBarSize, clientRect.Height - hBarSize); } private void SafeUpdateScrollBars() { if (InvokeRequired) Invoke(new MethodInvoker(UpdateScrollBars)); else UpdateScrollBars(); } private void UpdateScrollBars() { UpdateVScrollBar(); UpdateHScrollBar(); UpdateVScrollBar(); UpdateHScrollBar(); _hScrollBar.Width = DisplayRectangle.Width; _vScrollBar.Height = DisplayRectangle.Height; } private void UpdateHScrollBar() { _hScrollBar.Maximum = ContentWidth; _hScrollBar.LargeChange = Math.Max(DisplayRectangle.Width, 0); _hScrollBar.SmallChange = 5; _hScrollBar.Visible = _hScrollBar.LargeChange < _hScrollBar.Maximum; _hScrollBar.Value = Math.Min(_hScrollBar.Value, _hScrollBar.Maximum - _hScrollBar.LargeChange + 1); } private void UpdateVScrollBar() { _vScrollBar.Maximum = Math.Max(RowCount - 1, 0); _vScrollBar.LargeChange = _rowLayout.PageRowCount; _vScrollBar.Visible = (RowCount > 0) && (_vScrollBar.LargeChange <= _vScrollBar.Maximum); _vScrollBar.Value = Math.Min(_vScrollBar.Value, _vScrollBar.Maximum - _vScrollBar.LargeChange + 1); } protected override CreateParams CreateParams { [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] get { CreateParams res = base.CreateParams; switch (BorderStyle) { case BorderStyle.FixedSingle: res.Style |= 0x800000; break; case BorderStyle.Fixed3D: res.ExStyle |= 0x200; break; } return res; } } protected override void OnGotFocus(EventArgs e) { HideEditor(); UpdateView(); ChangeInput(); base.OnGotFocus(e); } protected override void OnLeave(EventArgs e) { if (_currentEditorOwner != null) _currentEditorOwner.ApplyChanges(); HideEditor(); UpdateView(); base.OnLeave(e); } protected override void OnFontChanged(EventArgs e) { base.OnFontChanged(e); _measureContext.Font = Font; FullUpdate(); } internal IEnumerable<NodeControlInfo> GetNodeControls(TreeNodeAdv node) { if (node == null) yield break; Rectangle rowRect = _rowLayout.GetRowBounds(node.Row); foreach (NodeControlInfo n in GetNodeControls(node, rowRect)) yield return n; } internal IEnumerable<NodeControlInfo> GetNodeControls(TreeNodeAdv node, Rectangle rowRect) { if (node == null) yield break; int y = rowRect.Y; int x = (node.Level - 1) * _indent + LeftMargin; int width = 0; Rectangle rect = Rectangle.Empty; if (ShowPlusMinus) { width = _plusMinus.GetActualSize(node, _measureContext).Width; rect = new Rectangle(x, y, width, rowRect.Height); if (UseColumns && Columns.Count > 0 && Columns[0].Width < rect.Right) rect.Width = Columns[0].Width - x; yield return new NodeControlInfo(_plusMinus, rect, node); x += width; } if (!UseColumns) { foreach (NodeControl c in NodeControls) { Size s = c.GetActualSize(node, _measureContext); if (!s.IsEmpty) { width = s.Width; rect = new Rectangle(x, y, width, rowRect.Height); x += rect.Width; yield return new NodeControlInfo(c, rect, node); } } } else { int right = 0; foreach (TreeColumn col in Columns) { if (col.IsVisible && col.Width > 0) { right += col.Width; for (int i = 0; i < NodeControls.Count; i++) { NodeControl nc = NodeControls[i]; if (nc.ParentColumn == col) { Size s = nc.GetActualSize(node, _measureContext); if (!s.IsEmpty) { bool isLastControl = true; for (int k = i + 1; k < NodeControls.Count; k++) if (NodeControls[k].ParentColumn == col) { isLastControl = false; break; } width = right - x; if (!isLastControl) width = s.Width; int maxWidth = Math.Max(0, right - x); rect = new Rectangle(x, y, Math.Min(maxWidth, width), rowRect.Height); x += width; yield return new NodeControlInfo(nc, rect, node); } } } x = right; } } } } internal static double Dist(Point p1, Point p2) { return Math.Sqrt(Math.Pow(p1.X - p2.X, 2) + Math.Pow(p1.Y - p2.Y, 2)); } public void FullUpdate() { if (InvokeRequired) Invoke(new MethodInvoker(UnsafeFullUpdate)); else UnsafeFullUpdate(); } private void UnsafeFullUpdate() { _rowLayout.ClearCache(); CreateRowMap(); SafeUpdateScrollBars(); UpdateView(); _needFullUpdate = false; } internal void UpdateView() { if (!_suspendUpdate) Invalidate(false); } internal void UpdateHeaders() { Invalidate(new Rectangle(0,0, Width, ColumnHeaderHeight)); } internal void UpdateColumns() { FullUpdate(); } private void CreateNodes() { Selection.Clear(); SelectionStart = null; _root = new TreeNodeAdv(this, null); _root.IsExpanded = true; if (_root.Nodes.Count > 0) CurrentNode = _root.Nodes[0]; else CurrentNode = null; } internal void ReadChilds(TreeNodeAdv parentNode) { ReadChilds(parentNode, false); } internal void ReadChilds(TreeNodeAdv parentNode, bool performFullUpdate) { if (!parentNode.IsLeaf) { parentNode.IsExpandedOnce = true; List<TreeNodeAdv> oldNodes = new List<TreeNodeAdv>(parentNode.Nodes); parentNode.Nodes.Clear(); if (Model != null) { IEnumerable items = Model.GetChildren(GetPath(parentNode)); if (items != null) foreach (object obj in items) { bool found = false; if (obj != null) { for (int i = 0; i < oldNodes.Count; i++) if (obj == oldNodes[i].Tag) { oldNodes[i].RightBounds = oldNodes[i].Height = null; AddNode(parentNode, -1, oldNodes[i]); oldNodes.RemoveAt(i); found = true; break; } } if (!found) AddNewNode(parentNode, obj, -1); if (performFullUpdate) FullUpdate(); } } } } private void AddNewNode(TreeNodeAdv parent, object tag, int index) { TreeNodeAdv node = new TreeNodeAdv(this, tag); AddNode(parent, index, node); } private void AddNode(TreeNodeAdv parent, int index, TreeNodeAdv node) { if (index >= 0 && index < parent.Nodes.Count) parent.Nodes.Insert(index, node); else parent.Nodes.Add(node); node.IsLeaf = Model.IsLeaf(GetPath(node)); if (node.IsLeaf) node.Nodes.Clear(); if (!LoadOnDemand || node.IsExpandedOnce) ReadChilds(node); } private struct ExpandArgs { public TreeNodeAdv Node; public bool Value; public bool IgnoreChildren; } public void AbortBackgroundExpandingThreads() { _threadPool.CancelAll(true); for (int i = 0; i < _expandingNodes.Count; i++) _expandingNodes[i].IsExpandingNow = false; _expandingNodes.Clear(); Invalidate(); } internal void SetIsExpanded(TreeNodeAdv node, bool value, bool ignoreChildren) { ExpandArgs eargs = new ExpandArgs(); eargs.Node = node; eargs.Value = value; eargs.IgnoreChildren = ignoreChildren; if (AsyncExpanding && LoadOnDemand && !_threadPool.IsMyThread(Thread.CurrentThread)) { WaitCallback wc = delegate(object argument) { SetIsExpanded((ExpandArgs)argument); }; _threadPool.QueueUserWorkItem(wc, eargs); } else SetIsExpanded(eargs); } private void SetIsExpanded(ExpandArgs eargs) { bool update = !eargs.IgnoreChildren && !AsyncExpanding; if (update) BeginUpdate(); try { if (IsMyNode(eargs.Node) && eargs.Node.IsExpanded != eargs.Value) SetIsExpanded(eargs.Node, eargs.Value); if (!eargs.IgnoreChildren) SetIsExpandedRecursive(eargs.Node, eargs.Value); } finally { if (update) EndUpdate(); } } internal void SetIsExpanded(TreeNodeAdv node, bool value) { if (Root == node && !value) return; //Can't collapse root node if (value) OnExpanding(node); else OnCollapsing(node); if (value && !node.IsExpandedOnce) { if (AsyncExpanding && LoadOnDemand) { AddExpandingNode(node); node.AssignIsExpanded(true); Invalidate(); } ReadChilds(node, AsyncExpanding); RemoveExpandingNode(node); } node.AssignIsExpanded(value); SmartFullUpdate(); if (value) OnExpanded(node); else OnCollapsed(node); } private void RemoveExpandingNode(TreeNodeAdv node) { node.IsExpandingNow = false; _expandingNodes.Remove(node); } private void AddExpandingNode(TreeNodeAdv node) { node.IsExpandingNow = true; _expandingNodes.Add(node); ExpandingIcon.Start(); } internal void SetIsExpandedRecursive(TreeNodeAdv root, bool value) { for (int i = 0; i < root.Nodes.Count; i++) { TreeNodeAdv node = root.Nodes[i]; node.IsExpanded = value; SetIsExpandedRecursive(node, value); } } private void CreateRowMap() { RowMap.Clear(); int row = 0; _contentWidth = 0; foreach (TreeNodeAdv node in VisibleNodes) { node.Row = row; RowMap.Add(node); if (!UseColumns) { _contentWidth = Math.Max(_contentWidth, GetNodeWidth(node)); } row++; } if (UseColumns) { _contentWidth = 0; foreach (TreeColumn col in _columns) if (col.IsVisible) _contentWidth += col.Width; } } private int GetNodeWidth(TreeNodeAdv node) { if (node.RightBounds == null) { Rectangle res = GetNodeBounds(GetNodeControls(node, Rectangle.Empty)); node.RightBounds = res.Right; } return node.RightBounds.Value; } internal Rectangle GetNodeBounds(TreeNodeAdv node) { return GetNodeBounds(GetNodeControls(node)); } private Rectangle GetNodeBounds(IEnumerable<NodeControlInfo> nodeControls) { Rectangle res = Rectangle.Empty; foreach (NodeControlInfo info in nodeControls) { if (res == Rectangle.Empty) res = info.Bounds; else res = Rectangle.Union(res, info.Bounds); } return res; } private void _vScrollBar_ValueChanged(object sender, EventArgs e) { FirstVisibleRow = _vScrollBar.Value; } private void _hScrollBar_ValueChanged(object sender, EventArgs e) { OffsetX = _hScrollBar.Value; } internal void SmartFullUpdate() { if (_suspendUpdate) _needFullUpdate = true; else FullUpdate(); } internal bool IsMyNode(TreeNodeAdv node) { if (node == null) return false; if (node.Tree != this) return false; while (node.Parent != null) node = node.Parent; return node == _root; } private void UpdateSelection() { bool flag = false; if (!IsMyNode(CurrentNode)) CurrentNode = null; if (!IsMyNode(_selectionStart)) _selectionStart = null; for (int i = Selection.Count - 1; i >= 0; i--) if (!IsMyNode(Selection[i])) { flag = true; Selection.RemoveAt(i); } if (flag) OnSelectionChanged(); } internal void ChangeColumnWidth(TreeColumn column) { if (!(_input is ResizeColumnState)) { FullUpdate(); OnColumnWidthChanged(column); } } public TreeNodeAdv FindNode(TreePath path) { return FindNode(path, false); } public TreeNodeAdv FindNode(TreePath path, bool readChilds) { if (path.IsEmpty()) return _root; else return FindNode(_root, path, 0, readChilds); } private TreeNodeAdv FindNode(TreeNodeAdv root, TreePath path, int level, bool readChilds) { if (!root.IsExpandedOnce && readChilds) ReadChilds(root); for (int i = 0; i < root.Nodes.Count; i++) { TreeNodeAdv node = root.Nodes[i]; if (node.Tag == path.FullPath[level]) { if (level == path.FullPath.Length - 1) return node; else return FindNode(node, path, level + 1, readChilds); } } return null; } public TreeNodeAdv FindNodeByTag(object tag) { return FindNodeByTag(_root, tag); } private TreeNodeAdv FindNodeByTag(TreeNodeAdv root, object tag) { foreach (TreeNodeAdv node in root.Nodes) { if (node.Tag == tag) return node; TreeNodeAdv res = FindNodeByTag(node, tag); if (res != null) return res; } return null; } #region Editor public void DisplayEditor(Control control, EditableControl owner) { if (control == null || owner == null) throw new ArgumentNullException(); if (CurrentNode != null) { HideEditor(); _currentEditor = control; _currentEditorOwner = owner; UpdateEditorBounds(); UpdateView(); control.Parent = this; control.Focus(); owner.UpdateEditor(control); } } public void UpdateEditorBounds() { if (_currentEditor != null) { EditorContext context = new EditorContext(); context.Owner = _currentEditorOwner; context.CurrentNode = CurrentNode; context.Editor = _currentEditor; context.DrawContext = _measureContext; SetEditorBounds(context); } } public void HideEditor() { if (_currentEditorOwner != null) { _currentEditorOwner.HideEditor(_currentEditor); _currentEditor = null; _currentEditorOwner = null; } } private void SetEditorBounds(EditorContext context) { foreach (NodeControlInfo info in GetNodeControls(context.CurrentNode)) { if (context.Owner == info.Control && info.Control is EditableControl) { Point p = info.Bounds.Location; p.X += info.Control.LeftMargin; p.X -= OffsetX; p.Y -= (_rowLayout.GetRowBounds(FirstVisibleRow).Y - ColumnHeaderHeight); int width = DisplayRectangle.Width - p.X; if (UseColumns && info.Control.ParentColumn != null && Columns.Contains(info.Control.ParentColumn)) { Rectangle rect = GetColumnBounds(info.Control.ParentColumn.Index); width = rect.Right - OffsetX - p.X; } context.Bounds = new Rectangle(p.X, p.Y, width, info.Bounds.Height); ((EditableControl)info.Control).SetEditorBounds(context); return; } } } private Rectangle GetColumnBounds(int column) { int x = 0; for (int i = 0; i < Columns.Count; i++) { if (Columns[i].IsVisible) { if (i < column) x += Columns[i].Width; else return new Rectangle(x, 0, Columns[i].Width, 0); } } return Rectangle.Empty; } #endregion #region ModelEvents private void BindModelEvents() { _model.NodesChanged += new EventHandler<TreeModelEventArgs>(_model_NodesChanged); _model.NodesInserted += new EventHandler<TreeModelEventArgs>(_model_NodesInserted); _model.NodesRemoved += new EventHandler<TreeModelEventArgs>(_model_NodesRemoved); _model.StructureChanged += new EventHandler<TreePathEventArgs>(_model_StructureChanged); } private void UnbindModelEvents() { _model.NodesChanged -= new EventHandler<TreeModelEventArgs>(_model_NodesChanged); _model.NodesInserted -= new EventHandler<TreeModelEventArgs>(_model_NodesInserted); _model.NodesRemoved -= new EventHandler<TreeModelEventArgs>(_model_NodesRemoved); _model.StructureChanged -= new EventHandler<TreePathEventArgs>(_model_StructureChanged); } private void _model_StructureChanged(object sender, TreePathEventArgs e) { if (e.Path == null) throw new ArgumentNullException(); TreeNodeAdv node = FindNode(e.Path); if (node != null) { ReadChilds(node); UpdateSelection(); SmartFullUpdate(); } //else // throw new ArgumentException("Path not found"); } private void _model_NodesRemoved(object sender, TreeModelEventArgs e) { TreeNodeAdv parent = FindNode(e.Path); if (parent != null) { if (e.Indices != null) { List<int> list = new List<int>(e.Indices); list.Sort(); for (int n = list.Count - 1; n >= 0; n--) { int index = list[n]; if (index >= 0 && index <= parent.Nodes.Count) parent.Nodes.RemoveAt(index); else throw new ArgumentOutOfRangeException("Index out of range"); } } else { for (int i = parent.Nodes.Count - 1; i >= 0; i--) { for (int n = 0; n < e.Children.Length; n++) if (parent.Nodes[i].Tag == e.Children[n]) { parent.Nodes.RemoveAt(i); break; } } } } UpdateSelection(); SmartFullUpdate(); } private void _model_NodesInserted(object sender, TreeModelEventArgs e) { if (e.Indices == null) throw new ArgumentNullException("Indices"); TreeNodeAdv parent = FindNode(e.Path); if (parent != null) { for (int i = 0; i < e.Children.Length; i++) AddNewNode(parent, e.Children[i], e.Indices[i]); } SmartFullUpdate(); } private void _model_NodesChanged(object sender, TreeModelEventArgs e) { TreeNodeAdv parent = FindNode(e.Path); if (parent != null && parent.IsVisible && parent.IsExpanded) { if (InvokeRequired) Invoke(new UpdateContentWidthDelegate(ClearNodesSize), e, parent); else ClearNodesSize(e, parent); SmartFullUpdate(); } } private delegate void UpdateContentWidthDelegate(TreeModelEventArgs e, TreeNodeAdv parent); private void ClearNodesSize(TreeModelEventArgs e, TreeNodeAdv parent) { if (e.Indices != null) { foreach (int index in e.Indices) { if (index >= 0 && index < parent.Nodes.Count) { TreeNodeAdv node = parent.Nodes[index]; node.Height = node.RightBounds = null; } else throw new ArgumentOutOfRangeException("Index out of range"); } } else { foreach (TreeNodeAdv node in parent.Nodes) { foreach (object obj in e.Children) if (node.Tag == obj) { node.Height = node.RightBounds = null; } } } } #endregion } }
using System; using Foundation; using OpenGLES; using CoreGraphics; using CoreVideo; using OpenTK.Graphics.ES20; namespace AVCustomEdit { public class OpenGLRenderer : NSObject { public int ProgramY = -1; public int ProgramUV = -1; public CGAffineTransform RenderTransform; public CVOpenGLESTextureCache VideoTextureCache; public EAGLContext CurrentContext; public uint OffscreenBufferHandle; public int[] Uniforms = new int[(int)Uniform.Num_Uniforms]; string vertShaderSource = "attribute vec4 position; \n" + "attribute vec2 texCoord; \n" + "uniform mat4 renderTransform; \n"+ "varying vec2 texCoordVarying; \n"+ "void main() \n"+ "{ \n"+ "gl_Position = position * renderTransform; \n"+ "texCoordVarying = texCoord; \n"+ "}"; string fragShaderYSource = "varying highp vec2 texCoordVarying; \n"+ " uniform sampler2D SamplerY; \n"+ "void main() \n"+ "{ \n"+ "gl_FragColor.r = texture2D(SamplerY, texCoordVarying).r; \n"+ "}"; string fragShaderUVSource ="varying highp vec2 texCoordVarying; \n"+ "uniform sampler2D SamplerUV; \n"+ "void main() \n"+ "{ \n"+ "gl_FragColor.rg = texture2D(SamplerUV, texCoordVarying).rg; \n"+ "}"; public OpenGLRenderer () : base() { CurrentContext = new EAGLContext (EAGLRenderingAPI.OpenGLES2); EAGLContext.SetCurrentContext (CurrentContext); SetupOffScreenRenderContext(); loadShaders (); EAGLContext.SetCurrentContext (null); } public virtual CVOpenGLESTexture LumaTextureForPixelBuffer (CVPixelBuffer pixelBuffer) { CVOpenGLESTexture lumaTexture = null; CVReturn err; if (VideoTextureCache == null) { Console.Error.WriteLine ("No video texture cache"); return lumaTexture; } // Periodic texture cache flush every frame VideoTextureCache.Flush (0); // CVOpenGLTextureCacheCreateTextureFromImage will create GL texture optimally from CVPixelBufferRef. // UV lumaTexture = VideoTextureCache.TextureFromImage (pixelBuffer, true, All.RedExt, (int)pixelBuffer.Width,(int) pixelBuffer.Height, All.RedExt, DataType.UnsignedByte, 0, out err); if (lumaTexture == null || err != CVReturn.Success) Console.Error.WriteLine ("Error at creating luma texture using CVOpenGLESTextureCacheCreateTextureFromImage: " + err.ToString ()); return lumaTexture; } public virtual CVOpenGLESTexture ChromaTextureForPixelBuffer (CVPixelBuffer pixelBuffer) { CVOpenGLESTexture chromaTexture = null; CVReturn err; if (VideoTextureCache == null) { Console.Error.WriteLine ("No video texture cache"); return chromaTexture; } // Periodic texture cache flush every frame VideoTextureCache.Flush (0); // CVOpenGLTextureCacheCreateTextureFromImage will create GL texture optimally from CVPixelBufferRef. // UV var height = pixelBuffer.GetHeightOfPlane (1); var width = pixelBuffer.GetWidthOfPlane (1); chromaTexture = VideoTextureCache.TextureFromImage (pixelBuffer, true, All.RgExt, (int)width, (int)height, All.RgExt, DataType.UnsignedByte, 1, out err); if (chromaTexture == null || err != CVReturn.Success) Console.Error.WriteLine ("Error at creating chroma texture using CVOpenGLESTextureCacheCreateTextureFromImage: " + err.ToString ()); return chromaTexture; } public virtual void RenderPixelBuffer(CVPixelBuffer destinationPixelBuffer, CVPixelBuffer foregroundPixelBuffer, CVPixelBuffer backgroundPixelBuffer, float tween) { DoesNotRecognizeSelector (new ObjCRuntime.Selector ("_cmd")); } public void SetupOffScreenRenderContext() { //-- Create CVOpenGLESTextureCacheRef for optimal CVPixelBufferRef to GLES texture conversion. if (VideoTextureCache != null) { VideoTextureCache.Dispose (); VideoTextureCache = null; } VideoTextureCache = CVOpenGLESTextureCache.FromEAGLContext (CurrentContext); GL.Disable (EnableCap.DepthTest); GL.GenFramebuffers (1, out OffscreenBufferHandle); GL.BindFramebuffer (FramebufferTarget.Framebuffer, OffscreenBufferHandle); } // OpenGL ES 2 shader compilation bool loadShaders() { int vertShader = 0, fragShaderY = 0, fragShaderUV = 0; // Create the shader program. ProgramY = GL.CreateProgram (); ProgramUV = GL.CreateProgram (); // Create and compile the vertex shader. if (!compileShader (ShaderType.VertexShader, vertShaderSource, out vertShader)) { Console.Error.WriteLine ("Failed to compile vertex shader"); return false; } if(!compileShader (ShaderType.FragmentShader, fragShaderYSource, out fragShaderY)) { Console.Error.WriteLine ("Failed to compile Y fragment shader"); return false; } if(!compileShader (ShaderType.FragmentShader, fragShaderUVSource, out fragShaderUV)) { Console.Error.WriteLine ("Failed to compile UV fragment shader"); return false; } GL.AttachShader (ProgramY, vertShader); GL.AttachShader (ProgramY, fragShaderY); GL.AttachShader (ProgramUV, vertShader); GL.AttachShader (ProgramUV, fragShaderUV); // Bind attribute locations. This needs to be done prior to linking. GL.BindAttribLocation (ProgramY,(int) Attrib.Vertex_Y, "position"); GL.BindAttribLocation (ProgramY,(int) Attrib.TexCoord_Y, "texCoord"); GL.BindAttribLocation (ProgramUV,(int) Attrib.Vertex_UV, "position"); GL.BindAttribLocation (ProgramUV, (int)Attrib.TexCoord_UV, "texCoord"); // Link the program. if (!linkProgram (ProgramY) || !this.linkProgram (ProgramUV)) { Console.Error.WriteLine ("Failed to link program"); if (vertShader != 0) { GL.DeleteShader (vertShader); vertShader = 0; } if (fragShaderY != 0) { GL.DeleteShader (fragShaderY); fragShaderY = 0; } if (fragShaderUV != 0) { GL.DeleteShader (fragShaderUV); fragShaderUV = 0; } if (ProgramY != 0) { GL.DeleteProgram (ProgramY); ProgramY = 0; } if (ProgramUV != 0) { GL.DeleteProgram (ProgramUV); ProgramUV = 0; } return false; } // Get uniform locations. Uniforms [(int)Uniform.Y] = GL.GetUniformLocation (ProgramY, "SamplerY"); Uniforms [(int)Uniform.UV] = GL.GetUniformLocation (ProgramUV, "SamplerUV"); Uniforms [(int)Uniform.Render_Transform_Y] = GL.GetUniformLocation (ProgramY, "renderTransform"); Uniforms [(int)Uniform.Render_Transform_UV] = GL.GetUniformLocation (ProgramUV, "renderTransform"); //Release vertex and fragment shaders. if (vertShader != 0) { GL.DetachShader (ProgramY, vertShader); GL.DetachShader (ProgramUV, vertShader); GL.DeleteShader (vertShader); } if (fragShaderY != 0) { GL.DetachShader (ProgramY, fragShaderY); GL.DeleteShader (fragShaderY); } if (fragShaderUV != 0) { GL.DetachShader (ProgramUV, fragShaderUV); GL.DeleteShader (fragShaderUV); } return true; } bool compileShader(ShaderType type, string sourceString, out int shader) { if (string.IsNullOrEmpty (sourceString)) { Console.Error.WriteLine ("Failed to load vertex shader: Empty source string"); shader = 0; return false; } int status; shader = GL.CreateShader (type); GL.ShaderSource (shader, sourceString); GL.CompileShader (shader); #if DEBUG int logLength; GL.GetShader (shader, ShaderParameter.InfoLogLength, out logLength); if (logLength > 0) { var log = GL.GetShaderInfoLog (shader); Console.WriteLine ("Shader compile log: {0}", log); } #endif GL.GetShader (shader, ShaderParameter.CompileStatus, out status); if (status == 0) { GL.DeleteShader (shader); return false; } return true; } bool linkProgram(int program) { int status = 0; GL.LinkProgram (program); #if DEBUG int logLength = 0; GL.GetProgram(program, ProgramParameter.InfoLogLength, out logLength); if (logLength > 0) { System.Text.StringBuilder log = new System.Text.StringBuilder(logLength); GL.GetProgramInfoLog (program, logLength, out logLength, log); Console.WriteLine("Program link log: " + log.ToString()); log.Clear (); } #endif GL.GetProgram (program, ProgramParameter.LinkStatus, out status); if (status == 0) return false; return true; } bool validateProgram(int program) { int logLength = 0; int status = 0; GL.ValidateProgram (program); GL.GetProgram (program, ProgramParameter.InfoLogLength, out logLength); if (logLength > 0) { System.Text.StringBuilder log = new System.Text.StringBuilder(logLength); GL.GetProgramInfoLog (program, logLength, out logLength, log); Console.WriteLine("Program validate log: " + log.ToString()); log.Clear (); } GL.GetProgram (program, ProgramParameter.ValidateStatus, out status); if (status == 0) return false; return true; } } public enum Uniform { Y, UV, Render_Transform_Y, Render_Transform_UV, Num_Uniforms } public enum Attrib{ Vertex_Y, TexCoord_Y, Vertex_UV, TexCoord_UV, Num_Attributes } }
using System.Collections.Generic; namespace IxMilia.Iges.Entities { public abstract partial class IgesEntity { internal static IgesEntity FromData(IgesDirectoryData directoryData, List<string> parameters, IgesReaderBinder binder) { IgesEntity entity = null; switch (directoryData.EntityType) { case IgesEntityType.AngularDimension: entity = new IgesAngularDimension(); break; case IgesEntityType.AssociativityInstance: switch (directoryData.FormNumber) { case 5: entity = new IgesLabelDisplayAssociativity(); break; } break; case IgesEntityType.Block: entity = new IgesBlock(); break; case IgesEntityType.BooleanTree: entity = new IgesBooleanTree(); break; case IgesEntityType.Boundary: entity = new IgesBoundary(); break; case IgesEntityType.BoundedSurface: entity = new IgesBoundedSurface(); break; case IgesEntityType.CircularArc: entity = new IgesCircularArc(); break; case IgesEntityType.ColorDefinition: entity = new IgesColorDefinition(); break; case IgesEntityType.CompositeCurve: entity = new IgesCompositeCurve(); break; case IgesEntityType.ConicArc: entity = new IgesConicArc(); break; case IgesEntityType.ConnectPoint: entity = new IgesConnectPoint(); break; case IgesEntityType.CopiousData: entity = new IgesCopiousData(); break; case IgesEntityType.CurveDimension: entity = new IgesCurveDimension(); break; case IgesEntityType.CurveOnAParametricSurface: entity = new IgesCurveOnAParametricSurface(); break; case IgesEntityType.DiameterDimension: entity = new IgesDiameterDimension(); break; case IgesEntityType.Direction: entity = new IgesDirection(); break; case IgesEntityType.ElementResults: entity = new IgesElementResults(); break; case IgesEntityType.Ellipsoid: entity = new IgesEllipsoid(); break; case IgesEntityType.FlagNote: entity = new IgesFlagNote(); break; case IgesEntityType.Flash: entity = new IgesFlash(); break; case IgesEntityType.FiniteElement: entity = new IgesFiniteElementDummy(); break; case IgesEntityType.GeneralLabel: entity = new IgesGeneralLabel(); break; case IgesEntityType.GeneralNote: entity = new IgesGeneralNote(); break; case IgesEntityType.GeneralSymbol: entity = new IgesGeneralSymbol(); break; case IgesEntityType.Leader: entity = new IgesLeader(); break; case IgesEntityType.Line: entity = new IgesLine(); break; case IgesEntityType.LinearDimension: entity = new IgesLinearDimension(); break; case IgesEntityType.LineFontDefinition: switch (directoryData.FormNumber) { case 1: entity = new IgesTemplateLineFontDefinition(); break; case 2: entity = new IgesPatternLineFontDefinition(); break; } break; case IgesEntityType.ManifestSolidBRepObject: entity = new IgesManifestSolidBRepObject(); break; case IgesEntityType.NewGeneralNote: entity = new IgesNewGeneralNote(); break; case IgesEntityType.NodalDisplacementAndRotation: entity = new IgesNodalDisplacementAndRotation(); break; case IgesEntityType.NodalResults: entity = new IgesNodalResults(); break; case IgesEntityType.Node: entity = new IgesNode(); break; case IgesEntityType.Null: entity = new IgesNull(); break; case IgesEntityType.OffsetCurve: entity = new IgesOffsetCurve(); break; case IgesEntityType.OffsetSurface: entity = new IgesOffsetSurface(); break; case IgesEntityType.OrdinateDimension: entity = new IgesOrdinateDimension(); break; case IgesEntityType.ParametricSplineCurve: entity = new IgesParametricSplineCurve(); break; case IgesEntityType.ParametricSplineSurface: entity = new IgesParametricSplineSurface(); break; case IgesEntityType.Plane: entity = new IgesPlane(); break; case IgesEntityType.PlaneSurface: entity = new IgesPlaneSurface(); break; case IgesEntityType.Point: entity = new IgesLocation(); break; case IgesEntityType.PointDimension: entity = new IgesPointDimension(); break; case IgesEntityType.Property: switch (directoryData.FormNumber) { case 1: entity = new IgesDefinitionLevelsProperty(); break; case 15: entity = new IgesNameProperty(); break; } break; case IgesEntityType.RadiusDimension: entity = new IgesRadiusDimension(); break; case IgesEntityType.RationalBSplineCurve: entity = new IgesRationalBSplineCurve(); break; case IgesEntityType.RationalBSplineSurface: entity = new IgesRationalBSplineSurface(); break; case IgesEntityType.RightAngularWedge: entity = new IgesRightAngularWedge(); break; case IgesEntityType.RightCircularConeFrustrum: entity = new IgesRightCircularConeFrustrum(); break; case IgesEntityType.RightCircularConicalSurface: entity = new IgesRightCircularConicalSurface(); break; case IgesEntityType.RightCircularCylinder: entity = new IgesRightCircularCylinder(); break; case IgesEntityType.RightCircularCylindricalSurface: entity = new IgesRightCircularCylindricalSurface(); break; case IgesEntityType.RuledSurface: entity = new IgesRuledSurface(); break; case IgesEntityType.SectionedArea: entity = new IgesSectionedArea(); break; case IgesEntityType.SelectedComponent: entity = new IgesSelectedComponent(); break; case IgesEntityType.SingularSubfigureInstance: entity = new IgesSingularSubfigureInstance(); break; case IgesEntityType.SolidAssembly: entity = new IgesSolidAssembly(); break; case IgesEntityType.SolidOfLinearExtrusion: entity = new IgesSolidOfLinearExtrusion(); break; case IgesEntityType.SolidOfRevolution: entity = new IgesSolidOfRevolution(); break; case IgesEntityType.Sphere: entity = new IgesSphere(); break; case IgesEntityType.SphericalSurface: entity = new IgesSphericalSurface(); break; case IgesEntityType.SubfigureDefinition: entity = new IgesSubfigureDefinition(); break; case IgesEntityType.SurfaceOfRevolution: entity = new IgesSurfaceOfRevolution(); break; case IgesEntityType.TabulatedCylinder: entity = new IgesTabulatedCylinder(); break; case IgesEntityType.TextDisplayTemplate: entity = new IgesTextDisplayTemplate(); break; case IgesEntityType.TextFontDefinition: entity = new IgesTextFontDefinition(); break; case IgesEntityType.ToroidalSurface: entity = new IgesToroidalSurface(); break; case IgesEntityType.Torus: entity = new IgesTorus(); break; case IgesEntityType.TransformationMatrix: entity = new IgesTransformationMatrix(); break; case IgesEntityType.TrimmedParametricSurface: entity = new IgesTrimmedParametricSurface(); break; case IgesEntityType.View: switch (directoryData.FormNumber) { case 0: entity = new IgesView(); break; case 1: entity = new IgesPerspectiveView(); break; } break; } if (entity != null) { entity.PopulateDirectoryData(directoryData); int nextIndex = entity.ReadParameters(parameters, binder); entity.ReadCommonPointers(parameters, nextIndex, binder); } return entity; } } }
using System; using System.Collections.Generic; using System.Threading; using MonoTouch.Foundation; using System.IO; using MonoTouch.UIKit; namespace ClanceysLib { /// <summary> /// Static downloader class. /// This class will download files one at a time. /// If the app is closed or the lock screen is enabled, the app will continue to dowload the remaining files. /// If the app runs out of the alloted background time, It will alert the user to reopen the app to avoid disruption. /// /// Use: /// To use just call Downloader.Add(); /// </summary> public static class Downloader { private static bool _isBusy; private static List<string> remainingFiles = new List<string> (); private static int bgTask = 0; private static ProgressDialog progressDialog = null; private static bool _cancel = false; private static bool _ShowProgress = true; static readonly ReaderWriterLockSlim _locker = new ReaderWriterLockSlim (); private static NSString invoker = new NSString (""); private static UIApplication app = UIApplication.SharedApplication; public static void StartDownload () { // If already downloading do nothing... if (isBusy) return; //If the list is empty do nothing... if (Remaining == 0) { isBusy = false; return; } cancel = false; isBusy = true; Thread thread = new Thread (new ThreadStart (startDownloading)); thread.Start (); } private static void startDownloading () { //Thread gc... using (NSAutoreleasePool pool = new NSAutoreleasePool ()) { Console.WriteLine ("Starting the downloading process"); downloadAllFiles (); } } public static int Remaining { get { _locker.EnterReadLock (); try { return remainingFiles.Count; } finally { _locker.ExitReadLock (); } } } public static bool isBusy { get { _locker.EnterReadLock (); try { return _isBusy; } finally { _locker.ExitReadLock (); } } private set { _locker.EnterWriteLock (); try { _isBusy = value; } finally { _locker.ExitWriteLock (); } } } public static bool ShowProgress { get { _locker.EnterReadLock (); try { return _ShowProgress; } finally { _locker.ExitReadLock (); } } set { _locker.EnterWriteLock (); try { _ShowProgress = value; } finally { _locker.ExitWriteLock (); } } } private static bool cancel { get { _locker.EnterReadLock (); try { return _cancel; } finally { _locker.ExitReadLock (); } } set { _locker.EnterWriteLock (); try { _cancel = value; } finally { _locker.ExitWriteLock (); } } } private static void downloadAllFiles () { if (Remaining == 0 || cancel) { downloadComplete (); return; } if (bgTask == 0) bgTask = app.BeginBackgroundTask (delegate { outOfTime (); Console.WriteLine ("Didnt update on time..."); }); downloadFile (getFilePath (0), delegate { if (Remaining == 0 || cancel) { downloadComplete (); } else downloadAllFiles (); }); } private static void downloadComplete () { Console.WriteLine ("Downloads Complete"); setStatus (statusType.Completed, ""); isBusy = false; app.EndBackgroundTask (bgTask); bgTask = 0; } private static void downloadFile (string filePath, Action completed) { Console.WriteLine ("Starting: " + filePath); try { var fileName = Path.GetFileNameWithoutExtension (filePath); setStatus (statusType.Update, fileName); //TODO: Remove Sleeper Add your code to download the file or process it in some way. // simulates the time it would take to download something Thread.Sleep (6000); //Remove after download is complete removeFile (filePath); } catch (Exception ex) { setStatus (statusType.Error, ex.Message); StopDownloading (); } //Tell the other thread your done.... Console.WriteLine ("Completed: " + filePath); if (completed != null) completed (); } private enum statusType { Update, Error, Completed } private static void setStatus (statusType status, string inStatus) { if (!ShowProgress) { if (progressDialog != null) { progressDialog.dispose (); progressDialog = null; } return; } invoker.InvokeOnMainThread (delegate { if (progressDialog == null) { progressDialog = new ProgressDialog ("Downloading", delegate { progressDialog.setMessage ("Canceling..."); StopDownloading (); }); } if (status == Downloader.statusType.Completed) { // successful completion // tell the user all set progressDialog.dispose (); progressDialog = null; UIAlertView alert = new UIAlertView ("Success", "Finished update.", null, "OK"); alert.Show (); } else if (status == statusType.Update) { // no errors - normal status update //this was s progressDialog.setMessage (Path.GetFileNameWithoutExtension (inStatus)); } else { progressDialog.dispose (); progressDialog = null; // some error occurred // tell the user about it UIAlertView alert = new UIAlertView ("Error", inStatus, null, "OK"); alert.Show (); } }); } public static void StopDownloading () { cancel = true; } public static void AddFile (string filePath) { _locker.EnterUpgradeableReadLock (); try { if (!remainingFiles.Contains (filePath)) { _locker.EnterWriteLock (); try { remainingFiles.Add (filePath); } finally { _locker.ExitWriteLock (); } } StartDownload (); } finally { _locker.ExitUpgradeableReadLock (); } } private static void removeFile (string filePath) { _locker.EnterWriteLock (); try { remainingFiles.Remove (filePath); } finally { _locker.ExitWriteLock (); } } private static string getFilePath (int index) { _locker.EnterReadLock (); try { return remainingFiles[index]; } finally { _locker.ExitReadLock (); } } /// <summary> /// This will send a local push notification warning the user the download /// is not complete and will be canceled if they dont reopen the app, If /// opened on time the download will continue perfectly. /// </summary> private static void outOfTime () { var notify = new UILocalNotification (); notify.AlertAction = "Ok"; notify.AlertBody = "Your Download is about to be canceled!"; notify.HasAction = true; notify.SoundName = UILocalNotification.DefaultSoundName; notify.FireDate = NSDate.Now; notify.TimeZone = NSTimeZone.DefaultTimeZone; //NSDictionary param = NSDictionary.FromObjectsAndKeys(objs,keys); //notify.UserInfo = param; app.ScheduleLocalNotification (notify); Console.WriteLine ("out of time:" + app.BackgroundTimeRemaining); } private class ProgressDialog { UIAlertView myAlert; public ProgressDialog (string title, EventHandler<MonoTouch.UIKit.UIButtonEventArgs> Clicked) { myAlert = new UIAlertView (); myAlert.Title = title; myAlert.Message = "In progress..."; myAlert.Clicked += Clicked; myAlert.AddButton ("Cancel"); myAlert.Show (); } public void dispose () { // dismiss with button clicked so if invoked on another thread we don't die for some reason myAlert.DismissWithClickedButtonIndex (0, true); myAlert.Dispose (); myAlert = null; } public void setMessage (string msg) { myAlert.Message = msg; Console.WriteLine ("setting message: " + msg); } } } }
//----------------------------------------------------------------------- // <copyright file="ARCoreIOSLifecycleManager.cs" company="Google"> // // Copyright 2018 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCoreInternal { using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; using GoogleARCore; using UnityEngine; internal class ARCoreIOSLifecycleManager : ILifecycleManager { private const string k_CloudServicesApiKeyPath = "RuntimeSettings/CloudServicesApiKey"; private static ARCoreIOSLifecycleManager s_Instance; private IntPtr m_SessionHandle = IntPtr.Zero; private IntPtr m_FrameHandle = IntPtr.Zero; // Avoid warnings for fields that are unused on Android platform. #pragma warning disable 67, 414 private string m_CloudServicesApiKey; private bool m_SessionEnabled = false; private IntPtr m_RealArKitSessionHandle = IntPtr.Zero; public event Action UpdateSessionFeatures; public event Action EarlyUpdate; public event Action<bool> OnSessionSetEnabled; #pragma warning restore 67, 414 public static ARCoreIOSLifecycleManager Instance { get { if (s_Instance == null) { s_Instance = new ARCoreIOSLifecycleManager(); s_Instance._Initialize(); s_Instance.m_CloudServicesApiKey = (Resources.Load(k_CloudServicesApiKeyPath) as TextAsset).text; #if ARCORE_IOS_SUPPORT UnityEngine.XR.iOS.UnityARSessionNativeInterface.ARFrameUpdatedEvent += s_Instance._OnARKitFrameUpdated; #endif } return s_Instance; } } public SessionStatus SessionStatus { get; private set; } public LostTrackingReason LostTrackingReason { get; private set; } public ARCoreSession SessionComponent { get; private set; } public NativeSession NativeSession { get; private set; } public bool IsSessionChangedThisFrame { get; private set; } public AsyncTask<ApkAvailabilityStatus> CheckApkAvailability() { return new AsyncTask<ApkAvailabilityStatus>( ApkAvailabilityStatus.UnsupportedDeviceNotCapable); } public AsyncTask<ApkInstallationStatus> RequestApkInstallation(bool userRequested) { return new AsyncTask<ApkInstallationStatus>(ApkInstallationStatus.Error); } public void CreateSession(ARCoreSession sessionComponent) { #if ARCORE_IOS_SUPPORT if (SessionComponent != null) { Debug.LogError("Multiple ARCore session components cannot exist in the scene. " + "Destroying the newest."); GameObject.Destroy(sessionComponent); return; } m_RealArKitSessionHandle = _GetSessionHandleFromArkitPlugin(); SessionComponent = sessionComponent; var status = ExternApi.ArSession_create(m_CloudServicesApiKey, null, ref m_SessionHandle); if (status != ApiArStatus.Success) { Debug.LogErrorFormat( "Could not create a cross platform ARCore session ({0}).", status); return; } NativeSession = new NativeSession(m_SessionHandle, IntPtr.Zero); #else Debug.Log("ARCore iOS Support is not enabled. ARCore will be disabled on iOS device."); return; #endif } public void EnableSession() { m_SessionEnabled = true; SessionStatus = SessionStatus.Tracking; } public void DisableSession() { m_SessionEnabled = false; SessionStatus = SessionStatus.NotTracking; } public void ResetSession() { if (m_SessionHandle != IntPtr.Zero) { if (m_FrameHandle != IntPtr.Zero) { NativeSession.FrameApi.Release(m_FrameHandle); m_FrameHandle = IntPtr.Zero; } ExternApi.ArSession_destroy(m_SessionHandle); m_SessionHandle = IntPtr.Zero; } _Initialize(); } #if ARCORE_IOS_SUPPORT private void _OnARKitFrameUpdated(UnityEngine.XR.iOS.UnityARCamera camera) { if (m_FrameHandle != IntPtr.Zero) { NativeSession.FrameApi.Release(m_FrameHandle); m_FrameHandle = IntPtr.Zero; } if (m_SessionEnabled) { m_FrameHandle = ExternApi.ARCoreARKitIntegration_getCurrentFrame(m_RealArKitSessionHandle); ExternApi.ArSession_updateAndAcquireArFrame( m_SessionHandle, m_FrameHandle, ref m_FrameHandle); } if (NativeSession != null) { NativeSession.OnUpdate(m_FrameHandle); } if (EarlyUpdate != null) { EarlyUpdate(); } } #endif private void _Initialize() { m_SessionEnabled = false; SessionStatus = SessionStatus.NotTracking; LostTrackingReason = LostTrackingReason.None; IsSessionChangedThisFrame = false; } private IntPtr _GetSessionHandleFromArkitPlugin() { IntPtr result = IntPtr.Zero; #if ARCORE_IOS_SUPPORT var m_session = UnityEngine.XR.iOS.UnityARSessionNativeInterface.GetARSessionNativeInterface(); var sessionField = m_session.GetType().GetField( "m_NativeARSession", BindingFlags.NonPublic | BindingFlags.Instance); var val = sessionField.GetValue(m_session); result = ExternApi.ARCoreARKitIntegration_castUnitySessionToARKitSession((System.IntPtr)val); #endif return result; } private struct ExternApi { #if UNITY_IOS [DllImport(ApiConstants.ARCoreARKitIntegrationApi)] public static extern IntPtr ARCoreARKitIntegration_castUnitySessionToARKitSession( IntPtr sessionToCast); [DllImport(ApiConstants.ARCoreARKitIntegrationApi)] public static extern IntPtr ARCoreARKitIntegration_getCurrentFrame( IntPtr arkitSessionHandle); [DllImport(ApiConstants.ARCoreNativeApi)] public static extern ApiArStatus ArSession_create( string apiKey, string bundleIdentifier, ref IntPtr sessionHandle); [DllImport(ApiConstants.ARCoreNativeApi)] public static extern void ArSession_destroy(IntPtr session); [DllImport(ApiConstants.ARCoreNativeApi)] public static extern ApiArStatus ArSession_updateAndAcquireArFrame( IntPtr sessionHandle, IntPtr arkitFrameHandle, ref IntPtr arFrame); #else public static IntPtr ARCoreARKitIntegration_castUnitySessionToARKitSession( IntPtr sessionToCast) { return IntPtr.Zero; } public static IntPtr ARCoreARKitIntegration_getCurrentFrame(IntPtr arkitSessionHandle) { return IntPtr.Zero; } public static ApiArStatus ArSession_create(string apiKey, string bundleIdentifier, ref IntPtr sessionHandle) { return ApiArStatus.Success; } public static void ArSession_destroy(IntPtr session) { } public static ApiArStatus ArSession_updateAndAcquireArFrame(IntPtr sessionHandle, IntPtr arkitFrameHandle, ref IntPtr arFrame) { return ApiArStatus.Success; } #endif } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Data; using System.Data.Common; using System.Dynamic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using System.Text.RegularExpressions; namespace Massive { public static class ObjectExtensions { /// <summary> /// Extension method for adding in a bunch of parameters /// </summary> public static void AddParams(this DbCommand cmd, params object[] args) { foreach (var item in args) { AddParam(cmd, item); } } /// <summary> /// Extension for adding single parameter /// </summary> public static void AddParam(this DbCommand cmd, object item) { var p = cmd.CreateParameter(); p.ParameterName = string.Format("@{0}", cmd.Parameters.Count); if (item == null) { p.Value = DBNull.Value; } else { if (item.GetType() == typeof(Guid)) { p.Value = item.ToString(); p.DbType = DbType.String; p.Size = 4000; } else if (item.GetType() == typeof(ExpandoObject)) { var d = (IDictionary<string, object>)item; p.Value = d.Values.FirstOrDefault(); } else { p.Value = item; } if (item.GetType() == typeof(string)) p.Size = ((string)item).Length > 4000 ? -1 : 4000; } cmd.Parameters.Add(p); } /// <summary> /// Turns an IDataReader to a Dynamic list of things /// </summary> public static List<dynamic> ToExpandoList(this IDataReader rdr) { var result = new List<dynamic>(); while (rdr.Read()) { result.Add(rdr.RecordToExpando()); } return result; } public static dynamic RecordToExpando(this IDataReader rdr) { dynamic e = new ExpandoObject(); var d = e as IDictionary<string, object>; for (int i = 0; i < rdr.FieldCount; i++) d.Add(rdr.GetName(i), DBNull.Value.Equals(rdr[i]) ? null : rdr[i]); return e; } /// <summary> /// Turns the object into an ExpandoObject /// </summary> public static dynamic ToExpando(this object o) { var result = new ExpandoObject(); var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary if (o.GetType() == typeof(ExpandoObject)) return o; //shouldn't have to... but just in case if (o.GetType() == typeof(NameValueCollection) || o.GetType().IsSubclassOf(typeof(NameValueCollection))) { var nv = (NameValueCollection)o; nv.Cast<string>().Select(key => new KeyValuePair<string, object>(key, nv[key])).ToList().ForEach(i => d.Add(i)); } else { var props = o.GetType().GetProperties(); foreach (var item in props) { d.Add(item.Name, item.GetValue(o, null)); } } return result; } /// <summary> /// Turns the object into a Dictionary /// </summary> public static IDictionary<string, object> ToDictionary(this object thingy) { return (IDictionary<string, object>)thingy.ToExpando(); } } /// <summary> /// Convenience class for opening/executing data /// </summary> public static class DB { public static DynamicModel Current { get { if (ConfigurationManager.ConnectionStrings.Count > 1) { return new DynamicModel(ConfigurationManager.ConnectionStrings[1].Name); } throw new InvalidOperationException("Need a connection string name - can't determine what it is"); } } } //-------------Dynamic Model-------------------------------------- /// <summary> /// A class that wraps your database table in Dynamic Funtime /// </summary> public class DynamicModel : DynamicObject { DbProviderFactory _factory; string ConnectionString; public static DynamicModel Open(string connectionStringName) { dynamic dm = new DynamicModel(connectionStringName); return dm; } public DynamicModel(string connectionStringName, string tableName = "", string primaryKeyField = "", string descriptorField = "") { TableName = tableName == "" ? this.GetType().Name : tableName; PrimaryKeyField = string.IsNullOrEmpty(primaryKeyField) ? "ID" : primaryKeyField; //hb var _providerName = "System.Data.SqlClient"; //string _providerName = "System.Data.SqlServerCe.4.0"; _factory = DbProviderFactories.GetFactory(_providerName); ConnectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString; } /// <summary> /// Creates a new Expando from a Form POST - white listed against the columns in the DB /// </summary> public dynamic CreateFrom(NameValueCollection coll) { dynamic result = new ExpandoObject(); var dc = (IDictionary<string, object>)result; var schema = Schema; //loop the collection, setting only what's in the Schema foreach (var item in coll.Keys) { var exists = schema.Any(x => x.COLUMN_NAME.ToLower() == item.ToString().ToLower()); if (exists) { var key = item.ToString(); var val = coll[key]; dc.Add(key, val); } } return result; } /// <summary> /// Gets a default value for the column /// </summary> public dynamic DefaultValue(dynamic column) { dynamic result = null; string def = column.COLUMN_DEFAULT; if (String.IsNullOrEmpty(def)) { result = null; } else if (def == "getdate()" || def == "(getdate())") { result = DateTime.Now.ToShortDateString(); } else if (def == "newid()") { result = Guid.NewGuid().ToString(); } else { result = def.Replace("(", "").Replace(")", ""); } return result; } /// <summary> /// Creates an empty Expando set with defaults from the DB /// </summary> public dynamic Prototype { get { dynamic result = new ExpandoObject(); var schema = Schema; foreach (dynamic column in schema) { var dc = (IDictionary<string, object>)result; dc.Add(column.COLUMN_NAME, DefaultValue(column)); } result._Table = this; return result; } } private string _descriptorField; public string DescriptorField { get { return _descriptorField; } } /// <summary> /// List out all the schema bits for use with ... whatever /// </summary> IEnumerable<dynamic> _schema; public IEnumerable<dynamic> Schema { get { if (_schema == null) _schema = Query("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @0", TableName); return _schema; } } /// <summary> /// Enumerates the reader yielding the result - thanks to Jeroen Haegebaert /// </summary> public virtual IEnumerable<dynamic> Query(string sql, params object[] args) { using (var conn = OpenConnection()) { var rdr = CreateCommand(sql, conn, args).ExecuteReader(); while (rdr.Read()) { yield return rdr.RecordToExpando(); ; } } } public virtual IEnumerable<dynamic> Query(string sql, DbConnection connection, params object[] args) { using (var rdr = CreateCommand(sql, connection, args).ExecuteReader()) { while (rdr.Read()) { yield return rdr.RecordToExpando(); ; } } } /// <summary> /// Returns a single result /// </summary> public virtual object Scalar(string sql, params object[] args) { object result = null; using (var conn = OpenConnection()) { result = CreateCommand(sql, conn, args).ExecuteScalar(); } return result; } /// <summary> /// Creates a DBCommand that you can use for loving your database. /// </summary> DbCommand CreateCommand(string sql, DbConnection conn, params object[] args) { var result = _factory.CreateCommand(); result.Connection = conn; result.CommandText = sql; if (args.Length > 0) result.AddParams(args); return result; } /// <summary> /// Returns and OpenConnection /// </summary> public virtual DbConnection OpenConnection() { var result = _factory.CreateConnection(); result.ConnectionString = ConnectionString; result.Open(); return result; } /// <summary> /// Builds a set of Insert and Update commands based on the passed-on objects. /// These objects can be POCOs, Anonymous, NameValueCollections, or Expandos. Objects /// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs /// </summary> public virtual List<DbCommand> BuildCommands(params object[] things) { var commands = new List<DbCommand>(); foreach (var item in things) { if (HasPrimaryKey(item)) { commands.Add(CreateUpdateCommand(item, GetPrimaryKey(item))); } else { commands.Add(CreateInsertCommand(item)); } } return commands; } public virtual int Execute(DbCommand command) { return Execute(new DbCommand[] { command }); } public virtual int Execute(string sql, params object[] args) { return Execute(CreateCommand(sql, null, args)); } /// <summary> /// Executes a series of DBCommands in a transaction /// </summary> public virtual int Execute(IEnumerable<DbCommand> commands) { var result = 0; using (var conn = OpenConnection()) { using (var tx = conn.BeginTransaction()) { foreach (var cmd in commands) { cmd.Connection = conn; cmd.Transaction = tx; result += cmd.ExecuteNonQuery(); } tx.Commit(); } } return result; } public virtual string PrimaryKeyField { get; set; } /// <summary> /// Conventionally introspects the object passed in for a field that /// looks like a PK. If you've named your PrimaryKeyField, this becomes easy /// </summary> public virtual bool HasPrimaryKey(object o) { return o.ToDictionary().ContainsKey(PrimaryKeyField); } /// <summary> /// If the object passed in has a property with the same name as your PrimaryKeyField /// it is returned here. /// </summary> public virtual object GetPrimaryKey(object o) { object result = null; o.ToDictionary().TryGetValue(PrimaryKeyField, out result); return result; } public virtual string TableName { get; set; } /// <summary> /// Returns all records complying with the passed-in WHERE clause and arguments, /// ordered as specified, limited (TOP) by limit. /// </summary> public virtual IEnumerable<dynamic> All(string where = "", string orderBy = "", int limit = 0, string columns = "*", params object[] args) { string sql = BuildSelect(where, orderBy, limit); return Query(string.Format(sql, columns, TableName), args); } private static string BuildSelect(string where, string orderBy, int limit) { string sql = limit > 0 ? "SELECT TOP " + limit + " {0} FROM {1} " : "SELECT {0} FROM {1} "; if (!string.IsNullOrEmpty(where)) sql += where.Trim().StartsWith("where", StringComparison.OrdinalIgnoreCase) ? where : "WHERE " + where; if (!String.IsNullOrEmpty(orderBy)) sql += orderBy.Trim().StartsWith("order by", StringComparison.OrdinalIgnoreCase) ? orderBy : " ORDER BY " + orderBy; return sql; } /// <summary> /// Returns a dynamic PagedResult. Result properties are Items, TotalPages, and TotalRecords. /// </summary> public virtual dynamic Paged(string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args) { dynamic result = new ExpandoObject(); var countSQL = string.Format("SELECT COUNT({0}) FROM {1}", PrimaryKeyField, TableName); if (String.IsNullOrEmpty(orderBy)) orderBy = PrimaryKeyField; if (!string.IsNullOrEmpty(where)) { if (!where.Trim().StartsWith("where", StringComparison.OrdinalIgnoreCase)) { //where = "WHERE " + where; //hb:11/18/2011-- added a space before WHERE where = " WHERE " + where; } } var sql = string.Format("SELECT {0} FROM (SELECT ROW_NUMBER() OVER (ORDER BY {2}) AS Row, {0} FROM {3} {4}) AS Paged ", columns, pageSize, orderBy, TableName, where); var pageStart = (currentPage - 1) * pageSize; sql += string.Format(" WHERE Row > {0} AND Row <={1}", pageStart, (pageStart + pageSize)); countSQL += where; result.TotalRecords = Scalar(countSQL, args); result.TotalPages = result.TotalRecords / pageSize; if (result.TotalRecords % pageSize > 0) result.TotalPages += 1; result.Items = Query(string.Format(sql, columns, TableName), args); return result; } /// <summary> /// Returns a single row from the database /// </summary> public virtual dynamic Single(string where, params object[] args) { var sql = string.Format("SELECT * FROM {0} WHERE {1}", TableName, where); return Query(sql, args).FirstOrDefault(); } /// <summary> /// Returns a single row from the database /// </summary> public virtual dynamic Single(object key, string columns = "*") { var sql = string.Format("SELECT {0} FROM {1} WHERE {2} = @0", columns, TableName, PrimaryKeyField); return Query(sql, key).FirstOrDefault(); } /// <summary> /// This will return a string/object dictionary for dropdowns etc /// </summary> public virtual IDictionary<string, object> KeyValues(string orderBy = "") { if (String.IsNullOrEmpty(DescriptorField)) throw new InvalidOperationException("There's no DescriptorField set - do this in your constructor to describe the text value you want to see"); var sql = string.Format("SELECT {0},{1} FROM {2} ", PrimaryKeyField, DescriptorField, TableName); if (!String.IsNullOrEmpty(orderBy)) sql += "ORDER BY " + orderBy; return (IDictionary<string, object>)Query(sql); } /// <summary> /// This will return an Expando as a Dictionary /// </summary> public virtual IDictionary<string, object> ItemAsDictionary(ExpandoObject item) { return (IDictionary<string, object>)item; } //Checks to see if a key is present based on the passed-in value public virtual bool ItemContainsKey(string key, ExpandoObject item) { var dc = ItemAsDictionary(item); return dc.ContainsKey(key); } /// <summary> /// Executes a set of objects as Insert or Update commands based on their property settings, within a transaction. /// These objects can be POCOs, Anonymous, NameValueCollections, or Expandos. Objects /// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs /// </summary> public virtual int Save(params object[] things) { foreach (var item in things) { if (!IsValid(item)) { throw new InvalidOperationException("Can't save this item: " + String.Join("; ", Errors.ToArray())); } } var commands = BuildCommands(things); return Execute(commands); } public virtual DbCommand CreateInsertCommand(dynamic expando) { DbCommand result = null; var settings = (IDictionary<string, object>)expando; var sbKeys = new StringBuilder(); var sbVals = new StringBuilder(); var stub = "INSERT INTO {0} ({1}) \r\n VALUES ({2})"; result = CreateCommand(stub, null); int counter = 0; foreach (var item in settings) { sbKeys.AppendFormat("{0},", item.Key); sbVals.AppendFormat("@{0},", counter.ToString()); result.AddParam(item.Value); counter++; } if (counter > 0) { var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 1); var vals = sbVals.ToString().Substring(0, sbVals.Length - 1); var sql = string.Format(stub, TableName, keys, vals); result.CommandText = sql; } else throw new InvalidOperationException("Can't parse this object to the database - there are no properties set"); return result; } /// <summary> /// Creates a command for use with transactions - internal stuff mostly, but here for you to play with /// </summary> public virtual DbCommand CreateUpdateCommand(dynamic expando, object key) { var settings = (IDictionary<string, object>)expando; var sbKeys = new StringBuilder(); var stub = "UPDATE {0} SET {1} WHERE {2} = @{3}"; var args = new List<object>(); var result = CreateCommand(stub, null); int counter = 0; foreach (var item in settings) { var val = item.Value; if (!item.Key.Equals(PrimaryKeyField, StringComparison.OrdinalIgnoreCase) && item.Value != null) { result.AddParam(val); sbKeys.AppendFormat("{0} = @{1}, \r\n", item.Key, counter.ToString()); counter++; } } if (counter > 0) { //add the key result.AddParam(key); //strip the last commas var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 4); result.CommandText = string.Format(stub, TableName, keys, PrimaryKeyField, counter); } else throw new InvalidOperationException("No parsable object was sent in - could not divine any name/value pairs"); return result; } /// <summary> /// Removes one or more records from the DB according to the passed-in WHERE /// </summary> public virtual DbCommand CreateDeleteCommand(string where = "", object key = null, params object[] args) { var sql = string.Format("DELETE FROM {0} ", TableName); if (key != null) { sql += string.Format("WHERE {0}=@0", PrimaryKeyField); args = new object[] { key }; } else if (!string.IsNullOrEmpty(where)) { sql += where.Trim().StartsWith("where", StringComparison.OrdinalIgnoreCase) ? where : "WHERE " + where; } return CreateCommand(sql, null, args); } public bool IsValid(dynamic item) { Errors.Clear(); Validate(item); return Errors.Count == 0; } //Temporary holder for error messages public IList<string> Errors = new List<string>(); /// <summary> /// Adds a record to the database. You can pass in an Anonymous object, an ExpandoObject, /// A regular old POCO, or a NameValueColletion from a Request.Form or Request.QueryString /// </summary> public virtual dynamic Insert(object o) { var ex = o.ToExpando(); if (!IsValid(ex)) { throw new InvalidOperationException("Can't insert: " + String.Join("; ", Errors.ToArray())); } if (BeforeSave(ex)) { using (dynamic conn = OpenConnection()) { var cmd = CreateInsertCommand(ex); cmd.Connection = conn; cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT @@IDENTITY as newID"; ex.ID = cmd.ExecuteScalar(); Inserted(ex); } return ex; } else { return null; } } /// <summary> /// Updates a record in the database. You can pass in an Anonymous object, an ExpandoObject, /// A regular old POCO, or a NameValueCollection from a Request.Form or Request.QueryString /// </summary> public virtual int Update(object o, object key) { var ex = o.ToExpando(); if (!IsValid(ex)) { throw new InvalidOperationException("Can't Update: " + String.Join("; ", Errors.ToArray())); } var result = 0; if (BeforeSave(ex)) { result = Execute(CreateUpdateCommand(ex, key)); Updated(ex); } return result; } /// <summary> /// Removes one or more records from the DB according to the passed-in WHERE /// </summary> public int Delete(object key = null, string where = "", params object[] args) { var deleted = this.Single(key); var result = 0; if (BeforeDelete(deleted)) { result = Execute(CreateDeleteCommand(where: where, key: key, args: args)); Deleted(deleted); } return result; } public void DefaultTo(string key, object value, dynamic item) { if (!ItemContainsKey(key, item)) { var dc = (IDictionary<string, object>)item; dc[key] = value; } } //Hooks public virtual void Validate(dynamic item) { } public virtual void Inserted(dynamic item) { } public virtual void Updated(dynamic item) { } public virtual void Deleted(dynamic item) { } public virtual bool BeforeDelete(dynamic item) { return true; } public virtual bool BeforeSave(dynamic item) { return true; } //validation methods public virtual void ValidatesPresenceOf(object value, string message = "Required") { if (value == null) Errors.Add(message); if (String.IsNullOrEmpty(value.ToString())) Errors.Add(message); } //fun methods public virtual void ValidatesNumericalityOf(object value, string message = "Should be a number") { var type = value.GetType().Name; var numerics = new string[] { "Int32", "Int16", "Int64", "Decimal", "Double", "Single", "Float" }; if (!numerics.Contains(type)) { Errors.Add(message); } } public virtual void ValidateIsCurrency(object value, string message = "Should be money") { if (value == null) Errors.Add(message); decimal val = decimal.MinValue; decimal.TryParse(value.ToString(), out val); if (val == decimal.MinValue) Errors.Add(message); } public int Count() { return Count(TableName); } public int Count(string tableName, string where="") { return (int)Scalar("SELECT COUNT(*) FROM " + tableName); } /// <summary> /// A helpful query tool /// </summary> public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { //parse the method var constraints = new List<string>(); var counter = 0; var info = binder.CallInfo; // accepting named args only... SKEET! if (info.ArgumentNames.Count != args.Length) { throw new InvalidOperationException("Please use named arguments for this type of query - the column name, orderby, columns, etc"); } //first should be "FindBy, Last, Single, First" var op = binder.Name; var columns = " * "; string orderBy = string.Format(" ORDER BY {0}", PrimaryKeyField); string sql = ""; string where = ""; var whereArgs = new List<object>(); //loop the named args - see if we have order, columns and constraints if (info.ArgumentNames.Count > 0) { for (int i = 0; i < args.Length; i++) { var name = info.ArgumentNames[i].ToLower(); switch (name) { case "orderby": orderBy = " ORDER BY " + args[i]; break; case "columns": columns = args[i].ToString(); break; default: constraints.Add(string.Format(" {0} = @{1}", name, counter)); whereArgs.Add(args[i]); counter++; break; } } } //Build the WHERE bits if (constraints.Count > 0) { where = " WHERE " + string.Join(" AND ", constraints.ToArray()); } //probably a bit much here but... yeah this whole thing needs to be refactored... if (op.ToLower() == "count") { result = Scalar("SELECT COUNT(*) FROM " + TableName + where, whereArgs.ToArray()); } else if (op.ToLower() == "sum") { result = Scalar("SELECT SUM(" + columns + ") FROM " + TableName + where, whereArgs.ToArray()); } else if (op.ToLower() == "max") { result = Scalar("SELECT MAX(" + columns + ") FROM " + TableName + where, whereArgs.ToArray()); } else if (op.ToLower() == "min") { result = Scalar("SELECT MIN(" + columns + ") FROM " + TableName + where, whereArgs.ToArray()); } else if (op.ToLower() == "avg") { result = Scalar("SELECT AVG(" + columns + ") FROM " + TableName + where, whereArgs.ToArray()); } else { //build the SQL sql = "SELECT TOP 1 " + columns + " FROM " + TableName + where; var justOne = op.StartsWith("First") || op.StartsWith("Last") || op.StartsWith("Get") || op.StartsWith("Single"); //Be sure to sort by DESC on the PK (PK Sort is the default) if (op.StartsWith("Last")) { orderBy = orderBy + " DESC "; } else { //default to multiple sql = "SELECT " + columns + " FROM " + TableName + where; } if (justOne) { //return a single record result = Query(sql + orderBy, whereArgs.ToArray()).FirstOrDefault(); } else { //return lots result = Query(sql + orderBy, whereArgs.ToArray()); } } return true; } } }
// 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 Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal enum CorElementType { ELEMENT_TYPE_U1, ELEMENT_TYPE_I2, ELEMENT_TYPE_I4, ELEMENT_TYPE_I8, ELEMENT_TYPE_R4, ELEMENT_TYPE_R8, ELEMENT_TYPE_CHAR, ELEMENT_TYPE_BOOLEAN, ELEMENT_TYPE_I1, ELEMENT_TYPE_U2, ELEMENT_TYPE_U4, ELEMENT_TYPE_U8, ELEMENT_TYPE_I, ELEMENT_TYPE_U, ELEMENT_TYPE_OBJECT, ELEMENT_TYPE_STRING, ELEMENT_TYPE_TYPEDBYREF, ELEMENT_TYPE_CLASS, ELEMENT_TYPE_VALUETYPE, ELEMENT_TYPE_END } internal class PredefinedTypes { private SymbolTable _runtimeBinderSymbolTable; private BSYMMGR _pBSymmgr; private AggregateSymbol[] _predefSyms; // array of predefined symbol types. private KAID _aidMsCorLib; // The assembly ID for all predefined types. public PredefinedTypes(BSYMMGR pBSymmgr) { _pBSymmgr = pBSymmgr; _aidMsCorLib = KAID.kaidNil; _runtimeBinderSymbolTable = null; } // We want to delay load the predef syms as needed. private AggregateSymbol DelayLoadPredefSym(PredefinedType pt) { CType type = _runtimeBinderSymbolTable.GetCTypeFromType(PredefinedTypeFacts.GetAssociatedSystemType(pt)); AggregateSymbol sym = type.getAggregate(); // If we failed to load this thing, we have problems. if (sym == null) { return null; } return PredefinedTypes.InitializePredefinedType(sym, pt); } internal static AggregateSymbol InitializePredefinedType(AggregateSymbol sym, PredefinedType pt) { sym.SetPredefined(true); sym.SetPredefType(pt); sym.SetSkipUDOps(pt <= PredefinedType.PT_ENUM && pt != PredefinedType.PT_INTPTR && pt != PredefinedType.PT_UINTPTR && pt != PredefinedType.PT_TYPE); return sym; } public bool Init(ErrorHandling errorContext, SymbolTable symtable) { _runtimeBinderSymbolTable = symtable; Debug.Assert(_pBSymmgr != null); #if !CSEE Debug.Assert(_predefSyms == null); #else // CSEE Debug.Assert(predefSyms == null || aidMsCorLib != KAID.kaidNil); #endif // CSEE if (_aidMsCorLib == KAID.kaidNil) { // If we haven't found mscorlib yet, first look for System.Object. Then use its assembly as // the location for all other pre-defined types. AggregateSymbol aggObj = FindPredefinedType(errorContext, PredefinedTypeFacts.GetName(PredefinedType.PT_OBJECT), KAID.kaidGlobal, AggKindEnum.Class, 0, true); if (aggObj == null) return false; _aidMsCorLib = aggObj.GetAssemblyID(); } _predefSyms = new AggregateSymbol[(int)PredefinedType.PT_COUNT]; Debug.Assert(_predefSyms != null); return true; } //////////////////////////////////////////////////////////////////////////////// // finds an existing declaration for a predefined type. // returns null on failure. If isRequired is true, an error message is also // given. private static readonly char[] s_nameSeparators = new char[] { '.' }; private AggregateSymbol FindPredefinedType(ErrorHandling errorContext, string pszType, KAID aid, AggKindEnum aggKind, int arity, bool isRequired) { Debug.Assert(!string.IsNullOrEmpty(pszType)); // Shouldn't be the empty string! NamespaceOrAggregateSymbol bagCur = _pBSymmgr.GetRootNS(); Name name = null; string[] nameParts = pszType.Split(s_nameSeparators); for (int i = 0, n = nameParts.Length; i < n; i++) { name = _pBSymmgr.GetNameManager().Add(nameParts[i]); if (i == n - 1) { // This is the last component. Handle it special below. break; } // first search for an outer type which is also predefined // this must be first because we always create a namespace for // outer names, even for nested types AggregateSymbol aggNext = _pBSymmgr.LookupGlobalSymCore(name, bagCur, symbmask_t.MASK_AggregateSymbol).AsAggregateSymbol(); if (aggNext != null && aggNext.InAlias(aid) && aggNext.IsPredefined()) { bagCur = aggNext; } else { // ... if no outer type, then search for namespaces NamespaceSymbol nsNext = _pBSymmgr.LookupGlobalSymCore(name, bagCur, symbmask_t.MASK_NamespaceSymbol).AsNamespaceSymbol(); bool bIsInAlias = true; if (nsNext == null) { bIsInAlias = false; } else { bIsInAlias = nsNext.InAlias(aid); } if (!bIsInAlias) { // Didn't find the namespace in this aid. if (isRequired) { errorContext.Error(ErrorCode.ERR_PredefinedTypeNotFound, pszType); } return null; } bagCur = nsNext; } } AggregateSymbol aggAmbig; AggregateSymbol aggBad; AggregateSymbol aggFound = FindPredefinedTypeCore(name, bagCur, aid, aggKind, arity, out aggAmbig, out aggBad); if (aggFound == null) { // Didn't find the AggregateSymbol. if (aggBad != null && (isRequired || aid == KAID.kaidGlobal && aggBad.IsSource())) errorContext.ErrorRef(ErrorCode.ERR_PredefinedTypeBadType, aggBad); else if (isRequired) errorContext.Error(ErrorCode.ERR_PredefinedTypeNotFound, pszType); return null; } if (aggAmbig == null && aid != KAID.kaidGlobal) { // Look in kaidGlobal to make sure there isn't a conflicting one. AggregateSymbol tmp; AggregateSymbol agg2 = FindPredefinedTypeCore(name, bagCur, KAID.kaidGlobal, aggKind, arity, out aggAmbig, out tmp); Debug.Assert(agg2 != null); if (agg2 != aggFound) aggAmbig = agg2; } return aggFound; } private AggregateSymbol FindPredefinedTypeCore(Name name, NamespaceOrAggregateSymbol bag, KAID aid, AggKindEnum aggKind, int arity, out AggregateSymbol paggAmbig, out AggregateSymbol paggBad) { AggregateSymbol aggFound = null; paggAmbig = null; paggBad = null; for (AggregateSymbol aggCur = _pBSymmgr.LookupGlobalSymCore(name, bag, symbmask_t.MASK_AggregateSymbol).AsAggregateSymbol(); aggCur != null; aggCur = BSYMMGR.LookupNextSym(aggCur, bag, symbmask_t.MASK_AggregateSymbol).AsAggregateSymbol()) { if (!aggCur.InAlias(aid) || aggCur.GetTypeVarsAll().size != arity) { continue; } if (aggCur.AggKind() != aggKind) { if (paggBad == null) { paggBad = aggCur; } continue; } if (aggFound != null) { Debug.Assert(paggAmbig == null); paggAmbig = aggCur; break; } aggFound = aggCur; if (paggAmbig == null) { break; } } return aggFound; } public void ReportMissingPredefTypeError(ErrorHandling errorContext, PredefinedType pt) { Debug.Assert(_pBSymmgr != null); Debug.Assert(_predefSyms != null); Debug.Assert((PredefinedType)0 <= pt && pt < PredefinedType.PT_COUNT && _predefSyms[(int)pt] == null); // We do not assert that !predefTypeInfo[pt].isRequired because if the user is defining // their own MSCorLib and is defining a required PredefType, they'll run into this error // and we need to allow it to go through. errorContext.Error(ErrorCode.ERR_PredefinedTypeNotFound, PredefinedTypeFacts.GetName(pt)); } public AggregateSymbol GetReqPredefAgg(PredefinedType pt) { if (!PredefinedTypeFacts.IsRequired(pt)) throw Error.InternalCompilerError(); if (_predefSyms[(int)pt] == null) { // Delay load this thing. _predefSyms[(int)pt] = DelayLoadPredefSym(pt); } return _predefSyms[(int)pt]; } public AggregateSymbol GetOptPredefAgg(PredefinedType pt) { if (_predefSyms[(int)pt] == null) { // Delay load this thing. _predefSyms[(int)pt] = DelayLoadPredefSym(pt); } Debug.Assert(_predefSyms != null); return _predefSyms[(int)pt]; } //////////////////////////////////////////////////////////////////////////////// // Some of the predefined types have built-in names, like "int" or "string" or // "object". This return the nice name if one exists; otherwise null is // returned. public static string GetNiceName(PredefinedType pt) { return PredefinedTypeFacts.GetNiceName(pt); } public static string GetNiceName(AggregateSymbol type) { if (type.IsPredefined()) return GetNiceName(type.GetPredefType()); else return null; } public static string GetFullName(PredefinedType pt) { return PredefinedTypeFacts.GetName(pt); } public static bool isRequired(PredefinedType pt) { return PredefinedTypeFacts.IsRequired(pt); } } internal static class PredefinedTypeFacts { internal static string GetName(PredefinedType type) { return s_pdTypes[(int)type].name; } internal static bool IsRequired(PredefinedType type) { return s_pdTypes[(int)type].required; } internal static FUNDTYPE GetFundType(PredefinedType type) { return s_pdTypes[(int)type].fundType; } internal static Type GetAssociatedSystemType(PredefinedType type) { return s_pdTypes[(int)type].AssociatedSystemType; } internal static bool IsSimpleType(PredefinedType type) { switch (type) { case PredefinedType.PT_BYTE: case PredefinedType.PT_SHORT: case PredefinedType.PT_INT: case PredefinedType.PT_LONG: case PredefinedType.PT_FLOAT: case PredefinedType.PT_DOUBLE: case PredefinedType.PT_DECIMAL: case PredefinedType.PT_CHAR: case PredefinedType.PT_BOOL: case PredefinedType.PT_SBYTE: case PredefinedType.PT_USHORT: case PredefinedType.PT_UINT: case PredefinedType.PT_ULONG: return true; default: return false; } } internal static bool IsNumericType(PredefinedType type) { switch (type) { case PredefinedType.PT_BYTE: case PredefinedType.PT_SHORT: case PredefinedType.PT_INT: case PredefinedType.PT_LONG: case PredefinedType.PT_FLOAT: case PredefinedType.PT_DOUBLE: case PredefinedType.PT_DECIMAL: case PredefinedType.PT_SBYTE: case PredefinedType.PT_USHORT: case PredefinedType.PT_UINT: case PredefinedType.PT_ULONG: return true; default: return false; } } internal static string GetNiceName(PredefinedType type) { switch (type) { case PredefinedType.PT_BYTE: return "byte"; case PredefinedType.PT_SHORT: return "short"; case PredefinedType.PT_INT: return "int"; case PredefinedType.PT_LONG: return "long"; case PredefinedType.PT_FLOAT: return "float"; case PredefinedType.PT_DOUBLE: return "double"; case PredefinedType.PT_DECIMAL: return "decimal"; case PredefinedType.PT_CHAR: return "char"; case PredefinedType.PT_BOOL: return "bool"; case PredefinedType.PT_SBYTE: return "sbyte"; case PredefinedType.PT_USHORT: return "ushort"; case PredefinedType.PT_UINT: return "uint"; case PredefinedType.PT_ULONG: return "ulong"; case PredefinedType.PT_OBJECT: return "object"; case PredefinedType.PT_STRING: return "string"; default: return null; } } internal static bool IsPredefinedType(string name) { return s_pdTypeNames.ContainsKey(name); } internal static PredefinedType GetPredefTypeIndex(string name) { return s_pdTypeNames[name]; } private class PredefinedTypeInfo { internal PredefinedType type; internal string name; internal bool required; internal FUNDTYPE fundType; internal Type AssociatedSystemType; internal PredefinedTypeInfo(PredefinedType type, Type associatedSystemType, string name, bool required, int arity, AggKindEnum aggKind, FUNDTYPE fundType, bool inMscorlib) { this.type = type; this.name = name; this.required = required; this.fundType = fundType; this.AssociatedSystemType = associatedSystemType; } internal PredefinedTypeInfo(PredefinedType type, Type associatedSystemType, string name, bool required, int arity, bool inMscorlib) : this(type, associatedSystemType, name, required, arity, AggKindEnum.Class, FUNDTYPE.FT_REF, inMscorlib) { } } static PredefinedTypeFacts() { #if DEBUG for (int i = 0; i < (int)PredefinedType.PT_COUNT; i++) { System.Diagnostics.Debug.Assert(s_pdTypes[i].type == (PredefinedType)i); } #endif for (int i = 0; i < (int)PredefinedType.PT_COUNT; i++) { s_pdTypeNames.Add(s_pdTypes[i].name, (PredefinedType)i); } } private static readonly Dictionary<string, PredefinedType> s_pdTypeNames = new Dictionary<string, PredefinedType>(); private static readonly PredefinedTypeInfo[] s_pdTypes = new PredefinedTypeInfo[] { new PredefinedTypeInfo(PredefinedType.PT_BYTE, typeof(System.Byte), "System.Byte", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_U1, true), new PredefinedTypeInfo(PredefinedType.PT_SHORT, typeof(System.Int16), "System.Int16", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_I2, true), new PredefinedTypeInfo(PredefinedType.PT_INT, typeof(System.Int32), "System.Int32", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_I4, true), new PredefinedTypeInfo(PredefinedType.PT_LONG, typeof(System.Int64), "System.Int64", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_I8, true), new PredefinedTypeInfo(PredefinedType.PT_FLOAT, typeof(System.Single), "System.Single", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_R4, true), new PredefinedTypeInfo(PredefinedType.PT_DOUBLE, typeof(System.Double), "System.Double", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_R8, true), new PredefinedTypeInfo(PredefinedType.PT_DECIMAL, typeof(System.Decimal), "System.Decimal", false, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_CHAR, typeof(System.Char), "System.Char", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_U2, true), new PredefinedTypeInfo(PredefinedType.PT_BOOL, typeof(System.Boolean), "System.Boolean", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_I1, true), new PredefinedTypeInfo(PredefinedType.PT_SBYTE, typeof(System.SByte), "System.SByte", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_I1, true), new PredefinedTypeInfo(PredefinedType.PT_USHORT, typeof(System.UInt16), "System.UInt16", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_U2, true), new PredefinedTypeInfo(PredefinedType.PT_UINT, typeof(System.UInt32), "System.UInt32", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_U4, true), new PredefinedTypeInfo(PredefinedType.PT_ULONG, typeof(System.UInt64), "System.UInt64", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_U8, true), new PredefinedTypeInfo(PredefinedType.PT_INTPTR, typeof(System.IntPtr), "System.IntPtr", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_UINTPTR, typeof(System.UIntPtr), "System.UIntPtr", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_OBJECT, typeof(System.Object), "System.Object", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_STRING, typeof(System.String), "System.String", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DELEGATE, typeof(System.Delegate), "System.Delegate", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_MULTIDEL, typeof(System.MulticastDelegate), "System.MulticastDelegate", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_ARRAY, typeof(System.Array), "System.Array", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_EXCEPTION, typeof(System.Exception), "System.Exception", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_TYPE, typeof(System.Type), "System.Type", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_MONITOR, typeof(System.Threading.Monitor), "System.Threading.Monitor", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_VALUE, typeof(System.ValueType), "System.ValueType", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_ENUM, typeof(System.Enum), "System.Enum", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DATETIME, typeof(System.DateTime), "System.DateTime", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_DEBUGGABLEATTRIBUTE, typeof(System.Diagnostics.DebuggableAttribute), "System.Diagnostics.DebuggableAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DEBUGGABLEATTRIBUTE_DEBUGGINGMODES, typeof(System.Diagnostics.DebuggableAttribute.DebuggingModes), "System.Diagnostics.DebuggableAttribute.DebuggingModes", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_IN, typeof(System.Runtime.InteropServices.InAttribute), "System.Runtime.InteropServices.InAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_OUT, typeof(System.Runtime.InteropServices.OutAttribute), "System.Runtime.InteropServices.OutAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_ATTRIBUTE, typeof(System.Attribute), "System.Attribute", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_ATTRIBUTEUSAGE, typeof(System.AttributeUsageAttribute), "System.AttributeUsageAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_ATTRIBUTETARGETS, typeof(System.AttributeTargets), "System.AttributeTargets", false, 0, AggKindEnum.Enum, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_OBSOLETE, typeof(System.ObsoleteAttribute), "System.ObsoleteAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_CONDITIONAL, typeof(System.Diagnostics.ConditionalAttribute), "System.Diagnostics.ConditionalAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_CLSCOMPLIANT, typeof(System.CLSCompliantAttribute), "System.CLSCompliantAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_GUID, typeof(System.Runtime.InteropServices.GuidAttribute), "System.Runtime.InteropServices.GuidAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DEFAULTMEMBER, typeof(System.Reflection.DefaultMemberAttribute), "System.Reflection.DefaultMemberAttribute", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_PARAMS, typeof(System.ParamArrayAttribute), "System.ParamArrayAttribute", true, 0, true), new PredefinedTypeInfo(PredefinedType.PT_COMIMPORT, typeof(System.Runtime.InteropServices.ComImportAttribute), "System.Runtime.InteropServices.ComImportAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_FIELDOFFSET, typeof(System.Runtime.InteropServices.FieldOffsetAttribute), "System.Runtime.InteropServices.FieldOffsetAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_STRUCTLAYOUT, typeof(System.Runtime.InteropServices.StructLayoutAttribute), "System.Runtime.InteropServices.StructLayoutAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_LAYOUTKIND, typeof(System.Runtime.InteropServices.LayoutKind), "System.Runtime.InteropServices.LayoutKind", false, 0, AggKindEnum.Enum, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_MARSHALAS, typeof(System.Runtime.InteropServices.MarshalAsAttribute), "System.Runtime.InteropServices.MarshalAsAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DLLIMPORT, typeof(System.Runtime.InteropServices.DllImportAttribute), "System.Runtime.InteropServices.DllImportAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_INDEXERNAME, typeof(System.Runtime.CompilerServices.IndexerNameAttribute), "System.Runtime.CompilerServices.IndexerNameAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DECIMALCONSTANT, typeof(System.Runtime.CompilerServices.DecimalConstantAttribute), "System.Runtime.CompilerServices.DecimalConstantAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DEFAULTVALUE, typeof(System.Runtime.InteropServices.DefaultParameterValueAttribute), "System.Runtime.InteropServices.DefaultParameterValueAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_UNMANAGEDFUNCTIONPOINTER, typeof(System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute), "System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_CALLINGCONVENTION, typeof(System.Runtime.InteropServices.CallingConvention), "System.Runtime.InteropServices.CallingConvention", false, 0, AggKindEnum.Enum, FUNDTYPE.FT_I4, true), new PredefinedTypeInfo(PredefinedType.PT_CHARSET, typeof(System.Runtime.InteropServices.CharSet), "System.Runtime.InteropServices.CharSet", false, 0, AggKindEnum.Enum, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_TYPEHANDLE, typeof(System.RuntimeTypeHandle), "System.RuntimeTypeHandle", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_FIELDHANDLE, typeof(System.RuntimeFieldHandle), "System.RuntimeFieldHandle", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_METHODHANDLE, typeof(System.RuntimeMethodHandle), "System.RuntimeMethodHandle", false, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_G_DICTIONARY, typeof(System.Collections.Generic.Dictionary<,>), "System.Collections.Generic.Dictionary`2", false, 2, true), new PredefinedTypeInfo(PredefinedType.PT_IASYNCRESULT, typeof(System.IAsyncResult), "System.IAsyncResult", false, 0, AggKindEnum.Interface, FUNDTYPE.FT_REF, true), new PredefinedTypeInfo(PredefinedType.PT_ASYNCCBDEL, typeof(System.AsyncCallback), "System.AsyncCallback", false, 0, AggKindEnum.Delegate, FUNDTYPE.FT_REF, true), new PredefinedTypeInfo(PredefinedType.PT_IDISPOSABLE, typeof(System.IDisposable), "System.IDisposable", true, 0, AggKindEnum.Interface, FUNDTYPE.FT_REF, true), new PredefinedTypeInfo(PredefinedType.PT_IENUMERABLE, typeof(System.Collections.IEnumerable), "System.Collections.IEnumerable", true, 0, AggKindEnum.Interface, FUNDTYPE.FT_REF, true), new PredefinedTypeInfo(PredefinedType.PT_IENUMERATOR, typeof(System.Collections.IEnumerator), "System.Collections.IEnumerator", true, 0, AggKindEnum.Interface, FUNDTYPE.FT_REF, true), new PredefinedTypeInfo(PredefinedType.PT_SYSTEMVOID, typeof(void), "System.Void", true, 0, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_RUNTIMEHELPERS, typeof(System.Runtime.CompilerServices.RuntimeHelpers), "System.Runtime.CompilerServices.RuntimeHelpers", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_VOLATILEMOD, typeof(System.Runtime.CompilerServices.IsVolatile), "System.Runtime.CompilerServices.IsVolatile", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_COCLASS, typeof(System.Runtime.InteropServices.CoClassAttribute), "System.Runtime.InteropServices.CoClassAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_ACTIVATOR, typeof(System.Activator), "System.Activator", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_G_IENUMERABLE, typeof(System.Collections.Generic.IEnumerable<>), "System.Collections.Generic.IEnumerable`1", false, 1, AggKindEnum.Interface, FUNDTYPE.FT_REF, true), new PredefinedTypeInfo(PredefinedType.PT_G_IENUMERATOR, typeof(System.Collections.Generic.IEnumerator<>), "System.Collections.Generic.IEnumerator`1", false, 1, AggKindEnum.Interface, FUNDTYPE.FT_REF, true), new PredefinedTypeInfo(PredefinedType.PT_G_OPTIONAL, typeof(System.Nullable<>), "System.Nullable`1", false, 1, AggKindEnum.Struct, FUNDTYPE.FT_STRUCT, true), new PredefinedTypeInfo(PredefinedType.PT_FIXEDBUFFER, typeof(System.Runtime.CompilerServices.FixedBufferAttribute), "System.Runtime.CompilerServices.FixedBufferAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DEFAULTCHARSET, typeof(System.Runtime.InteropServices.DefaultCharSetAttribute), "System.Runtime.InteropServices.DefaultCharSetAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_COMPILATIONRELAXATIONS, typeof(System.Runtime.CompilerServices.CompilationRelaxationsAttribute), "System.Runtime.CompilerServices.CompilationRelaxationsAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_RUNTIMECOMPATIBILITY, typeof(System.Runtime.CompilerServices.RuntimeCompatibilityAttribute), "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_FRIENDASSEMBLY, typeof(System.Runtime.CompilerServices.InternalsVisibleToAttribute), "System.Runtime.CompilerServices.InternalsVisibleToAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DEBUGGERHIDDEN, typeof(System.Diagnostics.DebuggerHiddenAttribute), "System.Diagnostics.DebuggerHiddenAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_TYPEFORWARDER, typeof(System.Runtime.CompilerServices.TypeForwardedToAttribute), "System.Runtime.CompilerServices.TypeForwardedToAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_KEYFILE, typeof(System.Reflection.AssemblyKeyFileAttribute), "System.Reflection.AssemblyKeyFileAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_KEYNAME, typeof(System.Reflection.AssemblyKeyNameAttribute), "System.Reflection.AssemblyKeyNameAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DELAYSIGN, typeof(System.Reflection.AssemblyDelaySignAttribute), "System.Reflection.AssemblyDelaySignAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_NOTSUPPORTEDEXCEPTION, typeof(System.NotSupportedException), "System.NotSupportedException", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_COMPILERGENERATED, typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), "System.Runtime.CompilerServices.CompilerGeneratedAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_UNSAFEVALUETYPE, typeof(System.Runtime.CompilerServices.UnsafeValueTypeAttribute), "System.Runtime.CompilerServices.UnsafeValueTypeAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_ASSEMBLYFLAGS, typeof(System.Reflection.AssemblyFlagsAttribute), "System.Reflection.AssemblyFlagsAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_ASSEMBLYVERSION, typeof(System.Reflection.AssemblyVersionAttribute), "System.Reflection.AssemblyVersionAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_ASSEMBLYCULTURE, typeof(System.Reflection.AssemblyCultureAttribute), "System.Reflection.AssemblyCultureAttribute", false, 0, true), // LINQ new PredefinedTypeInfo(PredefinedType.PT_G_IQUERYABLE, typeof(System.Linq.IQueryable<>), "System.Linq.IQueryable`1", false, 1, AggKindEnum.Interface, FUNDTYPE.FT_REF, false), new PredefinedTypeInfo(PredefinedType.PT_IQUERYABLE, typeof(System.Linq.IQueryable), "System.Linq.IQueryable", false, 0, AggKindEnum.Interface, FUNDTYPE.FT_REF, false), new PredefinedTypeInfo(PredefinedType.PT_STRINGBUILDER, typeof(System.Text.StringBuilder), "System.Text.StringBuilder", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_G_ICOLLECTION, typeof(System.Collections.Generic.ICollection<>), "System.Collections.Generic.ICollection`1", false, 1, AggKindEnum.Interface, FUNDTYPE.FT_REF, true), new PredefinedTypeInfo(PredefinedType.PT_G_ILIST, typeof(System.Collections.Generic.IList<>), "System.Collections.Generic.IList`1", false, 1, AggKindEnum.Interface, FUNDTYPE.FT_REF, true), new PredefinedTypeInfo(PredefinedType.PT_EXTENSION, typeof(System.Runtime.CompilerServices.ExtensionAttribute), "System.Runtime.CompilerServices.ExtensionAttribute", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_G_EXPRESSION, typeof(System.Linq.Expressions.Expression<>), "System.Linq.Expressions.Expression`1", false, 1, false), new PredefinedTypeInfo(PredefinedType.PT_EXPRESSION, typeof(System.Linq.Expressions.Expression), "System.Linq.Expressions.Expression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_LAMBDAEXPRESSION, typeof(System.Linq.Expressions.LambdaExpression), "System.Linq.Expressions.LambdaExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_BINARYEXPRESSION, typeof(System.Linq.Expressions.BinaryExpression), "System.Linq.Expressions.BinaryExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_UNARYEXPRESSION, typeof(System.Linq.Expressions.UnaryExpression), "System.Linq.Expressions.UnaryExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_CONDITIONALEXPRESSION, typeof(System.Linq.Expressions.ConditionalExpression), "System.Linq.Expressions.ConditionalExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_CONSTANTEXPRESSION, typeof(System.Linq.Expressions.ConstantExpression), "System.Linq.Expressions.ConstantExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_PARAMETEREXPRESSION, typeof(System.Linq.Expressions.ParameterExpression), "System.Linq.Expressions.ParameterExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_MEMBEREXPRESSION, typeof(System.Linq.Expressions.MemberExpression), "System.Linq.Expressions.MemberExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_METHODCALLEXPRESSION, typeof(System.Linq.Expressions.MethodCallExpression), "System.Linq.Expressions.MethodCallExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_NEWEXPRESSION, typeof(System.Linq.Expressions.NewExpression), "System.Linq.Expressions.NewExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_BINDING, typeof(System.Linq.Expressions.MemberBinding), "System.Linq.Expressions.MemberBinding", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_MEMBERINITEXPRESSION, typeof(System.Linq.Expressions.MemberInitExpression), "System.Linq.Expressions.MemberInitExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_LISTINITEXPRESSION, typeof(System.Linq.Expressions.ListInitExpression), "System.Linq.Expressions.ListInitExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_TYPEBINARYEXPRESSION, typeof(System.Linq.Expressions.TypeBinaryExpression), "System.Linq.Expressions.TypeBinaryExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_NEWARRAYEXPRESSION, typeof(System.Linq.Expressions.NewArrayExpression), "System.Linq.Expressions.NewArrayExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_MEMBERASSIGNMENT, typeof(System.Linq.Expressions.MemberAssignment), "System.Linq.Expressions.MemberAssignment", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_MEMBERLISTBINDING, typeof(System.Linq.Expressions.MemberListBinding), "System.Linq.Expressions.MemberListBinding", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_MEMBERMEMBERBINDING, typeof(System.Linq.Expressions.MemberMemberBinding), "System.Linq.Expressions.MemberMemberBinding", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_INVOCATIONEXPRESSION, typeof(System.Linq.Expressions.InvocationExpression), "System.Linq.Expressions.InvocationExpression", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_FIELDINFO, typeof(System.Reflection.FieldInfo), "System.Reflection.FieldInfo", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_METHODINFO, typeof(System.Reflection.MethodInfo), "System.Reflection.MethodInfo", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_CONSTRUCTORINFO, typeof(System.Reflection.ConstructorInfo), "System.Reflection.ConstructorInfo", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_PROPERTYINFO, typeof(System.Reflection.PropertyInfo), "System.Reflection.PropertyInfo", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_METHODBASE, typeof(System.Reflection.MethodBase), "System.Reflection.MethodBase", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_MEMBERINFO, typeof(System.Reflection.MemberInfo), "System.Reflection.MemberInfo", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DEBUGGERDISPLAY, typeof(System.Diagnostics.DebuggerDisplayAttribute), "System.Diagnostics.DebuggerDisplayAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DEBUGGERBROWSABLE, typeof(System.Diagnostics.DebuggerBrowsableAttribute), "System.Diagnostics.DebuggerBrowsableAttribute", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_DEBUGGERBROWSABLESTATE, typeof(System.Diagnostics.DebuggerBrowsableState), "System.Diagnostics.DebuggerBrowsableState", false, 0, AggKindEnum.Enum, FUNDTYPE.FT_I4, true), new PredefinedTypeInfo(PredefinedType.PT_G_EQUALITYCOMPARER, typeof(System.Collections.Generic.EqualityComparer<>), "System.Collections.Generic.EqualityComparer`1", false, 1, true), new PredefinedTypeInfo(PredefinedType.PT_ELEMENTINITIALIZER, typeof(System.Linq.Expressions.ElementInit), "System.Linq.Expressions.ElementInit", false, 0, false), new PredefinedTypeInfo(PredefinedType.PT_MISSING, typeof(System.Reflection.Missing), "System.Reflection.Missing", false, 0, true), new PredefinedTypeInfo(PredefinedType.PT_G_IREADONLYLIST, typeof(System.Collections.Generic.IReadOnlyList<>), "System.Collections.Generic.IReadOnlyList`1", false, 1, AggKindEnum.Interface, FUNDTYPE.FT_REF, false), new PredefinedTypeInfo(PredefinedType.PT_G_IREADONLYCOLLECTION, typeof(System.Collections.Generic.IReadOnlyCollection<>), "System.Collections.Generic.IReadOnlyCollection`1", false, 1, AggKindEnum.Interface, FUNDTYPE.FT_REF, false), }; } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Year 9-12 Exit Categories Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class KGGDataSet : EduHubDataSet<KGG> { /// <inheritdoc /> public override string Name { get { return "KGG"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return false; } } internal KGGDataSet(EduHubContext Context) : base(Context) { Index_KGGKEY = new Lazy<Dictionary<string, KGG>>(() => this.ToDictionary(i => i.KGGKEY)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="KGG" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="KGG" /> fields for each CSV column header</returns> internal override Action<KGG, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<KGG, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "KGGKEY": mapper[i] = (e, v) => e.KGGKEY = v; break; case "DESCRIPTION": mapper[i] = (e, v) => e.DESCRIPTION = v; break; case "EDFLAG_ORDER": mapper[i] = (e, v) => e.EDFLAG_ORDER = v; break; case "OPEN_CLOSED": mapper[i] = (e, v) => e.OPEN_CLOSED = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="KGG" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="KGG" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="KGG" /> entities</param> /// <returns>A merged <see cref="IEnumerable{KGG}"/> of entities</returns> internal override IEnumerable<KGG> ApplyDeltaEntities(IEnumerable<KGG> Entities, List<KGG> DeltaEntities) { HashSet<string> Index_KGGKEY = new HashSet<string>(DeltaEntities.Select(i => i.KGGKEY)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.KGGKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_KGGKEY.Remove(entity.KGGKEY); if (entity.KGGKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<string, KGG>> Index_KGGKEY; #endregion #region Index Methods /// <summary> /// Find KGG by KGGKEY field /// </summary> /// <param name="KGGKEY">KGGKEY value used to find KGG</param> /// <returns>Related KGG entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KGG FindByKGGKEY(string KGGKEY) { return Index_KGGKEY.Value[KGGKEY]; } /// <summary> /// Attempt to find KGG by KGGKEY field /// </summary> /// <param name="KGGKEY">KGGKEY value used to find KGG</param> /// <param name="Value">Related KGG entity</param> /// <returns>True if the related KGG entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByKGGKEY(string KGGKEY, out KGG Value) { return Index_KGGKEY.Value.TryGetValue(KGGKEY, out Value); } /// <summary> /// Attempt to find KGG by KGGKEY field /// </summary> /// <param name="KGGKEY">KGGKEY value used to find KGG</param> /// <returns>Related KGG entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KGG TryFindByKGGKEY(string KGGKEY) { KGG value; if (Index_KGGKEY.Value.TryGetValue(KGGKEY, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a KGG table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KGG]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[KGG]( [KGGKEY] varchar(2) NOT NULL, [DESCRIPTION] varchar(50) NULL, [EDFLAG_ORDER] varchar(2) NULL, [OPEN_CLOSED] varchar(1) NULL, CONSTRAINT [KGG_Index_KGGKEY] PRIMARY KEY CLUSTERED ( [KGGKEY] ASC ) ); END"); } /// <summary> /// Returns null as <see cref="KGGDataSet"/> has no non-clustered indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>null</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return null; } /// <summary> /// Returns null as <see cref="KGGDataSet"/> has no non-clustered indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>null</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return null; } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KGG"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="KGG"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KGG> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<string> Index_KGGKEY = new List<string>(); foreach (var entity in Entities) { Index_KGGKEY.Add(entity.KGGKEY); } builder.AppendLine("DELETE [dbo].[KGG] WHERE"); // Index_KGGKEY builder.Append("[KGGKEY] IN ("); for (int index = 0; index < Index_KGGKEY.Count; index++) { if (index != 0) builder.Append(", "); // KGGKEY var parameterKGGKEY = $"@p{parameterIndex++}"; builder.Append(parameterKGGKEY); command.Parameters.Add(parameterKGGKEY, SqlDbType.VarChar, 2).Value = Index_KGGKEY[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the KGG data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KGG data set</returns> public override EduHubDataSetDataReader<KGG> GetDataSetDataReader() { return new KGGDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the KGG data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KGG data set</returns> public override EduHubDataSetDataReader<KGG> GetDataSetDataReader(List<KGG> Entities) { return new KGGDataReader(new EduHubDataSetLoadedReader<KGG>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class KGGDataReader : EduHubDataSetDataReader<KGG> { public KGGDataReader(IEduHubDataSetReader<KGG> Reader) : base (Reader) { } public override int FieldCount { get { return 4; } } public override object GetValue(int i) { switch (i) { case 0: // KGGKEY return Current.KGGKEY; case 1: // DESCRIPTION return Current.DESCRIPTION; case 2: // EDFLAG_ORDER return Current.EDFLAG_ORDER; case 3: // OPEN_CLOSED return Current.OPEN_CLOSED; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // DESCRIPTION return Current.DESCRIPTION == null; case 2: // EDFLAG_ORDER return Current.EDFLAG_ORDER == null; case 3: // OPEN_CLOSED return Current.OPEN_CLOSED == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // KGGKEY return "KGGKEY"; case 1: // DESCRIPTION return "DESCRIPTION"; case 2: // EDFLAG_ORDER return "EDFLAG_ORDER"; case 3: // OPEN_CLOSED return "OPEN_CLOSED"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "KGGKEY": return 0; case "DESCRIPTION": return 1; case "EDFLAG_ORDER": return 2; case "OPEN_CLOSED": return 3; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using RobotDesk.Web.Areas.HelpPage.ModelDescriptions; using RobotDesk.Web.Areas.HelpPage.Models; namespace RobotDesk.Web.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Schema { using System.Collections; using System.Text; using System.Diagnostics; internal class NamespaceList { public enum ListType { Any, Other, Set }; private ListType _type = ListType.Any; private Hashtable _set = null; private string _targetNamespace; public NamespaceList() { } public NamespaceList(string namespaces, string targetNamespace) { Debug.Assert(targetNamespace != null); _targetNamespace = targetNamespace; namespaces = namespaces.Trim(); if (namespaces == "##any" || namespaces.Length == 0) { _type = ListType.Any; } else if (namespaces == "##other") { _type = ListType.Other; } else { _type = ListType.Set; _set = new Hashtable(); string[] splitString = XmlConvert.SplitString(namespaces); for (int i = 0; i < splitString.Length; ++i) { if (splitString[i] == "##local") { _set[string.Empty] = string.Empty; } else if (splitString[i] == "##targetNamespace") { _set[targetNamespace] = targetNamespace; } else { XmlConvert.ToUri(splitString[i]); // can throw _set[splitString[i]] = splitString[i]; } } } } public NamespaceList Clone() { NamespaceList nsl = (NamespaceList)MemberwiseClone(); if (_type == ListType.Set) { Debug.Assert(_set != null); nsl._set = (Hashtable)(_set.Clone()); } return nsl; } public ListType Type { get { return _type; } } public string Excluded { get { return _targetNamespace; } } public ICollection Enumerate { get { switch (_type) { case ListType.Set: return _set.Keys; case ListType.Other: case ListType.Any: default: throw new InvalidOperationException(); } } } public virtual bool Allows(string ns) { switch (_type) { case ListType.Any: return true; case ListType.Other: return ns != _targetNamespace && ns.Length != 0; case ListType.Set: return _set[ns] != null; } Debug.Assert(false); return false; } public bool Allows(XmlQualifiedName qname) { return Allows(qname.Namespace); } public override string ToString() { switch (_type) { case ListType.Any: return "##any"; case ListType.Other: return "##other"; case ListType.Set: StringBuilder sb = new StringBuilder(); bool first = true; foreach (string s in _set.Keys) { if (first) { first = false; } else { sb.Append(" "); } if (s == _targetNamespace) { sb.Append("##targetNamespace"); } else if (s.Length == 0) { sb.Append("##local"); } else { sb.Append(s); } } return sb.ToString(); } Debug.Assert(false); return string.Empty; } public static bool IsSubset(NamespaceList sub, NamespaceList super) { if (super._type == ListType.Any) { return true; } else if (sub._type == ListType.Other && super._type == ListType.Other) { return super._targetNamespace == sub._targetNamespace; } else if (sub._type == ListType.Set) { if (super._type == ListType.Other) { return !sub._set.Contains(super._targetNamespace); } else { Debug.Assert(super._type == ListType.Set); foreach (string ns in sub._set.Keys) { if (!super._set.Contains(ns)) { return false; } } return true; } } return false; } public static NamespaceList Union(NamespaceList o1, NamespaceList o2, bool v1Compat) { NamespaceList nslist = null; Debug.Assert(o1 != o2); if (o1._type == ListType.Any) { //clause 2 - o1 is Any nslist = new NamespaceList(); } else if (o2._type == ListType.Any) { //clause 2 - o2 is Any nslist = new NamespaceList(); } else if (o1._type == ListType.Set && o2._type == ListType.Set) { //clause 3 , both are sets nslist = o1.Clone(); foreach (string ns in o2._set.Keys) { nslist._set[ns] = ns; } } else if (o1._type == ListType.Other && o2._type == ListType.Other) { //clause 4, both are negations if (o1._targetNamespace == o2._targetNamespace) { //negation of same value nslist = o1.Clone(); } else { //Not a breaking change, going from not expressible to not(absent) nslist = new NamespaceList("##other", string.Empty); //clause 4, negations of different values, result is not(absent) } } else if (o1._type == ListType.Set && o2._type == ListType.Other) { if (v1Compat) { if (o1._set.Contains(o2._targetNamespace)) { nslist = new NamespaceList(); } else { //This was not there originally in V1, added for consistency since its not breaking nslist = o2.Clone(); } } else { if (o2._targetNamespace != string.Empty) { //clause 5, o1 is set S, o2 is not(tns) nslist = o1.CompareSetToOther(o2); } else if (o1._set.Contains(string.Empty)) { //clause 6.1 - set S includes absent, o2 is not(absent) nslist = new NamespaceList(); } else { //clause 6.2 - set S does not include absent, result is not(absent) nslist = new NamespaceList("##other", string.Empty); } } } else if (o2._type == ListType.Set && o1._type == ListType.Other) { if (v1Compat) { if (o2._set.Contains(o2._targetNamespace)) { nslist = new NamespaceList(); } else { nslist = o1.Clone(); } } else { //New rules if (o1._targetNamespace != string.Empty) { //clause 5, o1 is set S, o2 is not(tns) nslist = o2.CompareSetToOther(o1); } else if (o2._set.Contains(string.Empty)) { //clause 6.1 - set S includes absent, o2 is not(absent) nslist = new NamespaceList(); } else { //clause 6.2 - set S does not include absent, result is not(absent) nslist = new NamespaceList("##other", string.Empty); } } } return nslist; } private NamespaceList CompareSetToOther(NamespaceList other) { //clause 5.1 NamespaceList nslist = null; if (_set.Contains(other._targetNamespace)) { //S contains negated ns if (_set.Contains(string.Empty)) { // AND S contains absent nslist = new NamespaceList(); //any is the result } else { //clause 5.2 nslist = new NamespaceList("##other", string.Empty); } } else if (_set.Contains(string.Empty)) { //clause 5.3 - Not expressible nslist = null; } else { //clause 5.4 - Set S does not contain negated ns or absent nslist = other.Clone(); } return nslist; } public static NamespaceList Intersection(NamespaceList o1, NamespaceList o2, bool v1Compat) { NamespaceList nslist = null; Debug.Assert(o1 != o2); //clause 1 if (o1._type == ListType.Any) { //clause 2 - o1 is any nslist = o2.Clone(); } else if (o2._type == ListType.Any) { //clause 2 - o2 is any nslist = o1.Clone(); } else if (o1._type == ListType.Set && o2._type == ListType.Other) { //Clause 3 o2 is other nslist = o1.Clone(); nslist.RemoveNamespace(o2._targetNamespace); if (!v1Compat) { nslist.RemoveNamespace(string.Empty); //remove ##local } } else if (o1._type == ListType.Other && o2._type == ListType.Set) { //Clause 3 o1 is other nslist = o2.Clone(); nslist.RemoveNamespace(o1._targetNamespace); if (!v1Compat) { nslist.RemoveNamespace(string.Empty); //remove ##local } } else if (o1._type == ListType.Set && o2._type == ListType.Set) { //clause 4 nslist = o1.Clone(); nslist = new NamespaceList(); nslist._type = ListType.Set; nslist._set = new Hashtable(); foreach (string ns in o1._set.Keys) { if (o2._set.Contains(ns)) { nslist._set.Add(ns, ns); } } } else if (o1._type == ListType.Other && o2._type == ListType.Other) { if (o1._targetNamespace == o2._targetNamespace) { //negation of same namespace name nslist = o1.Clone(); return nslist; } if (!v1Compat) { if (o1._targetNamespace == string.Empty) { // clause 6 - o1 is negation of absent nslist = o2.Clone(); } else if (o2._targetNamespace == string.Empty) { //clause 6 - o1 is negation of absent nslist = o1.Clone(); } } //if it comes here, its not expressible //clause 5 } return nslist; } private void RemoveNamespace(string tns) { if (_set[tns] != null) { _set.Remove(tns); } } public bool IsEmpty() { return ((_type == ListType.Set) && ((_set == null) || _set.Count == 0)); } }; internal class NamespaceListV1Compat : NamespaceList { public NamespaceListV1Compat(string namespaces, string targetNamespace) : base(namespaces, targetNamespace) { } public override bool Allows(string ns) { if (this.Type == ListType.Other) { return ns != Excluded; } else { return base.Allows(ns); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Security.Cryptography; using System.Threading; using System.Linq; using Omnius.Base; using Omnius.Io; using Omnius.Security; using Xunit; using Xunit.Abstractions; using Omnius.Utils; namespace Omnius.Tests { [Trait("Category", "Omnius.Security")] public class Omnius_Security_Tests : TestsBase { private BufferManager _bufferManager = BufferManager.Instance; private Random _random = new Random(); public Omnius_Security_Tests(ITestOutputHelper output) : base(output) { } [Fact] public void SignatureTest() { var items = Enum.GetValues(typeof(DigitalSignatureAlgorithm)).OfType<DigitalSignatureAlgorithm>().ToArray(); foreach (var a in items) { var signature = (new DigitalSignature("123", a)).GetSignature(); Assert.Equal(Signature.Parse(signature.ToString()), signature); } foreach (var a in items) { Signature signature; using (var stream = new MemoryStream()) { stream.Write(new byte[1024], 0, 1024); stream.Seek(0, SeekOrigin.Begin); signature = (DigitalSignature.CreateCertificate(new DigitalSignature("123", a), stream)).GetSignature(); } Assert.Equal(Signature.Parse(signature.ToString()), signature); } } [Fact] public void DigitalSigunatureTest() { var items = Enum.GetValues(typeof(DigitalSignatureAlgorithm)).OfType<DigitalSignatureAlgorithm>().ToArray(); foreach (var a in items) { { var sigunature = new DigitalSignature("123", a); using (var streamSigunature = DigitalSignatureConverter.ToDigitalSignatureStream(sigunature)) { var sigunature2 = DigitalSignatureConverter.FromDigitalSignatureStream(streamSigunature); Assert.True(sigunature.GetHashCode() == sigunature2.GetHashCode()); Assert.True(sigunature == sigunature2); Assert.Equal(sigunature, sigunature2); } } { using (var stream = new MemoryStream()) { stream.Write(_random.GetBytes(1024), 0, 1024); stream.Seek(0, SeekOrigin.Begin); var certificate = DigitalSignature.CreateCertificate(new DigitalSignature("123", a), stream); stream.Seek(0, SeekOrigin.Begin); Assert.True(DigitalSignature.VerifyCertificate(certificate, stream)); stream.Seek(0, SeekOrigin.End); stream.Write(_random.GetBytes(1024), 0, 1024); stream.Seek(0, SeekOrigin.Begin); Assert.False(DigitalSignature.VerifyCertificate(certificate, stream)); } } } } [Fact] public void AgreementTest() { var items = Enum.GetValues(typeof(AgreementAlgorithm)).OfType<AgreementAlgorithm>().ToArray(); foreach (var a in items) { for (int i = 0; i < 10; i++) { var agreement1 = new Agreement(a); var agreement2 = new Agreement(a); var r1 = Agreement.GetSecret(agreement1.GetAgreementPublicKey(), agreement2.GetAgreementPrivateKey()); var r2 = Agreement.GetSecret(agreement2.GetAgreementPublicKey(), agreement1.GetAgreementPrivateKey()); Assert.True(CollectionUtils.Equals(r1, r2)); } } } [Fact] public void ExchangeTest() { var items = Enum.GetValues(typeof(ExchangeAlgorithm)).OfType<ExchangeAlgorithm>().ToArray(); foreach (var a in items) { for (int i = 0; i < 10; i++) { var exchange = new Exchange(a); var buffer = new byte[128]; _random.NextBytes(buffer); var eBuffer = Exchange.Encrypt(exchange.GetExchangePublicKey(), buffer); var dBuffer = Exchange.Decrypt(exchange.GetExchangePrivateKey(), eBuffer); Assert.True(CollectionUtils.Equals(buffer, dBuffer)); } } } [Fact] public void Kdf2Test() { var kdf2 = new Kdf2(System.Security.Cryptography.SHA256.Create()); var value = kdf2.GetBytes(new byte[4], 128); Assert.True(value.Length >= 128); } [Fact] public void Pbkdf2Test() { var password = new byte[256]; var salt = new byte[256]; _random.NextBytes(password); _random.NextBytes(salt); using (var hmac = new System.Security.Cryptography.HMACSHA1()) { var pbkdf2 = new Pbkdf2(hmac, password, salt, 1024); var rfc2898DeriveBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, 1024); Assert.True(CollectionUtils.Equals(pbkdf2.GetBytes(1024), rfc2898DeriveBytes.GetBytes(1024))); } //_random.NextBytes(password); //_random.NextBytes(salt); //using (var hmac = new System.Security.Cryptography.HMACSHA256()) //{ // CryptoConfig.AddAlgorithm(typeof(SHA256Cng), // "SHA256", // "SHA256Cng", // "System.Security.Cryptography.SHA256", // "System.Security.Cryptography.SHA256Cng"); // hmac.HashName = "System.Security.Cryptography.SHA256"; // Pbkdf2 pbkdf2 = new Pbkdf2(hmac, password, salt, 1024); // var h = pbkdf2.GetBytes(10); //} } [Fact] public void Crc32_CastagnoliTest() { for (int type = 0; type < 2; type++) { if (type == 0) Crc32_Castagnoli.LoadNativeMethods(); else if (type == 1) Crc32_Castagnoli.LoadPureUnsafeMethods(); var buffer = new byte[1024 * 32]; _random.NextBytes(buffer); Assert.True(CollectionUtils.Equals(T_Crc32_Castagnoli.ComputeHash(buffer), Crc32_Castagnoli.Compute(buffer))); using (var stream1 = new MemoryStream(buffer)) using (var stream2 = new MemoryStream(buffer)) { Assert.True(CollectionUtils.Equals(T_Crc32_Castagnoli.ComputeHash(stream1), Crc32_Castagnoli.Compute(stream2))); } var list = new List<ArraySegment<byte>>(); list.Add(new ArraySegment<byte>(buffer)); list.Add(new ArraySegment<byte>(buffer)); list.Add(new ArraySegment<byte>(buffer)); list.Add(new ArraySegment<byte>(buffer)); Assert.True(CollectionUtils.Equals(T_Crc32_Castagnoli.ComputeHash(list), Crc32_Castagnoli.Compute(list))); } Crc32_Castagnoli.LoadNativeMethods(); } [Fact] public void HmacSha256Test() { // http://tools.ietf.org/html/rfc4868#section-2.7.1 { var key = NetworkConverter.FromHexString("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); var value = NetworkConverter.FromHexString("4869205468657265"); using (var stream = new MemoryStream(value)) { string s = NetworkConverter.ToHexString(HmacSha256.Compute(stream, key)); } using (var hmacSha256 = new HMACSHA256(key)) { string s = NetworkConverter.ToHexString(hmacSha256.ComputeHash(value)); } } var list = new List<int>(); list.Add(1); list.Add(64); list.Add(128); var buffer = new byte[1024 * 32]; _random.NextBytes(buffer); for (int i = 0; i < list.Count; i++) { var key = new byte[list[i]]; _random.NextBytes(key); using (var stream1 = new MemoryStream(buffer)) using (var stream2 = new MemoryStream(buffer)) { using (var hmacSha256 = new HMACSHA256(key)) { Assert.True(Unsafe.Equals(hmacSha256.ComputeHash(stream1), HmacSha256.Compute(stream2, key))); } } } } [Fact] public void MinerTest() { //{ // var key = NetworkConverter.FromHexString("e0ee19d617ee6ea9ea592afbdf71bafba6eecde2beba0d3cdc51419522fe5dbdf18f6830081be1615969b1fe43344fac3c312cd86a487cb1bd04f2c44cddca11"); // var value = NetworkConverter.FromHexString("01010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101"); // var count = Verify_1(key, value); //} { var miner = new Miner(CashAlgorithm.Version1, -1, new TimeSpan(0, 0, 1)); Cash cash = null; var sw = new Stopwatch(); sw.Start(); var tokenSource = new CancellationTokenSource(); using (var stream = new MemoryStream(NetworkConverter.FromHexString("0101010101010101"))) { cash = miner.Create(stream, tokenSource.Token).Result; } sw.Stop(); Assert.True(sw.ElapsedMilliseconds < 1000 * 30); } { var miner = new Miner(CashAlgorithm.Version1, 20, new TimeSpan(1, 0, 0)); Cash cash = null; var tokenSource = new CancellationTokenSource(); using (var stream = new MemoryStream(NetworkConverter.FromHexString("0101010101010101"))) { cash = miner.Create(new WrapperStream(stream), tokenSource.Token).Result; stream.Seek(0, SeekOrigin.Begin); Assert.True(Miner.Verify(cash, stream).Value >= 20); } } { var miner = new Miner(CashAlgorithm.Version1, 0, TimeSpan.Zero); Cash cash = null; var tokenSource = new CancellationTokenSource(); using (var stream = new MemoryStream(NetworkConverter.FromHexString("0101010101010101"))) { cash = miner.Create(stream, tokenSource.Token).Result; } Assert.True(cash == null); } { var sw = new Stopwatch(); sw.Start(); Assert.Throws<AggregateException>(() => { var miner = new Miner(CashAlgorithm.Version1, -1, new TimeSpan(1, 0, 0)); var tokenSource = new CancellationTokenSource(); using (var stream = new MemoryStream(NetworkConverter.FromHexString("0101010101010101"))) { var task = miner.Create(stream, tokenSource.Token); Thread.Sleep(1000); tokenSource.Cancel(); var cash = task.Result; } }); sw.Stop(); Assert.True(sw.ElapsedMilliseconds < 1000 * 30); } } } }
using System; using System.Collections.Generic; using System.Text; using RRLab.PhysiologyWorkbench.Data; using RRLab.PhysiologyWorkbench.Devices; using NationalInstruments.DAQmx; namespace RRLab.PhysiologyWorkbench.Daq { public class LaserFluorescenceRecordingProtocol : DaqProtocol { private Task _DOTask; protected Task DOTask { get { return _DOTask; } set { _DOTask = value; } } private Task _AITask; protected Task AITask { get { return _AITask; } set { _AITask = value; } } private string _AISampleClock = "/dev1/MasterTimebase"; public string AISampleClock { get { return _AISampleClock; } set { _AISampleClock = value; FireSettingsChangedEvent(this, EventArgs.Empty); } } private string _DOSampleClock = "/dev1/MasterTimebase"; public string DOSampleClock { get { return _DOSampleClock; } set { _DOSampleClock = value; FireSettingsChangedEvent(this, EventArgs.Empty); } } private int _SampleRate = 10000; public int SampleRate { get { return _SampleRate; } set { _SampleRate = value; } } private SampleClockActiveEdge _ClockEdge = SampleClockActiveEdge.Rising; public SampleClockActiveEdge ClockEdge { get { return _ClockEdge; } set { _ClockEdge = value; } } private int _AcquisitionLength = 5000; public int AcquisitionLength { get { return _AcquisitionLength; } set { _AcquisitionLength = value; } } private List<string> _ChannelNames = new List<string>(); public ICollection<string> ChannelNames { get { return _ChannelNames.AsReadOnly(); } protected set { _ChannelNames.Clear(); _ChannelNames.AddRange(value); } } private Amplifier _Amplifier; public Amplifier Amplifier { get { return _Amplifier; } set { _Amplifier = value; FireSettingsChangedEvent(this, EventArgs.Empty); } } private SpectraPhysicsNitrogenLaser _Laser; public SpectraPhysicsNitrogenLaser Laser { get { return _Laser; } set { _Laser = value; FireSettingsChangedEvent(this, EventArgs.Empty); } } private Photodiode _Photodiode1; public Photodiode Photodiode1 { get { return _Photodiode1; } set { _Photodiode1 = value; FireSettingsChangedEvent(this, EventArgs.Empty); } } private Photodiode _Photodiode2; public Photodiode Photodiode2 { get { return _Photodiode2; } set { _Photodiode2 = value; FireSettingsChangedEvent(this, EventArgs.Empty); } } private FilterWheel _FilterWheel; public FilterWheel FilterWheel { get { return _FilterWheel; } set { _FilterWheel = value; FireSettingsChangedEvent(this, EventArgs.Empty); } } private int _LaserPulseFrequency = 20; public int LaserPulseFrequency { get { return _LaserPulseFrequency; } set { _LaserPulseFrequency = value; } } private float _PreFlashAcquisitionTime = 0.5F; public float PreFlashAcquisitionTime { get { return _PreFlashAcquisitionTime; } set { _PreFlashAcquisitionTime = value; } } private float _PostFlashAcquisitionTime = 1.5F; public float PostFlashAcquisitionTime { get { return _PostFlashAcquisitionTime; } set { _PostFlashAcquisitionTime = value; } } private bool _DiscardDataBetweenFlashes = true; public bool DiscardDataBetweenFlashes { get { return _DiscardDataBetweenFlashes; } set { _DiscardDataBetweenFlashes = value; FireSettingsChangedEvent(this, EventArgs.Empty); } } private string _DOStartTrigger = "/dev1/ai/StartTrigger"; public string DOStartTrigger { get { return _DOStartTrigger; } set { _DOStartTrigger = value; FireSettingsChangedEvent(this, EventArgs.Empty); } } private DigitalEdgeStartTriggerEdge _DOStartTriggerEdge = DigitalEdgeStartTriggerEdge.Rising; public DigitalEdgeStartTriggerEdge DOStartTriggerEdge { get { return _DOStartTriggerEdge; } set { _DOStartTriggerEdge = value; FireSettingsChangedEvent(this, EventArgs.Empty); } } protected AnalogMultiChannelReader AIReader = null; public LaserFluorescenceRecordingProtocol() { } protected override void Initialize() { Data = null; if ((DOTask != null) || (AITask != null)) FinalizeProtocol(); try { DOTask = new Task("DO"); AITask = new Task("AI"); ConfigureChannels(); // Configure channels if (ChannelNames.Count == 0) { for (int i = 0; i < AITask.AIChannels.Count; i++) _ChannelNames.Add(AITask.AIChannels[i].VirtualName); } int nsamples = AcquisitionLength * SampleRate / 1000; int nReducedSamples = Convert.ToInt32((PreFlashAcquisitionTime + PostFlashAcquisitionTime) * SampleRate / 1000); if (!DiscardDataBetweenFlashes) nReducedSamples = nsamples; // Configure timing AITask.Timing.ConfigureSampleClock(AISampleClock, SampleRate, ClockEdge, SampleQuantityMode.FiniteSamples, nsamples); DOTask.Timing.ConfigureSampleClock(DOSampleClock, SampleRate, ClockEdge, SampleQuantityMode.FiniteSamples, nsamples); // Configure triggers DOTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(DOStartTrigger, DOStartTriggerEdge); AITask.Control(TaskAction.Verify); DOTask.Control(TaskAction.Verify); FireStartingEvent(this, EventArgs.Empty); } catch (Exception e) { System.Windows.Forms.MessageBox.Show("Error during initialization: " + e.Message); FinalizeProtocol(); } } protected virtual void ConfigureChannelReaders() { AIReader = new AnalogMultiChannelReader(AITask.Stream); } public override void StartContinuousExecute() { if (!IsContinuousRecordingSupported) throw new ApplicationException("Continuous execution is not supported."); StopContinuousExecutionTrigger = false; Initialize(); System.Threading.ThreadStart exec = new System.Threading.ThreadStart(ContinuousExecute); ContinuouslyExecutingThread = new System.Threading.Thread(exec); ContinuouslyExecutingThread.Start(); } protected override void Execute() { try { WriteToDOChannels(); ConfigureChannelReaders(); DOTask.Start(); AITask.Start(); BeginAsyncRecordFromAIChannels(); AITask.WaitUntilDone(); DOTask.WaitUntilDone(); } catch (Exception e) { System.Windows.Forms.MessageBox.Show("Error during execution: " + e.Message); FinalizeProtocol(); } } protected virtual void ContinuousExecute() { WriteToDOChannels(); ConfigureChannelReaders(); while (!StopContinuousExecutionTrigger) { try { DOTask.Start(); AITask.Start(); AsyncRecordFromAIChannels(); AITask.WaitUntilDone(); AITask.Stop(); DOTask.Stop(); } catch (Exception e) { StopContinuousExecutionTrigger = true; System.Windows.Forms.MessageBox.Show("Error during execution: " + e.Message); FinalizeProtocol(); } } } public override void StopContinuousExecute() { StopContinuousExecutionTrigger = true; try { ContinuouslyExecutingThread.Join(AcquisitionLength * 2); } finally { ContinuouslyExecutingThread = null; FinalizeProtocol(); } } protected virtual void AsyncRecordFromAIChannels() { // Read all the samples int nsamples = Convert.ToInt32(AcquisitionLength * SampleRate / 1000); AIReader.BeginReadMultiSample(nsamples, new AsyncCallback(OnAIReadCompleted), null); } protected virtual void BeginAsyncRecordFromAIChannels() { System.Threading.ThreadStart asyncRecord = new System.Threading.ThreadStart(AsyncRecordFromAIChannels); asyncRecord.Invoke(); } protected override void FinalizeProtocol() { try { if (DOTask != null) { DOTask.Dispose(); DOTask = null; } if (AITask != null) { AITask.Dispose(); AITask = null; } } catch (Exception e) { System.Windows.Forms.MessageBox.Show("Error during finalization: " + e.Message); } FireFinishedEvent(this, EventArgs.Empty); } protected override void Dispose(bool disposing) { if (DOTask != null) DOTask.Dispose(); if (AITask != null) AITask.Dispose(); base.Dispose(disposing); } protected virtual void OnAIReadCompleted(IAsyncResult ar) { if (Disposing) return; double[,] data = AIReader.EndReadMultiSample(ar); string[] channelNames = new string[ChannelNames.Count]; ChannelNames.CopyTo(channelNames, 0); StoreCollectedData(channelNames, data); } protected virtual void StoreCollectedData(string[] channelNames, double[,] data) { List<string> units = new List<string>(); foreach (string name in channelNames) if (name == "Current") units.Add("pA"); else units.Add("V"); int nDataSamples = data.Length / channelNames.Length; int nSamplesToKeep = Convert.ToInt32((PreFlashAcquisitionTime + PostFlashAcquisitionTime) * ((AcquisitionLength / 1000) * LaserPulseFrequency) * SampleRate / 1000); float[] time = new float[nSamplesToKeep]; double[,] reducedData = new double[channelNames.Length, nSamplesToKeep]; Data = new Recording(); if (!DiscardDataBetweenFlashes) { nSamplesToKeep = nDataSamples; time = new float[nDataSamples]; for (int i = 0; i < nDataSamples; i++) time[i] = 1000F * ((float)i) / ((float)SampleRate); Data.AddData(channelNames, time, reducedData, units.ToArray()); } else { float tPreFlashDiscard = Laser.MinimumChargingTime - PreFlashAcquisitionTime; float tPostFlashDiscard = Laser.MinimumChargingTime + PostFlashAcquisitionTime; float tLaserPeriod = 1000F / ((float) LaserPulseFrequency); int i_stored = 0; // Index for the next data point stored for (int i = 0; i < nDataSamples; i++) { float t = 1000 * ((float)i) / ((float)SampleRate); // Calculate the time relative to the laser period float t_relative = t - (float) Math.Floor(t / tLaserPeriod)*tLaserPeriod; // tLaserPeriod + Math.IEEERemainder(t, tLaserPeriod); // Keep data between tPreFlashDiscard and tPostFlashDiscard if (t_relative > tPreFlashDiscard && t_relative <= tPostFlashDiscard) { time[i_stored] = t; for (int j = 0; j < channelNames.Length; j++) reducedData[j, i_stored] = data[j, i]; i_stored++; } else continue; // Otherwise discard } Data.AddData(channelNames, time, reducedData, units.ToArray()); } ProcessData(); } protected virtual void ConfigureChannels() { if ((Photodiode1 == null) && (Photodiode2 == null)) throw new ApplicationException("At least one photodiode must be set."); if (Photodiode1 != null) AITask.AIChannels.CreateVoltageChannel(Photodiode1.IntensityAI, Photodiode1.Name, NationalInstruments.DAQmx.AITerminalConfiguration.Rse, -10, 10, NationalInstruments.DAQmx.AIVoltageUnits.Volts); if (Photodiode2 != null && Photodiode2 != Photodiode1) AITask.AIChannels.CreateVoltageChannel(Photodiode2.IntensityAI, Photodiode2.Name, NationalInstruments.DAQmx.AITerminalConfiguration.Rse, -10, 10, NationalInstruments.DAQmx.AIVoltageUnits.Volts); DOTask.DOChannels.CreateChannel("/dev2/port0", "DO", NationalInstruments.DAQmx.ChannelLineGrouping.OneChannelForAllLines); DOTask.Stream.WriteRegenerationMode = WriteRegenerationMode.AllowRegeneration; } protected virtual void WriteToDOChannels() { DigitalSingleChannelWriter writer = new DigitalSingleChannelWriter(DOTask.Stream); byte[] output = Laser.GenerateLaserFlashDaqOutput(SampleRate, 1000/((double)LaserPulseFrequency), Laser.MinimumChargingTime); // Add laser method writer.WriteMultiSamplePort(false, output); } public override string ProtocolName { get { return "Laser-Illuminated Fluorescence Recording Protocol"; } } public override string ProtocolDescription { get { return "Records from a photodiode while illuminating continuously with a pulsed laser."; } } public override System.Windows.Forms.Control GetConfigurationControl() { return new LaserFluorescenceRecordingProtocolConfigPanel(this); } protected override void AnnotateData() { Amplifier.AnnotateEquipmentData(Data); base.AnnotateData(); } } }
/* * 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 ec2-2015-10-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.EC2.Model { /// <summary> /// Container for the parameters to the ImportImage operation. /// Import single or multi-volume disk images or EBS snapshots into an Amazon Machine /// Image (AMI). /// </summary> public partial class ImportImageRequest : AmazonEC2Request { private string _architecture; private ClientData _clientData; private string _clientToken; private string _description; private List<ImageDiskContainer> _diskContainers = new List<ImageDiskContainer>(); private string _hypervisor; private string _licenseType; private string _platform; private string _roleName; /// <summary> /// Gets and sets the property Architecture. /// <para> /// The architecture of the virtual machine. /// </para> /// /// <para> /// Valid values: <code>i386</code> | <code>x86_64</code> /// </para> /// </summary> public string Architecture { get { return this._architecture; } set { this._architecture = value; } } // Check to see if Architecture property is set internal bool IsSetArchitecture() { return this._architecture != null; } /// <summary> /// Gets and sets the property ClientData. /// <para> /// The client-specific data. /// </para> /// </summary> public ClientData ClientData { get { return this._clientData; } set { this._clientData = value; } } // Check to see if ClientData property is set internal bool IsSetClientData() { return this._clientData != null; } /// <summary> /// Gets and sets the property ClientToken. /// <para> /// The token to enable idempotency for VM import requests. /// </para> /// </summary> public string ClientToken { get { return this._clientToken; } set { this._clientToken = value; } } // Check to see if ClientToken property is set internal bool IsSetClientToken() { return this._clientToken != null; } /// <summary> /// Gets and sets the property Description. /// <para> /// A description string for the import image task. /// </para> /// </summary> public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } /// <summary> /// Gets and sets the property DiskContainers. /// <para> /// Information about the disk containers. /// </para> /// </summary> public List<ImageDiskContainer> DiskContainers { get { return this._diskContainers; } set { this._diskContainers = value; } } // Check to see if DiskContainers property is set internal bool IsSetDiskContainers() { return this._diskContainers != null && this._diskContainers.Count > 0; } /// <summary> /// Gets and sets the property Hypervisor. /// <para> /// The target hypervisor platform. /// </para> /// /// <para> /// Valid values: <code>xen</code> /// </para> /// </summary> public string Hypervisor { get { return this._hypervisor; } set { this._hypervisor = value; } } // Check to see if Hypervisor property is set internal bool IsSetHypervisor() { return this._hypervisor != null; } /// <summary> /// Gets and sets the property LicenseType. /// <para> /// The license type to be used for the Amazon Machine Image (AMI) after importing. /// </para> /// /// <para> /// <b>Note:</b> You may only use BYOL if you have existing licenses with rights to use /// these licenses in a third party cloud like AWS. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/VMImportPrerequisites.html">VM /// Import/Export Prerequisites</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>. /// </para> /// /// <para> /// Valid values: <code>AWS</code> | <code>BYOL</code> /// </para> /// </summary> public string LicenseType { get { return this._licenseType; } set { this._licenseType = value; } } // Check to see if LicenseType property is set internal bool IsSetLicenseType() { return this._licenseType != null; } /// <summary> /// Gets and sets the property Platform. /// <para> /// The operating system of the virtual machine. /// </para> /// /// <para> /// Valid values: <code>Windows</code> | <code>Linux</code> /// </para> /// </summary> public string Platform { get { return this._platform; } set { this._platform = value; } } // Check to see if Platform property is set internal bool IsSetPlatform() { return this._platform != null; } /// <summary> /// Gets and sets the property RoleName. /// <para> /// The name of the role to use when not using the default role, 'vmimport'. /// </para> /// </summary> public string RoleName { get { return this._roleName; } set { this._roleName = value; } } // Check to see if RoleName property is set internal bool IsSetRoleName() { return this._roleName != null; } } }
/* * Original author: Nicholas Shulman <nicksh .at. u.washington.edu>, * MacCoss Lab, Department of Genome Sciences, UW * * Copyright 2011 University of Washington - Seattle, WA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Threading; using pwiz.Common.Collections; namespace pwiz.Common.DataBinding.Internal { /// <summary> /// Handles transforming a ViewInfo and a collection of objects into a list of RowItems. /// First the objects are expanded into a list of RowNode's which lists of child /// nodes corresponding to the one-to-many relationships. /// Second, the RowNode's are and aggregated and grouped if the ViewInfo has any /// aggregates. /// Third, the RowNodes are transformed into RowItems. RowItems have only one /// list of children, corresponding to the SublistId of the ViewInfo. Other /// children become PivotKeys in the RowItem. /// </summary> internal class Pivoter { /// <summary> /// Pivoter Constructor. Initializes many lists of ColumnDescriptors that /// get used while doing the work of expanding, aggregating, and pivoting. /// </summary> public Pivoter(ViewInfo viewInfo) { ViewInfo = viewInfo; var collectionColumnArray = ViewInfo.GetCollectionColumns().ToArray(); Array.Sort(collectionColumnArray, (cd1, cd2) => cd1.PropertyPath.CompareTo(cd2.PropertyPath)); CollectionColumns = Array.AsReadOnly(collectionColumnArray); var sublistColumns = new List<ColumnDescriptor>(); var pivotColumns = new List<ColumnDescriptor>(); foreach (var collectionColumn in CollectionColumns) { if (collectionColumn.PropertyPath.IsRoot) { continue; } if (ViewInfo.SublistId.StartsWith(collectionColumn.PropertyPath)) { sublistColumns.Add(collectionColumn); } else { pivotColumns.Add(collectionColumn); } } SublistColumns = ImmutableList.ValueOf(sublistColumns); PivotColumns = ImmutableList.ValueOf(pivotColumns); } /// <summary> /// The ViewInfo that this Pivoter was created from. /// </summary> public ViewInfo ViewInfo { get; private set; } /// <summary> /// The list of all of the collection columns used by the ViewInfo. /// This includes the ParentColumn of the ViewInfo. /// </summary> public IList<ColumnDescriptor> CollectionColumns { get; private set; } /// <summary> /// The list of collection columns which should be expanded into /// separate RowItems in the grid. /// </summary> public IList<ColumnDescriptor> SublistColumns { get; private set; } /// <summary> /// The list of collection columns which are not SublistColumns, /// and show be expanded horizontally in the grid. /// </summary> public IList<ColumnDescriptor> PivotColumns { get; private set; } public IEnumerable<RowItem> Expand(CancellationToken cancellationToken, RowItem rowItem, int sublistColumnIndex) { cancellationToken.ThrowIfCancellationRequested(); if (sublistColumnIndex >= SublistColumns.Count) { return new[] {rowItem}; } var sublistColumn = SublistColumns[sublistColumnIndex]; object parentValue = sublistColumn.Parent.GetPropertyValue(rowItem, null); if (null == parentValue) { return new[] {rowItem}; } var items = sublistColumn.CollectionInfo.GetItems(parentValue).Cast<object>().ToArray(); if (items.Length == 0) { return new[] {rowItem}; } cancellationToken.ThrowIfCancellationRequested(); IList<object> keys = null; if (sublistColumn.CollectionInfo.IsDictionary) { keys = sublistColumn.CollectionInfo.GetKeys(parentValue).Cast<object>().ToArray(); } var expandedItems = new List<RowItem>(); for (int index = 0; index < items.Length; index++) { cancellationToken.ThrowIfCancellationRequested(); object key = keys == null ? index : keys[index]; var child = rowItem.SetRowKey(rowItem.RowKey.AppendValue(sublistColumn.PropertyPath, key)); expandedItems.AddRange(Expand(cancellationToken, child, sublistColumnIndex + 1)); } return expandedItems; } public RowItem Pivot(CancellationToken cancellationToken, RowItem rowItem) { cancellationToken.ThrowIfCancellationRequested(); foreach (var pivotColumn in PivotColumns) { cancellationToken.ThrowIfCancellationRequested(); var parent = pivotColumn.Parent.CollectionAncestor(); IList<PivotKey> pivotKeys; if (null == parent) { pivotKeys = new PivotKey[] { null }; } else { pivotKeys = rowItem.PivotKeys.Where(key => key.Last.Key.Equals(parent.PropertyPath)).ToArray(); } foreach (var pivotKey in pivotKeys) { cancellationToken.ThrowIfCancellationRequested(); var parentValue = pivotColumn.Parent.GetPropertyValue(rowItem, pivotKey); if (null != parentValue) { var keys = pivotColumn.CollectionInfo.GetKeys(parentValue).Cast<object>().ToArray(); if (keys.Length > 0) { var newPivotKeys = rowItem.PivotKeys.Except(new[] {pivotKey}).ToList(); var pivotKeyLocal = pivotKey ?? PivotKey.EMPTY; var propertyPath = pivotColumn.PropertyPath; newPivotKeys.AddRange(keys.Select(key => pivotKeyLocal.AppendValue(propertyPath, key))); rowItem = rowItem.SetPivotKeys(new HashSet<PivotKey>(newPivotKeys)); } } } } return rowItem; } public IEnumerable<RowItem> Filter(CancellationToken cancellationToken, IEnumerable<RowItem> rowItems) { if (ViewInfo.Filters.Count == 0) { return rowItems; } var filteredRows = new List<RowItem>(); foreach (var rowItem in rowItems) { cancellationToken.ThrowIfCancellationRequested(); var filteredRowItem = rowItem; foreach (var filter in ViewInfo.Filters) { filteredRowItem = filter.ApplyFilter(filteredRowItem); if (null == filteredRowItem) { break; } } if (null != filteredRowItem) { filteredRows.Add(filteredRowItem); } } return filteredRows; } public PivotedRows ExpandAndPivot(CancellationToken cancellationToken, IEnumerable<RowItem> rowItems) { var expandedItems = rowItems.SelectMany(rowItem => Expand(cancellationToken, rowItem, 0)).ToArray(); var pivotedItems = expandedItems.Select(item => Pivot(cancellationToken, item)); var filteredItems = Filter(cancellationToken, pivotedItems); var rows = ImmutableList.ValueOf(filteredItems); var result = new PivotedRows(rows, new PropertyDescriptorCollection(GetItemProperties(rows).ToArray())); if (ViewInfo.HasTotals) { result = GroupAndTotal(cancellationToken, result); } return result; } public PivotedRows GroupAndTotal(CancellationToken cancellationToken, PivotedRows pivotedRows) { IDictionary<IList<Tuple<PropertyPath, PivotKey, object>>, List<GroupedRow>> allReportRows = new Dictionary<IList<Tuple<PropertyPath, PivotKey, object>>, List<GroupedRow>>(); var groupColumns = ViewInfo.DisplayColumns .Where(col => TotalOperation.GroupBy == col.ColumnSpec.TotalOperation) .Select(col => col.ColumnDescriptor) .ToArray(); var pivotOnColumns = ViewInfo.DisplayColumns .Where(col => TotalOperation.PivotKey == col.ColumnSpec.TotalOperation) .Select(col => col.ColumnDescriptor) .ToArray(); var allInnerPivotKeys = new HashSet<PivotKey>(); var allPivotKeys = new Dictionary<PivotKey, PivotKey>(); foreach (var rowItem in pivotedRows.RowItems) { cancellationToken.ThrowIfCancellationRequested(); allInnerPivotKeys.UnionWith(rowItem.PivotKeys); IList<Tuple<PropertyPath, PivotKey, object>> groupKey = new List<Tuple<PropertyPath, PivotKey, object>>(); foreach (var column in groupColumns) { cancellationToken.ThrowIfCancellationRequested(); var pivotColumn = GetPivotColumn(column); if (null == pivotColumn) { groupKey.Add(new Tuple<PropertyPath, PivotKey, object>(column.PropertyPath, null, column.GetPropertyValue(rowItem, null))); } else { foreach (var pivotKey in GetPivotKeys(pivotColumn.PropertyPath, new []{rowItem})) { cancellationToken.ThrowIfCancellationRequested(); if (!pivotKey.Contains(pivotColumn.PropertyPath)) { continue; } groupKey.Add(new Tuple<PropertyPath, PivotKey, object>(column.PropertyPath, pivotKey, column.GetPropertyValue(rowItem, pivotKey))); } } } groupKey = ImmutableList.ValueOf(groupKey); var pivotOnKeyValues = new List<KeyValuePair<PropertyPath, object>>(); foreach (var column in pivotOnColumns) { cancellationToken.ThrowIfCancellationRequested(); var pivotColumn = GetPivotColumn(column); if (null == pivotColumn) { pivotOnKeyValues.Add(new KeyValuePair<PropertyPath, object>(column.PropertyPath, column.GetPropertyValue(rowItem, null))); } else { Trace.TraceWarning("Unable to pivot on column {0} because it is already pivoted.", pivotColumn.PropertyPath); // Not L10N } } var pivotOnKey = PivotKey.GetPivotKey(allPivotKeys, pivotOnKeyValues); List<GroupedRow> rowGroups; if (!allReportRows.TryGetValue(groupKey, out rowGroups)) { rowGroups = new List<GroupedRow>(); allReportRows.Add(groupKey, rowGroups); } var rowGroup = rowGroups.FirstOrDefault(rg => !rg.ContainsKey(pivotOnKey)); if (null == rowGroup) { rowGroup = new GroupedRow(); rowGroups.Add(rowGroup); } rowGroup.AddInnerRow(pivotOnKey, rowItem); } var outerPivotKeys = allPivotKeys.Keys.Where(key=>key.Length == pivotOnColumns.Length).ToArray(); var pivotKeyComparer = PivotKey.GetComparer(ViewInfo.DataSchema); Array.Sort(outerPivotKeys, pivotKeyComparer); var innerPivotKeys = allInnerPivotKeys.ToArray(); Array.Sort(innerPivotKeys, pivotKeyComparer); var reportItemProperties = new List<PropertyDescriptor>(); var propertyNames = new HashSet<string>(); foreach (var displayColumn in ViewInfo.DisplayColumns) { cancellationToken.ThrowIfCancellationRequested(); if (displayColumn.ColumnSpec.Hidden) { continue; } var totalOperation = displayColumn.ColumnSpec.TotalOperation; if (TotalOperation.GroupBy == totalOperation) { var pivotColumn = GetPivotColumn(displayColumn.ColumnDescriptor); if (null == pivotColumn) { string propertyName = MakeUniqueName(propertyNames, displayColumn.PropertyPath); reportItemProperties.Add(new GroupedPropertyDescriptor(propertyName, displayColumn, null)); } else { foreach (var innerPivotKey in innerPivotKeys) { cancellationToken.ThrowIfCancellationRequested(); string propertyName = MakeUniqueName(propertyNames, displayColumn.PropertyPath); reportItemProperties.Add(new GroupedPropertyDescriptor(propertyName, displayColumn, innerPivotKey)); } } } } foreach (var outerPivotKey in outerPivotKeys) { foreach (var displayColumn in ViewInfo.DisplayColumns) { cancellationToken.ThrowIfCancellationRequested(); if (displayColumn.ColumnSpec.Hidden) { continue; } if (TotalOperation.PivotValue == displayColumn.ColumnSpec.TotalOperation || TotalOperation.PivotKey == displayColumn.ColumnSpec.TotalOperation) { var pivotColumn = GetPivotColumn(displayColumn.ColumnDescriptor); if (null == pivotColumn) { string propertyName = MakeUniqueName(propertyNames, displayColumn.PropertyPath); reportItemProperties.Add(new GroupedPropertyDescriptor(propertyName, outerPivotKey, displayColumn, null)); } else { foreach (var innerPivotKey in allInnerPivotKeys) { string propertyName = MakeUniqueName(propertyNames, displayColumn.PropertyPath); reportItemProperties.Add(new GroupedPropertyDescriptor(propertyName, outerPivotKey, displayColumn, innerPivotKey)); } } } } } return new PivotedRows(allReportRows.SelectMany(entry=>entry.Value.Select( reportRow=>new RowItem(reportRow))), new PropertyDescriptorCollection(reportItemProperties.ToArray())); } public HashSet<PivotKey> GetPivotKeys(PropertyPath pivotColumnId, IEnumerable<RowItem> rowItems) { var pivotKeys = new HashSet<PivotKey>(); foreach (var row in rowItems) { pivotKeys.UnionWith(row.PivotKeys); } pivotKeys.RemoveWhere(pivotKey => !pivotKey.Contains(pivotColumnId)); return pivotKeys; } public IDictionary<PropertyPath, ICollection<PivotKey>> GetAllPivotKeys(IEnumerable<RowItem> rowItems) { var result = new Dictionary<PropertyPath, ICollection<PivotKey>>(); var enumerable = rowItems as RowItem[] ?? rowItems.ToArray(); foreach (var pivotColumn in PivotColumns) { result.Add(pivotColumn.PropertyPath, GetPivotKeys(pivotColumn.PropertyPath, enumerable)); } return result; } private ColumnDescriptor GetPivotColumn(ColumnDescriptor columnDescriptor) { return PivotColumns.LastOrDefault(col => columnDescriptor.PropertyPath.StartsWith(col.PropertyPath)); } public IEnumerable<PropertyDescriptor> GetItemProperties(IEnumerable<RowItem> rowItems) { var columnNames = new HashSet<string>(); var propertyDescriptors = new List<PropertyDescriptor>(); var pivotDisplayColumns = new Dictionary<PivotKey, List<DisplayColumn>>(); var rowItemsArray = rowItems as RowItem[] ?? rowItems.ToArray(); foreach (var displayColumn in ViewInfo.DisplayColumns) { if (displayColumn.ColumnSpec.Hidden) { continue; } var pivotColumn = PivotColumns.LastOrDefault(pc => displayColumn.PropertyPath.StartsWith(pc.PropertyPath)); ICollection<PivotKey> pivotKeys = null; if (pivotColumn != null) { pivotKeys = GetPivotKeys(pivotColumn.PropertyPath, rowItemsArray); } if (pivotKeys == null) { propertyDescriptors.Add(new ColumnPropertyDescriptor(displayColumn, MakeUniqueName(columnNames, displayColumn.PropertyPath))); continue; } foreach (var value in pivotKeys) { List<DisplayColumn> columns; if (!pivotDisplayColumns.TryGetValue(value, out columns)) { columns = new List<DisplayColumn>(); pivotDisplayColumns.Add(value, columns); } columns.Add(displayColumn); } } var allPivotKeys = pivotDisplayColumns.Keys.ToArray(); Array.Sort(allPivotKeys, PivotKey.GetComparer(ViewInfo.DataSchema)); foreach (var pivotKey in allPivotKeys) { foreach (var pivotColumn in pivotDisplayColumns[pivotKey]) { var qualifiedPropertyPath = PivotKey.QualifyPropertyPath(pivotKey, pivotColumn.PropertyPath); var columnName = MakeUniqueName(columnNames, qualifiedPropertyPath); propertyDescriptors.Add(new ColumnPropertyDescriptor(pivotColumn, columnName, qualifiedPropertyPath, pivotKey)); } } return propertyDescriptors; } private string MakeUniqueName(HashSet<string> columnNames, PropertyPath propertyPath) { return MakeUniqueName(columnNames, "COLUMN_" + propertyPath); // Not L10N } private string MakeUniqueName(HashSet<string> existingNames, string baseName) { string columnName = baseName; for (int index = 1; !existingNames.Add(columnName); index++) { columnName = baseName + index; } return columnName; } public class TickCounter { private long _tickCount; public TickCounter(CancellationToken cancellationToken) : this(cancellationToken, long.MaxValue) { } public TickCounter(CancellationToken cancellationToken, long maxTickCount) { CancellationToken = cancellationToken; MaxTickCount = maxTickCount; } public TickCounter(long maxTickCount) : this(CancellationToken.None, maxTickCount) { } public TickCounter() : this(10000000) { } public long TickCount {get { return _tickCount; }} public void Tick() { CancellationToken.ThrowIfCancellationRequested(); if (Interlocked.Increment(ref _tickCount) >= MaxTickCount) { throw new OperationCanceledException(string.Format("Number of steps exceeded {0}", MaxTickCount)); // Not L10N } } public long MaxTickCount { get; private set; } public CancellationToken CancellationToken { get; private set; } } } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System.Linq; using System.Reflection; using Glass.Mapper.Sc.CodeFirst; using Glass.Mapper.Sc.Configuration; using Glass.Mapper.Sc.Configuration.Fluent; using Glass.Mapper.Sc.FakeDb.CodeFirst.Templates.Level1; using Glass.Mapper.Sc.FakeDb.CodeFirst.Templates.Level1.Level2; using NUnit.Framework; using Sitecore; using Sitecore.Collections; using Sitecore.Configuration; using Sitecore.Data; using Sitecore.Data.DataProviders; using Sitecore.FakeDb; using Sitecore.FakeDb.Data.DataProviders; using Sitecore.SecurityModel; namespace Glass.Mapper.Sc.FakeDb.CodeFirst { [TestFixture] public class GlassDataProviderFixture { private SecurityDisabler _disabler; private Database _datebase; private GlassDataProvider _dataProvider; private Context _context; private Db _db; [SetUp] public void Setup() { _db = new Db { }; _disabler = new SecurityDisabler(); _datebase = _db.Database; _dataProvider = new GlassDataProvider("master", Context.DefaultContextName); GlassDataProvider.GetSqlProviderFunc = providers => providers.FirstOrDefault(x => x is FakeDataProvider); _context = Context.Create(Utilities.CreateStandardResolver()); //GlassDataProvider._setupComplete = false; InjectionDataProvider(_datebase, _dataProvider); } [TearDown] public void TearDown() { var providers = GetProviders(_datebase); var toRemove = providers.Where(x => x is GlassDataProvider).ToList(); toRemove.ForEach(x => providers.Remove(x)); var path = "/sitecore/templates/glasstemplates"; var rootFolder = _datebase.GetItem(path); if (rootFolder != null) rootFolder.Delete(); _disabler.Dispose(); _datebase = null; _dataProvider = null; _disabler = null; } [Test] [Category("LocalOnly")] public void GlassDataProvider_ReturnsGlassTemplateFolder() { //Assign _dataProvider.Initialise(_datebase); var path = "/sitecore/templates/glasstemplates"; _datebase.Caches.DataCache.Clear(); _datebase.Caches.ItemCache.Clear(); _datebase.Caches.ItemPathsCache.Clear(); _datebase.Caches.StandardValuesCache.Clear(); _datebase.Caches.PathCache.Clear(); //Act var folder = _datebase.GetItem(path); //Assert Assert.AreEqual(folder.Name, "GlassTemplates"); } [Test] [Category("LocalOnly")] public void GlassDataProvider_ReturnsTemplate() { //Assign var loader = new SitecoreFluentConfigurationLoader(); loader.Add<CodeFirstClass1>() .TemplateId("D3595652-AC29-4BD4-A8D7-DD2120EE6460") .TemplateName("CodeFirstClass1") .CodeFirst(); _context.Load(loader); var path = "/sitecore/templates/glasstemplates/CodeFirstClass1"; _dataProvider.Initialise(_datebase); //Act var folder = _datebase.GetItem(path); //Assert Assert.AreEqual(folder.Name, "CodeFirstClass1"); } [Test] [Category("LocalOnly")] public void GlassDataProvider_TemplateInNamespace_ReturnsTemplate() { //Assign var loader = new SitecoreFluentConfigurationLoader(); loader.Add<CodeFirstClass2>() .TemplateId("E33F1C58-FAB2-475A-B2FE-C26F5D7565A2") .TemplateName("CodeFirstClass2") .CodeFirst(); _context.Load(loader); var path = "/sitecore/templates/glasstemplates/Level1/CodeFirstClass2"; _dataProvider.Initialise(_datebase); //Act var folder = _datebase.GetItem(path); string xml = Factory.GetConfiguration().OuterXml; //Assert Assert.AreEqual(folder.Name, "CodeFirstClass2"); } [Test] [Category("LocalOnly")] public void GlassDataProvider_TemplateInNamespaceTwoDeep_ReturnsTemplate() { //Assign var loader = new SitecoreFluentConfigurationLoader(); loader.Add<CodeFirstClass3>() .TemplateId("E33F1C58-FAB2-475A-B2FE-C26F5D7565A2") .TemplateName("CodeFirstClass2") .CodeFirst(); _context.Load(loader); var path = "/sitecore/templates/glasstemplates/Level1/Level2/CodeFirstClass2"; _dataProvider.Initialise(_datebase); //Act var folder = _datebase.GetItem(path); string xml = Factory.GetConfiguration().OuterXml; //Assert Assert.AreEqual(folder.Name, "CodeFirstClass2"); } [Test] [Category("LocalOnly")] public void GlassDataProvider_TemplateInNamespaceTwoDeep_ReturnsTemplateTwoTemplates() { //Assign var loader = new SitecoreFluentConfigurationLoader(); loader.Add<CodeFirstClass3>() .TemplateId("E33F1C58-FAB2-475A-B2FE-C26F5D7565A2") .TemplateName("CodeFirstClass3") .CodeFirst(); loader.Add<CodeFirstClass4>() .TemplateId("{42B45E08-20A4-434B-8AC7-ED8ABCE5B3BE}") .TemplateName("CodeFirstClass4") .CodeFirst(); _context.Load(loader); var path1 = "/sitecore/templates/glasstemplates/Level1/Level2/CodeFirstClass3"; var path2 = "/sitecore/templates/glasstemplates/Level1/Level2/CodeFirstClass4"; _dataProvider.Initialise(_datebase); //Act var template1 = _datebase.GetItem(path1); var template2 = _datebase.GetItem(path2); //Assert Assert.AreEqual(template1.Name, "CodeFirstClass3"); Assert.AreEqual(template2.Name, "CodeFirstClass4"); } [Test] [Category("LocalOnly")] public void GlassDataProvider_ReturnsTemplateWithSectionAndField() { //Assign var loader = new SitecoreFluentConfigurationLoader(); loader.Add<CodeFirstClass1>() .TemplateId("D3595652-AC29-4BD4-A8D7-DD2120EE6460") .TemplateName("CodeFirstClass1") .CodeFirst() .Fields(x => x.Field(y => y.Field1) .IsCodeFirst() .FieldId("32FE1520-EAD4-4CF8-A69F-A4717E2F07F6") .SectionName("TestSection") ); _context.Load(loader); var path = "/sitecore/templates/glasstemplates/CodeFirstClass1"; _dataProvider.Initialise(_datebase); //Act var folder = _datebase.GetItem(path); //Assert Assert.AreEqual(folder.Name, "CodeFirstClass1"); var section = folder.Children.FirstOrDefault(x => x.Name == "TestSection"); Assert.IsNotNull(section); var field = section.Children.FirstOrDefault(x => x.Name == "Field1"); Assert.IsNotNull(field); } [Test] [Category("LocalOnly")] public void GlassDataProvider_ReturnsTemplateWithSectionAndField_AllPropertiesSet() { //Assign var loader = new SitecoreFluentConfigurationLoader(); var fieldId = new ID("32FE1520-EAD4-4CF8-A69F-A4717E2F07F6"); var sectionName = "TestSection"; var fieldSortOrder = 123; var fieldName = "FieldName"; var fieldTitle = "TestTitle"; var fieldSource = "/source"; var fieldType = SitecoreFieldType.Date; var sectionSortOrder = 100; var validationErrorText = "TextValidation"; var validationRegEx = "testregex"; loader.Add<CodeFirstClass1>() .TemplateId("D3595652-AC29-4BD4-A8D7-DD2120EE6460") .TemplateName("CodeFirstClass1") .CodeFirst() .Fields(x => x.Field(y => y.Field1) .IsCodeFirst() .FieldId(fieldId.ToString()) .SectionName(sectionName) .FieldSortOrder(fieldSortOrder) .FieldName(fieldName) .FieldSource(fieldSource) .FieldTitle(fieldTitle) .FieldType(fieldType) .IsRequired() .IsShared() .IsUnversioned() .SectionSortOrder(sectionSortOrder) .ValidationErrorText(validationErrorText) .ValidationRegularExpression(validationRegEx) ); _context.Load(loader); var path = "/sitecore/templates/glasstemplates/CodeFirstClass1"; _dataProvider.Initialise(_datebase); //Act var folder = _datebase.GetItem(path); //Assert Assert.AreEqual(folder.Name, "CodeFirstClass1"); var section = folder.Children.FirstOrDefault(x => x.Name == sectionName); Assert.IsNotNull(section); Assert.AreEqual(sectionSortOrder.ToString(), section[FieldIDs.Sortorder]); var field = section.Children.FirstOrDefault(x => x.Name == fieldName); Assert.IsNotNull(field); Assert.AreEqual(fieldSortOrder.ToString(), field[FieldIDs.Sortorder]); Assert.AreEqual(fieldId, field.ID); Assert.AreEqual(fieldSource, field[TemplateFieldIDs.Source]); Assert.AreEqual(fieldTitle, field[TemplateFieldIDs.Title]); Assert.AreEqual(fieldType.ToString(), field[TemplateFieldIDs.Type]); Assert.AreEqual(Global.IDs.TemplateFieldIds.IsRequiredId, field[Global.IDs.TemplateFieldIds.ValidateButtonFieldId]); Assert.AreEqual(Global.IDs.TemplateFieldIds.IsRequiredId, field[Global.IDs.TemplateFieldIds.WorkflowFieldId]); Assert.AreEqual(Global.IDs.TemplateFieldIds.IsRequiredId, field[Global.IDs.TemplateFieldIds.ValidatorBarFieldId]); Assert.AreEqual(Global.IDs.TemplateFieldIds.IsRequiredId, field[Global.IDs.TemplateFieldIds.QuickActionBarFieldId]); Assert.AreEqual("1", field[TemplateFieldIDs.Shared]); Assert.AreEqual("1", field[TemplateFieldIDs.Unversioned]); Assert.AreEqual(validationErrorText, field[TemplateFieldIDs.ValidationText]); Assert.AreEqual(validationRegEx, field[TemplateFieldIDs.Validation]); } public class CodeFirstClass1 { public virtual string Field1 { get; set; } } private void InjectionDataProvider(Database db, DataProvider provider) { var providers = GetProviders(db); providers.Insert(0, provider); //var addMethod = typeof(Database).GetMethod("AddDataProvider", BindingFlags.NonPublic | BindingFlags.Instance); //addMethod.Invoke(db, new[] { provider }); } public DataProviderCollection GetProviders(Database db) { var providersField = typeof(Database).GetField("_dataProviders", BindingFlags.NonPublic | BindingFlags.Instance); var providers = providersField.GetValue(db) as DataProviderCollection; return providers; } } namespace Templates.Level1 { public class CodeFirstClass2 { } } namespace Templates.Level1.Level2 { public class CodeFirstClass3 { } public class CodeFirstClass4 { } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.IdentityModel.Metadata { using System.Collections.Generic; using System.Security.Claims; using SysClaimTypes = System.IdentityModel.Claims.ClaimTypes; /// <summary> /// This class represents the displayable claim object. Usually, the display tag /// and the description are localized. And claimType identifies different claim /// types. The display value is the string representation of the claim.Resource. /// </summary> public class DisplayClaim { static Dictionary<string, string> claimDescriptionMap = PopulateClaimDescriptionMap(); static Dictionary<string, string> claimTagMap = PopulateClaimTagMap(); string claimType; // required, should map to claim.ClaimType string displayTag; // should map to claim's friendly name, sometime called display name string displayValue; // should map to claim.Resource string description; // should map to claim's decription bool optional; // The Optional attribute static Dictionary<string, string> PopulateClaimTagMap() { Dictionary<string, string> map = new Dictionary<string, string>(); // populate _claimTagMap with known values map.Add(ClaimTypes.Country, SR.GetString(SR.CountryText)); map.Add(ClaimTypes.DateOfBirth, SR.GetString(SR.DateOfBirthText)); map.Add(ClaimTypes.Email, SR.GetString(SR.EmailAddressText)); map.Add(ClaimTypes.Gender, SR.GetString(SR.GenderText)); map.Add(ClaimTypes.GivenName, SR.GetString(SR.GivenNameText)); map.Add(ClaimTypes.HomePhone, SR.GetString(SR.HomePhoneText)); map.Add(ClaimTypes.Locality, SR.GetString(SR.LocalityText)); map.Add(ClaimTypes.MobilePhone, SR.GetString(SR.MobilePhoneText)); map.Add(ClaimTypes.Name, SR.GetString(SR.NameText)); map.Add(ClaimTypes.OtherPhone, SR.GetString(SR.OtherPhoneText)); map.Add(ClaimTypes.PostalCode, SR.GetString(SR.PostalCodeText)); map.Add(SysClaimTypes.PPID, SR.GetString(SR.PPIDText)); map.Add(ClaimTypes.StateOrProvince, SR.GetString(SR.StateOrProvinceText)); map.Add(ClaimTypes.StreetAddress, SR.GetString(SR.StreetAddressText)); map.Add(ClaimTypes.Surname, SR.GetString(SR.SurnameText)); map.Add(ClaimTypes.Webpage, SR.GetString(SR.WebPageText)); map.Add(ClaimTypes.Role, SR.GetString(SR.RoleText)); return map; } static Dictionary<string, string> PopulateClaimDescriptionMap() { // populate _claimDescriptionMap with known values Dictionary<string, string> map = new Dictionary<string, string>(); map.Add(ClaimTypes.Country, SR.GetString(SR.CountryDescription)); map.Add(ClaimTypes.DateOfBirth, SR.GetString(SR.DateOfBirthDescription)); map.Add(ClaimTypes.Email, SR.GetString(SR.EmailAddressDescription)); map.Add(ClaimTypes.Gender, SR.GetString(SR.GenderDescription)); map.Add(ClaimTypes.GivenName, SR.GetString(SR.GivenNameDescription)); map.Add(ClaimTypes.HomePhone, SR.GetString(SR.HomePhoneDescription)); map.Add(ClaimTypes.Locality, SR.GetString(SR.LocalityDescription)); map.Add(ClaimTypes.MobilePhone, SR.GetString(SR.MobilePhoneDescription)); map.Add(ClaimTypes.Name, SR.GetString(SR.NameDescription)); map.Add(ClaimTypes.OtherPhone, SR.GetString(SR.OtherPhoneDescription)); map.Add(ClaimTypes.PostalCode, SR.GetString(SR.PostalCodeDescription)); map.Add(SysClaimTypes.PPID, SR.GetString(SR.PPIDDescription)); map.Add(ClaimTypes.StateOrProvince, SR.GetString(SR.StateOrProvinceDescription)); map.Add(ClaimTypes.StreetAddress, SR.GetString(SR.StreetAddressDescription)); map.Add(ClaimTypes.Surname, SR.GetString(SR.SurnameDescription)); map.Add(ClaimTypes.Webpage, SR.GetString(SR.WebPageDescription)); map.Add(ClaimTypes.Role, SR.GetString(SR.RoleDescription)); return map; } static string ClaimTagForClaimType(string claimType) { string tag = null; claimTagMap.TryGetValue(claimType, out tag); return tag; } static string ClaimDescriptionForClaimType(string claimType) { string description = null; claimDescriptionMap.TryGetValue(claimType, out description); return description; } /// <summary> /// Creates a display claim from a given claim type and sets default values /// for DisplayTag and Description properities. /// </summary> /// <param name="claimType">The unique uri identifier of a claim type</param> public static DisplayClaim CreateDisplayClaimFromClaimType(string claimType) { DisplayClaim displayClaim = new DisplayClaim(claimType); displayClaim.DisplayTag = ClaimTagForClaimType(claimType); displayClaim.Description = ClaimDescriptionForClaimType(claimType); return displayClaim; } /// <summary> /// Constructs a display claim object if claimType is known /// </summary> /// <param name="claimType">The unique uri identifier of a claim type</param> public DisplayClaim(string claimType) : this(claimType, null, null, null) { } /// <summary> /// Instantiates a DisplayClaim object. Use this constructor if the actual value of the claim is unknown. /// </summary> /// <param name="claimType">claim.ClaimType, e.g http://.../claims/EmailAddr </param> /// <param name="displayTag">friendly name sometime called display name, e.g. Email address</param> /// <param name="description">the description of this claim, e.g. If a person possess this email address</param> public DisplayClaim(string claimType, string displayTag, string description) : this(claimType, displayTag, description, null) { } /// <summary> /// Instantiates a DisplayClaim object. Use this constructor if the actual value of the claim is known. /// </summary> /// <param name="claimType">claim.ClaimType, e.g http://.../claims/EmailAddr </param> /// <param name="displayTag">friendly name sometime called display name, e.g. Email address</param> /// <param name="description">the description of this claim, e.g. If a person possess this email address</param> /// <param name="displayValue">claim.Resource, e.g. joe@fabrikam.com</param> public DisplayClaim(string claimType, string displayTag, string description, string displayValue) : this(claimType, displayTag, description, displayValue, true) { } /// <summary> /// Instantiates a DisplayClaim object. Use this constructor if the actual value of the claim is known. /// </summary> /// <param name="claimType">claim.ClaimType, e.g http://.../claims/EmailAddr </param> /// <param name="displayTag">friendly name sometime called display name, e.g. Email address</param> /// <param name="description">the description of this claim, e.g. If a person possess this email address</param> /// <param name="displayValue">claim.Resource, e.g. joe@fabrikam.com</param> /// <param name="optional">If the claim is optional.</param> /// <exception cref="ArgumentNullException">If the claim type is empty or null.</exception> public DisplayClaim(string claimType, string displayTag, string description, string displayValue, bool optional) { if (string.IsNullOrEmpty(claimType)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("claimType"); } this.claimType = claimType; this.displayTag = displayTag; this.description = description; this.displayValue = displayValue; this.optional = optional; } /// <summary> /// This required attribute provides the unique identifier (URI) /// of the individual claim returned in the security token /// </summary> public string ClaimType { get { return this.claimType; } } /// <summary> /// This optional element provides a friendly name for the claim /// returned in the security token /// </summary> public string DisplayTag { get { return this.displayTag; } set { this.displayTag = value; } } /// <summary> /// This optional element provides one or more /// displayable values for the claim returned in the security token /// </summary> public string DisplayValue { get { return this.displayValue; } set { this.displayValue = value; } } /// <summary> /// This optional element provides a description of the semantics /// for the claim returned in the security token. /// </summary> public string Description { get { return this.description; } set { this.description = value; } } /// <summary> /// Gets or sets the optional attribute. /// </summary> public bool Optional { get { return this.optional; } set { this.optional = value; } } /// <summary> /// Gets or sets whether the optional attribute will be serialized. The default value is false. /// </summary> public bool WriteOptionalAttribute { get; set; } } }
// // Community.CsharpSqlite.SQLiteClient.SqliteConnectionStringBuilder.cs // // Author(s): // Sureshkumar T (tsureshkumar@novell.com) // Marek Habersack (grendello@gmail.com) // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // Copyright (C) 2007 Marek Habersack // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Globalization; using System.Text; namespace Community.CsharpSqlite.SQLiteClient { public sealed class SqliteConnectionStringBuilder : DbConnectionStringBuilder { private const string DEF_URI = null; private const Int32 DEF_MODE = 0644; private const Int32 DEF_VERSION = 2; private const Encoding DEF_ENCODING = null; private const Int32 DEF_BUSYTIMEOUT = 0; #region // Fields private string _uri; private Int32 _mode; private Int32 _version; private Encoding _encoding; private Int32 _busy_timeout; private static Dictionary <string, string> _keywords; // for mapping duplicate keywords #endregion // Fields #region Constructors public SqliteConnectionStringBuilder () : this (String.Empty) { } public SqliteConnectionStringBuilder (string connectionString) { Init (); base.ConnectionString = connectionString; } static SqliteConnectionStringBuilder () { _keywords = new Dictionary <string, string> (); _keywords ["URI"] = "Uri"; _keywords ["DATA SOURCE"] = "Data Source"; _keywords ["DATASOURCE"] = "Data Source"; _keywords ["URI"] = "Data Source"; _keywords ["MODE"] = "Mode"; _keywords ["VERSION"] = "Version"; _keywords ["BUSY TIMEOUT"] = "Busy Timeout"; _keywords ["BUSYTIMEOUT"] = "Busy Timeout"; _keywords ["ENCODING"] = "Encoding"; } #endregion // Constructors #region Properties public string DataSource { get { return _uri; } set { base ["Data Source"] = value; _uri = value; } } public string Uri { get { return _uri; } set { base ["Data Source"] = value; _uri = value; } } public Int32 Mode { get { return _mode; } set { base ["Mode"] = value; _mode = value; } } public Int32 Version { get { return _version; } set { base ["Version"] = value; _version = value; } } public Int32 BusyTimeout { get { return _busy_timeout; } set { base ["Busy Timeout"] = value; _busy_timeout = value; } } public Encoding Encoding { get { return _encoding; } set { base ["Encoding"] = value; _encoding = value; } } public override bool IsFixedSize { get { return true; } } public override object this [string keyword] { get { string mapped = MapKeyword (keyword); return base [mapped]; } set {SetValue (keyword, value);} } public override ICollection Keys { get { return base.Keys; } } public override ICollection Values { get { return base.Values; } } #endregion // Properties #region Methods private void Init () { _uri = DEF_URI; _mode = DEF_MODE; _version = DEF_VERSION; _encoding = DEF_ENCODING; _busy_timeout = DEF_BUSYTIMEOUT; } public override void Clear () { base.Clear (); Init (); } public override bool ContainsKey (string keyword) { keyword = keyword.ToUpper ().Trim (); if (_keywords.ContainsKey (keyword)) return base.ContainsKey (_keywords [keyword]); return false; } public override bool Remove (string keyword) { if (!ContainsKey (keyword)) return false; this [keyword] = null; return true; } public override bool TryGetValue (string keyword, out object value) { if (! ContainsKey (keyword)) { value = String.Empty; return false; } return base.TryGetValue (_keywords [keyword.ToUpper ().Trim ()], out value); } #endregion // Methods #region Private Methods private string MapKeyword (string keyword) { keyword = keyword.ToUpper ().Trim (); if (! _keywords.ContainsKey (keyword)) throw new ArgumentException("Keyword not supported :" + keyword); return _keywords [keyword]; } private void SetValue (string key, object value) { if (key == null) throw new ArgumentNullException ("key cannot be null!"); string mappedKey = MapKeyword (key); switch (mappedKey.ToUpper (CultureInfo.InvariantCulture).Trim ()) { case "DATA SOURCE": if (value == null) { _uri = DEF_URI; base.Remove (mappedKey); } else this.Uri = value.ToString (); break; case "MODE": if (value == null) { _mode = DEF_MODE; base.Remove (mappedKey); } else this.Mode = ConvertToInt32 (value); break; case "VERSION": if (value == null) { _version = DEF_MODE; base.Remove (mappedKey); } else this.Version = ConvertToInt32 (value); break; case "BUSY TIMEOUT": if (value == null) { _busy_timeout = DEF_BUSYTIMEOUT; base.Remove (mappedKey); } else this.BusyTimeout = ConvertToInt32 (value); break; case "ENCODING" : if (value == null) { _encoding = DEF_ENCODING; base.Remove (mappedKey); } else if (value is string) { this.Encoding = Encoding.GetEncoding ((string) value); } else throw new ArgumentException ("Cannot set encoding from a non-string argument"); break; default : throw new ArgumentException("Keyword not supported :" + key); } } static int ConvertToInt32 (object value) { return Int32.Parse (value.ToString (), CultureInfo.InvariantCulture); } static bool ConvertToBoolean (object value) { if (value == null) throw new ArgumentNullException ("null value cannot be converted to boolean"); string upper = value.ToString ().ToUpper ().Trim (); if (upper == "YES" || upper == "TRUE") return true; if (upper == "NO" || upper == "FALSE") return false; throw new ArgumentException (String.Format ("Invalid boolean value: {0}", value.ToString ())); } #endregion // Private Methods } }
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Ads.AdManager.Lib; using Google.Api.Ads.AdManager.Util.v202202; using Google.Api.Ads.AdManager.v202202; using System; namespace Google.Api.Ads.AdManager.Examples.CSharp.v202202 { /// <summary> /// This code example creates a new line item to serve to video content. To /// determine which line items exist, run GetAllLineItems.cs. To determine /// which orders exist, run GetAllOrders.cs. To create a video ad unit, run /// CreateVideoAdUnit.cs. To determine which content metadata key hierarchies /// exist, run GetAllContentMetadataKeyHierarchies.cs. /// </summary> public class CreateVideoLineItem : SampleBase { /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get { return "This code example creates a new line item to serve to video content. " + "To determine which line items exist, run GetAllLineItems.cs. To determine " + "which orders exist, run GetAllOrders.cs. To create a video ad unit, " + "run CreateVideoAdUnit.cs. To determine which content metadata key " + "hierarchies exist, run GetAllContentMetadataKeyHierarchies.cs"; } } /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> public static void Main() { CreateVideoLineItem codeExample = new CreateVideoLineItem(); Console.WriteLine(codeExample.Description); codeExample.Run(new AdManagerUser()); } /// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { using (LineItemService lineItemService = user.GetService<LineItemService>()) { // Set the order that all created line items will belong to and the // video ad unit ID to target. long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE")); string targetedVideoAdUnitId = _T("INSERT_TARGETED_VIDEO_AD_UNIT_ID_HERE"); // Set the content bundle to target long contentBundleId = long.Parse(_T("INSERT_CONTENT_BUNDLE_ID_HERE")); // Set the CMS metadata value to target long cmsMetadataValueId = long.Parse(_T("INSERT_CMS_METADATA_VALUE_ID_HERE")); // Create content targeting. ContentTargeting contentTargeting = new ContentTargeting() { targetedVideoContentBundleIds = new long[] { contentBundleId } }; // Create inventory targeting. InventoryTargeting inventoryTargeting = new InventoryTargeting() { targetedAdUnits = new AdUnitTargeting[] { new AdUnitTargeting() { adUnitId = targetedVideoAdUnitId, includeDescendants = true } } }; // Create video position targeting. VideoPositionTargeting videoPositionTargeting = new VideoPositionTargeting() { targetedPositions = new VideoPositionTarget[] { new VideoPositionTarget() { videoPosition = new VideoPosition() { positionType = VideoPositionType.PREROLL } } } }; // Target only video platforms RequestPlatformTargeting requestPlatformTargeting = new RequestPlatformTargeting() { targetedRequestPlatforms = new RequestPlatform[] { RequestPlatform.VIDEO_PLAYER } }; // Create custom criteria set CustomCriteriaSet customCriteriaSet = new CustomCriteriaSet() { logicalOperator = CustomCriteriaSetLogicalOperator.AND, children = new CustomCriteriaNode[] { new CmsMetadataCriteria() { cmsMetadataValueIds = new long[] { cmsMetadataValueId }, @operator = CmsMetadataCriteriaComparisonOperator.EQUALS } } }; // Create targeting. Targeting targeting = new Targeting() { contentTargeting = contentTargeting, inventoryTargeting = inventoryTargeting, videoPositionTargeting = videoPositionTargeting, requestPlatformTargeting = requestPlatformTargeting, customTargeting = customCriteriaSet }; // Create local line item object. LineItem lineItem = new LineItem() { name = "Video line item - " + this.GetTimeStamp(), orderId = orderId, targeting = targeting, lineItemType = LineItemType.SPONSORSHIP, allowOverbook = true, environmentType = EnvironmentType.VIDEO_PLAYER, creativeRotationType = CreativeRotationType.OPTIMIZED, // Set the maximum video creative length for this line item to 15 seconds. videoMaxDuration = 15000L }; // Create the master creative placeholder. CreativePlaceholder creativeMasterPlaceholder = new CreativePlaceholder() { size = new Size() { width = 400, height = 300, isAspectRatio = false } }; // Create companion creative placeholders. CreativePlaceholder companionCreativePlaceholder1 = new CreativePlaceholder() { size = new Size() { width = 300, height = 250, isAspectRatio = false } }; CreativePlaceholder companionCreativePlaceholder2 = new CreativePlaceholder() { size = new Size() { width = 728, height = 90, isAspectRatio = false } }; // Set companion creative placeholders. creativeMasterPlaceholder.companions = new CreativePlaceholder[] { companionCreativePlaceholder1, companionCreativePlaceholder2 }; // Set the size of creatives that can be associated with this line item. lineItem.creativePlaceholders = new CreativePlaceholder[] { creativeMasterPlaceholder }; // Set delivery of video companions to optional. lineItem.companionDeliveryOption = CompanionDeliveryOption.OPTIONAL; // Set the line item to run for one month. lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY; lineItem.endDateTime = DateTimeUtilities.FromDateTime(System.DateTime.Now.AddMonths(1), "America/New_York"); // Set the cost per day to $1. lineItem.costType = CostType.CPD; lineItem.costPerUnit = new Money() { currencyCode = "USD", microAmount = 1000000L }; // Set the percentage to be 100%. lineItem.primaryGoal = new Goal() { goalType = GoalType.DAILY, unitType = UnitType.IMPRESSIONS, units = 100 }; try { // Create the line item on the server. LineItem[] createdLineItems = lineItemService.createLineItems(new LineItem[] { lineItem }); foreach (LineItem createdLineItem in createdLineItems) { Console.WriteLine( "A line item with ID \"{0}\", belonging to order ID \"{1}\", and " + "named \"{2}\" was created.", createdLineItem.id, createdLineItem.orderId, createdLineItem.name); } } catch (Exception e) { Console.WriteLine("Failed to create line items. Exception says \"{0}\"", e.Message); } } } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using Nini.Config; using OpenMetaverse; using Aurora.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; namespace Aurora.Modules.Chat { public class InstantMessageModule : ISharedRegionModule { private readonly List<IScene> m_scenes = new List<IScene>(); private IMessageTransferModule m_TransferModule; /// <value> /// Is this module enabled? /// </value> private bool m_enabled; #region ISharedRegionModule Members public void Initialise(IConfigSource config) { if (config.Configs["Messaging"] != null) { if (config.Configs["Messaging"].GetString( "InstantMessageModule", "InstantMessageModule") != "InstantMessageModule") return; } m_enabled = true; } public void AddRegion(IScene scene) { if (!m_enabled) return; lock (m_scenes) { m_scenes.Add(scene); scene.EventManager.OnNewClient += EventManager_OnNewClient; scene.EventManager.OnClosingClient += EventManager_OnClosingClient; scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; } } public void RegionLoaded(IScene scene) { if (!m_enabled) return; if (m_TransferModule == null) { m_TransferModule = scene.RequestModuleInterface<IMessageTransferModule>(); if (m_TransferModule == null) { MainConsole.Instance.Error("[INSTANT MESSAGE]: No message transfer module, IM will not work!"); scene.EventManager.OnNewClient -= EventManager_OnNewClient; scene.EventManager.OnClosingClient -= EventManager_OnClosingClient; scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage; m_scenes.Clear(); m_enabled = false; } } } public void RemoveRegion(IScene scene) { if (!m_enabled) return; lock (m_scenes) m_scenes.Remove(scene); } public void PostInitialise() { } public void Close() { } public string Name { get { return "InstantMessageModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion private void EventManager_OnClosingClient(IClientAPI client) { //client.OnInstantMessage -= OnInstantMessage; } private void EventManager_OnNewClient(IClientAPI client) { client.OnInstantMessage += OnInstantMessage; } public void OnInstantMessage(IClientAPI client, GridInstantMessage im) { byte dialog = im.dialog; if (dialog != (byte) InstantMessageDialog.MessageFromAgent && dialog != (byte) InstantMessageDialog.StartTyping && dialog != (byte) InstantMessageDialog.StopTyping && dialog != (byte) InstantMessageDialog.BusyAutoResponse && dialog != (byte) InstantMessageDialog.MessageFromObject) { return; } if (m_TransferModule != null) { if (client == null) { UserAccount account = m_scenes[0].UserAccountService.GetUserAccount(m_scenes[0].RegionInfo.ScopeID, im.fromAgentID); if (account != null) im.fromAgentName = account.Name; else im.fromAgentName = im.fromAgentName + "(No account found for this user)"; } else im.fromAgentName = client.Name; m_TransferModule.SendInstantMessage(im); } } ///<summary> ///</summary> ///<param name = "msg"></param> private void OnGridInstantMessage(GridInstantMessage msg) { byte dialog = msg.dialog; if (dialog != (byte) InstantMessageDialog.MessageFromAgent && dialog != (byte) InstantMessageDialog.StartTyping && dialog != (byte) InstantMessageDialog.StopTyping && dialog != (byte) InstantMessageDialog.MessageFromObject) { return; } if (m_TransferModule != null) { UserAccount account = m_scenes[0].UserAccountService.GetUserAccount(m_scenes[0].RegionInfo.ScopeID, msg.fromAgentID); if (account != null) msg.fromAgentName = account.Name; else msg.fromAgentName = msg.fromAgentName + "(No account found for this user)"; foreach (IScene scene in m_scenes) { IScenePresence presence = null; if (scene.TryGetScenePresence(msg.toAgentID, out presence)) { presence.ControllingClient.SendInstantMessage(msg); return; } } if (dialog == (uint) InstantMessageDialog.StartTyping || dialog == (uint) InstantMessageDialog.StopTyping || dialog == (uint) InstantMessageDialog.MessageFromObject) { return; } } } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Collections; using System.Linq; using System.Reflection; using System.Text; using OpenMetaverse; using Aurora.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes.Serialization; namespace OpenSim.Region.Framework.Scenes { public class SceneObjectPartInventory : IEntityInventory { private string m_inventoryFileName = String.Empty; private byte[] m_fileData = new byte[0]; private uint m_inventoryFileNameSerial = 0; /// <value> /// The part to which the inventory belongs. /// </value> private readonly SceneObjectPart m_part; /// <summary> /// Serial count for inventory file , used to tell if inventory has changed /// no need for this to be part of Database backup /// </summary> protected uint m_inventorySerial = 0; /// <summary> /// Holds in memory prim inventory /// </summary> protected TaskInventoryDictionary m_items = new TaskInventoryDictionary(); protected object m_itemsLock = new object(); /// <summary> /// Tracks whether inventory has changed since the last persistent backup /// </summary> internal bool m_HasInventoryChanged; public bool HasInventoryChanged { get { return m_HasInventoryChanged; } set { //Set the parent as well so that backup will occur if (value && m_part.ParentGroup != null) m_part.ParentGroup.HasGroupChanged = true; m_HasInventoryChanged = value; } } /// <value> /// Inventory serial number /// </value> protected internal uint Serial { get { return m_inventorySerial; } set { m_inventorySerial = value; } } /// <value> /// Raw inventory data /// </value> protected internal TaskInventoryDictionary Items { get { return m_items; } set { m_items = value; m_inventorySerial++; } } /// <summary> /// Constructor /// </summary> /// <param name="part"> /// A <see cref="SceneObjectPart"/> /// </param> public SceneObjectPartInventory(SceneObjectPart part) { m_part = part; } /// <summary> /// Force the task inventory of this prim to persist at the next update sweep /// </summary> public void ForceInventoryPersistence() { HasInventoryChanged = true; } /// <summary> /// Reset UUIDs for all the items in the prim's inventory. This involves either generating /// new ones or setting existing UUIDs to the correct parent UUIDs. /// /// If this method is called and there are inventory items, then we regard the inventory as having changed. /// </summary> ///<param name="ChangeScripts"></param> public void ResetInventoryIDs (bool ChangeScripts) { if (null == m_part || null == m_part.ParentGroup) return; if (0 == m_items.Count) return; IList<TaskInventoryItem> items = GetInventoryItems (); lock (m_itemsLock) { m_items.Clear (); foreach (TaskInventoryItem item in items) { //UUID oldItemID = item.ItemID; item.ResetIDs (m_part.UUID); m_items.Add (item.ItemID, item); //LEAVE THIS COMMENTED!!! // When an object is duplicated, this will be called and it will destroy the original prims scripts!! // This needs to be moved to a place that is safer later // This was *originally* intended to be used on scripts that were crossing region borders /*if (m_part.ParentGroup != null) { lock (m_part.ParentGroup) { if (m_part.ParentGroup.Scene != null) { foreach (IScriptModule engine in m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>()) { engine.UpdateScriptToNewObject(oldItemID, item, m_part); } } } }*/ } HasInventoryChanged = true; } } public void ResetObjectID () { if (Items.Count == 0) { return; } lock (m_itemsLock) { HasInventoryChanged = true; if (m_part.ParentGroup != null) { m_part.ParentGroup.HasGroupChanged = true; } IList<TaskInventoryItem> items = Items.Values.ToList(); Items.Clear (); foreach (TaskInventoryItem item in items) { //UUID oldItemID = item.ItemID; item.ResetIDs (m_part.UUID); //LEAVE THIS COMMENTED!!! // When an object is duplicated, this will be called and it will destroy the original prims scripts!! // This needs to be moved to a place that is safer later // This was *originally* intended to be used on scripts that were crossing region borders /*if (m_part.ParentGroup != null) { lock (m_part.ParentGroup) { if (m_part.ParentGroup.Scene != null) { foreach (IScriptModule engine in m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>()) { engine.UpdateScriptToNewObject(oldItemID, item, m_part); } } } }*/ item.ResetIDs (m_part.UUID); Items.Add (item.ItemID, item); } } } /// <summary> /// Change every item in this inventory to a new owner. /// </summary> /// <param name="ownerId"></param> public void ChangeInventoryOwner(UUID ownerId) { lock (Items) { if (0 == Items.Count) { return; } } HasInventoryChanged = true; List<TaskInventoryItem> items = GetInventoryItems(); foreach (TaskInventoryItem item in items) { if (ownerId != item.OwnerID) { item.LastOwnerID = item.OwnerID; item.OwnerChanged = true; item.OwnerID = ownerId; item.PermsMask = 0; item.PermsGranter = UUID.Zero; } } } /// <summary> /// Change every item in this inventory to a new group. /// </summary> /// <param name="groupID"></param> public void ChangeInventoryGroup(UUID groupID) { lock (Items) { if (0 == Items.Count) { return; } } HasInventoryChanged = true; List<TaskInventoryItem> items = GetInventoryItems(); foreach (TaskInventoryItem item in items) { if (groupID != item.GroupID) item.GroupID = groupID; } } /// <summary> /// Start all the scripts contained in this prim's inventory /// </summary> public void CreateScriptInstances (int startParam, bool postOnRez, StateSource stateSource, UUID RezzedFrom) { List<TaskInventoryItem> LSLItems = GetInventoryScripts(); if (LSLItems.Count == 0) return; bool SendUpdate = m_part.AddFlag(PrimFlags.Scripted); m_part.ParentGroup.Scene.EventManager.TriggerRezScripts( m_part, LSLItems.ToArray(), startParam, postOnRez, stateSource, RezzedFrom); if(SendUpdate) m_part.ScheduleUpdate(PrimUpdateFlags.PrimFlags); //We only need to send a compressed ResumeScripts(); } public List<TaskInventoryItem> GetInventoryScripts() { List<TaskInventoryItem> ret = new List<TaskInventoryItem>(); lock (m_items) { #if (!ISWIN) foreach (TaskInventoryItem item in m_items.Values) { if (item.InvType == (int)InventoryType.LSL) { if (!m_part.ParentGroup.Scene.Permissions.CanRunScript(item.ItemID, m_part.UUID, item.OwnerID)) continue; ret.Add(item); } } #else ret.AddRange(m_items.Values.Where(item => item.InvType == (int)InventoryType.LSL).Where(item => m_part.ParentGroup.Scene.Permissions.CanRunScript(item.ItemID, m_part.UUID, item.OwnerID))); #endif } return ret; } public ArrayList GetScriptErrors(UUID itemID) { IScriptModule engine = m_part.ParentGroup.Scene.RequestModuleInterface<IScriptModule>(); if (engine == null) // No engine at all { ArrayList ret = new ArrayList {"No Script Engines available at this time."}; return ret; } return engine.GetScriptErrors(itemID); } /// <summary> /// Stop all the scripts in this prim. /// </summary> /// <param name="sceneObjectBeingDeleted"> /// Should be true if these scripts are being removed because the scene /// object is being deleted. This will prevent spurious updates to the client. /// </param> public void RemoveScriptInstances(bool sceneObjectBeingDeleted) { List<TaskInventoryItem> scripts = GetInventoryScripts(); foreach (TaskInventoryItem item in scripts) RemoveScriptInstance(item.ItemID, sceneObjectBeingDeleted); HasInventoryChanged = true; } /// <summary> /// Start a script which is in this prim's inventory. /// </summary> /// <param name="item"></param> /// <param name="startParam"></param> /// <param name="postOnRez"></param> /// <param name="stateSource"></param> /// <returns></returns> public void CreateScriptInstance (TaskInventoryItem item, int startParam, bool postOnRez, StateSource stateSource) { // MainConsole.Instance.InfoFormat( // "[PRIM INVENTORY]: " + // "Starting script {0}, {1} in prim {2}, {3}", // item.Name, item.ItemID, Name, UUID); if (!m_part.ParentGroup.Scene.Permissions.CanRunScript(item.ItemID, m_part.UUID, item.OwnerID)) return; if (!m_part.ParentGroup.Scene.RegionInfo.RegionSettings.DisableScripts) { lock (m_itemsLock) { m_items[item.ItemID].PermsMask = 0; m_items[item.ItemID].PermsGranter = UUID.Zero; } bool SendUpdate = m_part.AddFlag (PrimFlags.Scripted); m_part.ParentGroup.Scene.EventManager.TriggerRezScripts ( m_part, new[] { item }, startParam, postOnRez, stateSource, UUID.Zero); if (SendUpdate) m_part.ScheduleUpdate (PrimUpdateFlags.PrimFlags); //We only need to send a compressed } HasInventoryChanged = true; ResumeScript(item); } /// <summary> /// Updates a script which is in this prim's inventory. /// </summary> /// <param name="item"></param> /// <returns></returns> public void UpdateScriptInstance (UUID itemID, byte[] assetData, int startParam, bool postOnRez, StateSource stateSource) { TaskInventoryItem item = m_items[itemID]; if (!m_part.ParentGroup.Scene.Permissions.CanRunScript(item.ItemID, m_part.UUID, item.OwnerID)) return; m_part.AddFlag(PrimFlags.Scripted); if (!m_part.ParentGroup.Scene.RegionInfo.RegionSettings.DisableScripts) { lock (m_itemsLock) { m_items[item.ItemID].PermsMask = 0; m_items[item.ItemID].PermsGranter = UUID.Zero; } string script = Utils.BytesToString(assetData); IScriptModule[] modules = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>(); foreach (IScriptModule module in modules) { module.UpdateScript(m_part.UUID, item.ItemID, script, startParam, postOnRez, stateSource); } ResumeScript(item); } HasInventoryChanged = true; } /// <summary> /// Start a script which is in this prim's inventory. /// </summary> /// <param name="itemId"> /// A <see cref="UUID"/> /// </param> /// <param name="startParam"></param> /// <param name="postOnRez"></param> /// <param name="stateSource"></param> public void CreateScriptInstance (UUID itemId, int startParam, bool postOnRez, StateSource stateSource) { TaskInventoryItem item = GetInventoryItem(itemId); if (item != null) CreateScriptInstance(item, startParam, postOnRez, stateSource); else MainConsole.Instance.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't start script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}", itemId, m_part.Name, m_part.UUID, m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); } /// <summary> /// Stop a script which is in this prim's inventory. /// </summary> /// <param name="itemId"></param> /// <param name="sceneObjectBeingDeleted"> /// Should be true if this script is being removed because the scene /// object is being deleted. This will prevent spurious updates to the client. /// </param> public void RemoveScriptInstance(UUID itemId, bool sceneObjectBeingDeleted) { bool scriptPresent = false; lock (m_itemsLock) { if (m_items.ContainsKey (itemId)) scriptPresent = true; } if (scriptPresent) { if (!sceneObjectBeingDeleted) m_part.RemoveScriptEvents(itemId); m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemId); } else { MainConsole.Instance.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't stop script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}", itemId, m_part.Name, m_part.UUID, m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); } } /// <summary> /// Check if the inventory holds an item with a given name. /// </summary> /// <param name="name"></param> /// <returns></returns> private bool InventoryContainsName (string name) { lock (m_itemsLock) { #if (!ISWIN) foreach (TaskInventoryItem item in m_items.Values) { if (item.Name == name) { return true; } } #else if (m_items.Values.Any(item => item.Name == name)) { return true; } #endif } return false; } /// <summary> /// For a given item name, return that name if it is available. Otherwise, return the next available /// similar name (which is currently the original name with the next available numeric suffix). /// </summary> /// <param name="name"></param> /// <returns></returns> private string FindAvailableInventoryName(string name) { if (!InventoryContainsName(name)) return name; int suffix=1; while (suffix < 256) { string tryName=String.Format("{0} {1}", name, suffix); if (!InventoryContainsName(tryName)) return tryName; suffix++; } return String.Empty; } /// <summary> /// Add an item to this prim's inventory. If an item with the same name already exists, then an alternative /// name is chosen. /// </summary> /// <param name="item"></param> /// <param name="allowedDrop"></param> public void AddInventoryItem(TaskInventoryItem item, bool allowedDrop) { AddInventoryItem(item.Name, item, allowedDrop); } /// <summary> /// Add an item to this prim's inventory. If an item with the same name already exists, it is replaced. /// </summary> /// <param name="item"></param> /// <param name="allowedDrop"></param> public void AddInventoryItemExclusive(TaskInventoryItem item, bool allowedDrop) { List<TaskInventoryItem> il = GetInventoryItems(); foreach (TaskInventoryItem i in il) { if (i.Name == item.Name) { if (i.InvType == (int)InventoryType.LSL) RemoveScriptInstance(i.ItemID, false); RemoveInventoryItem(i.ItemID); break; } } AddInventoryItem(item.Name, item, allowedDrop); } /// <summary> /// Add an item to this prim's inventory. /// </summary> /// <param name="name">The name that the new item should have.</param> /// <param name="item"> /// The item itself. The name within this structure is ignored in favour of the name /// given in this method's arguments /// </param> /// <param name="allowedDrop"> /// Item was only added to inventory because AllowedDrop is set /// </param> protected void AddInventoryItem(string name, TaskInventoryItem item, bool allowedDrop) { name = FindAvailableInventoryName(name); if (name == String.Empty) return; item.ParentID = m_part.UUID; item.ParentPartID = m_part.UUID; item.Name = name; item.GroupID = m_part.GroupID; lock (m_itemsLock) { m_items.Add (item.ItemID, item); } m_part.TriggerScriptChangedEvent(allowedDrop ? Changed.ALLOWED_DROP : Changed.INVENTORY); m_inventorySerial++; //m_inventorySerial += 2; HasInventoryChanged = true; } /// <summary> /// Restore a whole collection of items to the prim's inventory at once. /// We assume that the items already have all their fields correctly filled out. /// The items are not flagged for persistence to the database, since they are being restored /// from persistence rather than being newly added. /// </summary> /// <param name="items"></param> public void RestoreInventoryItems (ICollection<TaskInventoryItem> items) { lock (m_itemsLock) { foreach (TaskInventoryItem item in items) { m_items.Add (item.ItemID, item); // m_part.TriggerScriptChangedEvent(Changed.INVENTORY); } m_inventorySerial++; } } /// <summary> /// Returns an existing inventory item. Returns the original, so any changes will be live. /// </summary> /// <param name="itemId"></param> /// <returns>null if the item does not exist</returns> public TaskInventoryItem GetInventoryItem(UUID itemId) { TaskInventoryItem item; lock (m_itemsLock) { m_items.TryGetValue (itemId, out item); } return item; } /// <summary> /// Get inventory items by name. /// </summary> /// <param name="name"></param> /// <returns> /// A list of inventory items with that name. /// If no inventory item has that name then an empty list is returned. /// </returns> public IList<TaskInventoryItem> GetInventoryItems (string name) { IList<TaskInventoryItem> items = new List<TaskInventoryItem> (); lock (m_itemsLock) { foreach (TaskInventoryItem item in m_items.Values) { if (item.Name == name) items.Add (item); } } return items; } public ISceneEntity GetRezReadySceneObject (TaskInventoryItem item) { AssetBase rezAsset = m_part.ParentGroup.Scene.AssetService.Get(item.AssetID.ToString()); if (null == rezAsset) { MainConsole.Instance.WarnFormat( "[PRIM INVENTORY]: Could not find asset {0} for inventory item {1} in {2}", item.AssetID, item.Name, m_part.Name); return null; } string xmlData = Utils.BytesToString(rezAsset.Data); SceneObjectGroup group = SceneObjectSerializer.FromOriginalXmlFormat(xmlData, m_part.ParentGroup.Scene); if (group == null) return null; group.IsDeleted = false; group.m_isLoaded = true; foreach (SceneObjectPart part in group.ChildrenList) { part.IsLoading = false; } //Reset IDs, etc m_part.ParentGroup.Scene.SceneGraph.PrepPrimForAdditionToScene(group); SceneObjectPart rootPart = (SceneObjectPart)group.GetChildPart(group.UUID); // Since renaming the item in the inventory does not affect the name stored // in the serialization, transfer the correct name from the inventory to the // object itself before we rez. rootPart.Name = item.Name; rootPart.Description = item.Description; SceneObjectPart[] partList = group.Parts; group.SetGroup(m_part.GroupID, group.OwnerID, false); if ((rootPart.OwnerID != item.OwnerID) || (item.CurrentPermissions & 16) != 0) { if (m_part.ParentGroup.Scene.Permissions.PropagatePermissions()) { foreach (SceneObjectPart part in partList) { part.EveryoneMask = item.EveryonePermissions; part.NextOwnerMask = item.NextPermissions; } group.ApplyNextOwnerPermissions(); } } foreach (SceneObjectPart part in partList) { if ((part.OwnerID != item.OwnerID) || (item.CurrentPermissions & 16) != 0) { part.LastOwnerID = part.OwnerID; part.OwnerID = item.OwnerID; part.Inventory.ChangeInventoryOwner(item.OwnerID); } part.EveryoneMask = item.EveryonePermissions; part.NextOwnerMask = item.NextPermissions; } rootPart.TrimPermissions(); return group; } /// <summary> /// Update an existing inventory item. /// </summary> /// <param name="item">The updated item. An item with the same id must already exist /// in this prim's inventory.</param> /// <returns>false if the item did not exist, true if the update occurred successfully</returns> public bool UpdateInventoryItem(TaskInventoryItem item) { return UpdateInventoryItem(item, true); } public bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents) { TaskInventoryItem it = GetInventoryItem(item.ItemID); if (it != null) { item.ParentID = m_part.UUID; item.ParentPartID = m_part.UUID; item.Flags = m_items[item.ItemID].Flags; // If group permissions have been set on, check that the groupID is up to date in case it has // changed since permissions were last set. if (item.GroupPermissions != (uint)PermissionMask.None) item.GroupID = m_part.GroupID; if (item.AssetID == UUID.Zero) item.AssetID = it.AssetID; lock (m_itemsLock) { m_items[item.ItemID] = item; m_inventorySerial++; } if (fireScriptEvents) m_part.TriggerScriptChangedEvent(Changed.INVENTORY); HasInventoryChanged = true; return true; } MainConsole.Instance.ErrorFormat( "[PRIM INVENTORY]: " + "Tried to retrieve item ID {0} from prim {1}, {2} at {3} in {4} but the item does not exist in this inventory", item.ItemID, m_part.Name, m_part.UUID, m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); return false; } /// <summary> /// Remove an item from this prim's inventory /// </summary> /// <param name="itemID"></param> /// <returns>Numeric asset type of the item removed. Returns -1 if the item did not exist /// in this prim's inventory.</returns> public int RemoveInventoryItem(UUID itemID) { TaskInventoryItem item = GetInventoryItem(itemID); if (item != null) { int type = m_items[itemID].InvType; if (type == 10) // Script { m_part.RemoveScriptEvents(itemID); m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemID); } m_items.Remove(itemID); m_inventorySerial++; m_part.TriggerScriptChangedEvent(Changed.INVENTORY); HasInventoryChanged = true; if (!ContainsScripts()) { if (m_part.RemFlag(PrimFlags.Scripted)) m_part.ScheduleUpdate(PrimUpdateFlags.PrimFlags); } return type; } return -1; } /// <summary> /// Returns true if the file needs to be rebuild, false if it does not /// </summary> /// <returns></returns> public bool GetInventoryFileName() { if (m_inventoryFileName == String.Empty || m_inventoryFileNameSerial < m_inventorySerial) { m_inventoryFileName = "inventory_" + UUID.Random().ToString() + ".tmp"; m_inventoryFileNameSerial = m_inventorySerial; return true; //We had to change the filename, need to rebuild the file } return false; } /// <summary> /// Serialize all the metadata for the items in this prim's inventory ready for sending to the client /// </summary> /// <param name="client"></param> public void RequestInventoryFile(IClientAPI client) { IXfer xferManager = client.Scene.RequestModuleInterface<IXfer> (); if (m_inventorySerial == 0) { //No inventory, no sending client.SendTaskInventory(m_part.UUID, 0, new byte[0]); return; } //If update == true, we need to recreate the file for the client bool Update = GetInventoryFileName(); if (!Update) { //We don't need to update the fileData, so just send the cached info and exit out of this method if (m_fileData.Length > 2) { client.SendTaskInventory (m_part.UUID, (short)m_inventorySerial, Utils.StringToBytes (m_inventoryFileName)); xferManager.AddNewFile(m_inventoryFileName, m_fileData); } else client.SendTaskInventory (m_part.UUID, 0, new byte[0]); return; } // Confusingly, the folder item has to be the object id, while the 'parent id' has to be zero. This matches // what appears to happen in the Second Life protocol. If this isn't the case. then various functionality // isn't available (such as drag from prim inventory to agent inventory) InventoryStringBuilder invString = new InventoryStringBuilder(m_part.UUID, UUID.Zero); bool includeAssets = false; if (m_part.ParentGroup.Scene.Permissions.CanEditObjectInventory(m_part.UUID, client.AgentId)) includeAssets = true; List<TaskInventoryItem> items = m_items.Clone2List(); foreach (TaskInventoryItem item in items) { UUID ownerID = item.OwnerID; const uint everyoneMask = 0; uint baseMask = item.BasePermissions; uint ownerMask = item.CurrentPermissions; uint groupMask = item.GroupPermissions; invString.AddItemStart (); invString.AddNameValueLine ("item_id", item.ItemID.ToString ()); invString.AddNameValueLine ("parent_id", m_part.UUID.ToString ()); invString.AddPermissionsStart (); invString.AddNameValueLine ("base_mask", Utils.UIntToHexString (baseMask)); invString.AddNameValueLine ("owner_mask", Utils.UIntToHexString (ownerMask)); invString.AddNameValueLine ("group_mask", Utils.UIntToHexString (groupMask)); invString.AddNameValueLine ("everyone_mask", Utils.UIntToHexString (everyoneMask)); invString.AddNameValueLine ("next_owner_mask", Utils.UIntToHexString (item.NextPermissions)); invString.AddNameValueLine ("creator_id", item.CreatorID.ToString ()); invString.AddNameValueLine ("owner_id", ownerID.ToString ()); invString.AddNameValueLine ("last_owner_id", item.LastOwnerID.ToString ()); invString.AddNameValueLine ("group_id", item.GroupID.ToString ()); invString.AddSectionEnd (); invString.AddNameValueLine("asset_id", includeAssets ? item.AssetID.ToString() : UUID.Zero.ToString()); invString.AddNameValueLine ("type", TaskInventoryItemHelpers.Types[item.Type]); invString.AddNameValueLine ("inv_type", TaskInventoryItemHelpers.InvTypes[item.InvType]); invString.AddNameValueLine ("flags", Utils.UIntToHexString (item.Flags)); invString.AddSaleStart (); invString.AddNameValueLine ("sale_type", TaskInventoryItemHelpers.SaleTypes[item.SaleType]); invString.AddNameValueLine ("sale_price", item.SalePrice.ToString ()); invString.AddSectionEnd (); invString.AddNameValueLine ("name", item.Name + "|"); invString.AddNameValueLine ("desc", item.Description + "|"); invString.AddNameValueLine ("creation_date", item.CreationDate.ToString ()); invString.AddSectionEnd (); } string str = invString.GetString(); if(str.Length > 0) str = str.Substring(0, str.Length - 1); m_fileData = Utils.StringToBytes(str); //MainConsole.Instance.Debug(Utils.BytesToString(fileData)); //MainConsole.Instance.Debug("[PRIM INVENTORY]: RequestInventoryFile fileData: " + Utils.BytesToString(fileData)); if (m_fileData.Length > 2) { client.SendTaskInventory (m_part.UUID, (short)m_inventorySerial, Utils.StringToBytes (m_inventoryFileName)); xferManager.AddNewFile(m_inventoryFileName, m_fileData); } else client.SendTaskInventory (m_part.UUID, 0, new byte[0]); } public void SaveScriptStateSaves() { IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>(); if (engines != null) { List<TaskInventoryItem> items = GetInventoryItems(); foreach (TaskInventoryItem item in items) { if (item.Type == (int)InventoryType.LSL) { foreach (IScriptModule engine in engines) { if (engine != null) { //NOTE: We will need to save the prim if we do this engine.SaveStateSave(item.ItemID, m_part.UUID); } } } } } } public class InventoryStringBuilder { private StringBuilder BuildString = new StringBuilder(); private bool _hasAddeditems = false; public string GetString() { if (_hasAddeditems) return BuildString.ToString(); return ""; } public InventoryStringBuilder(UUID folderID, UUID parentID) { BuildString.Append("\tinv_object\t0\n\t{\n"); AddNameValueLine("obj_id", folderID.ToString()); AddNameValueLine("parent_id", parentID.ToString()); AddNameValueLine("type", "category"); AddNameValueLine("name", "Contents|"); AddSectionEnd(); } public void AddItemStart() { _hasAddeditems = true; BuildString.Append("\tinv_item\t0\n"); AddSectionStart(); } public void AddPermissionsStart() { BuildString.Append("\tpermissions 0\n"); AddSectionStart(); } public void AddSaleStart() { BuildString.Append("\tsale_info\t0\n"); AddSectionStart(); } protected void AddSectionStart() { BuildString.Append("\t{\n"); } public void AddSectionEnd() { BuildString.Append("\t}\n"); } public void AddLine(string addLine) { BuildString.Append(addLine); } public void AddNameValueLine(string name, string value) { BuildString.Append("\t\t"); BuildString.Append( name + "\t"); BuildString.Append(value + "\n"); } public void Close() { } } public uint MaskEffectivePermissions () { uint mask = 0x7fffffff; lock (m_itemsLock) { foreach (TaskInventoryItem item in m_items.Values) { if (item.InvType != (int)InventoryType.Object) { if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0) mask &= ~((uint)PermissionMask.Copy >> 13); if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0) mask &= ~((uint)PermissionMask.Transfer >> 13); if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0) mask &= ~((uint)PermissionMask.Modify >> 13); } else { if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0) mask &= ~((uint)PermissionMask.Copy >> 13); if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0) mask &= ~((uint)PermissionMask.Transfer >> 13); if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0) mask &= ~((uint)PermissionMask.Modify >> 13); } if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) mask &= ~(uint)PermissionMask.Copy; if ((item.CurrentPermissions & (uint)PermissionMask.Transfer) == 0) mask &= ~(uint)PermissionMask.Transfer; if ((item.CurrentPermissions & (uint)PermissionMask.Modify) == 0) mask &= ~(uint)PermissionMask.Modify; } } return mask; } public void ApplyNextOwnerPermissions () { lock (m_itemsLock) { foreach (TaskInventoryItem item in m_items.Values) { if (item.InvType == (int)InventoryType.Object && (item.CurrentPermissions & 7) != 0) { if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0) item.CurrentPermissions &= ~(uint)PermissionMask.Copy; if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0) item.CurrentPermissions &= ~(uint)PermissionMask.Transfer; if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0) item.CurrentPermissions &= ~(uint)PermissionMask.Modify; } item.CurrentPermissions &= item.NextPermissions; item.BasePermissions &= item.NextPermissions; item.EveryonePermissions &= item.NextPermissions; item.OwnerChanged = true; item.PermsMask = 0; item.PermsGranter = UUID.Zero; } } } public void ApplyGodPermissions (uint perms) { lock (m_itemsLock) { foreach (TaskInventoryItem item in m_items.Values) { item.CurrentPermissions = perms; item.BasePermissions = perms; } } } public bool ContainsScripts () { lock (m_itemsLock) { #if (!ISWIN) foreach (TaskInventoryItem item in m_items.Values) { if (item.InvType == (int) InventoryType.LSL) { return true; } } #else if (m_items.Values.Any(item => item.InvType == (int)InventoryType.LSL)) { return true; } #endif } return false; } public List<UUID> GetInventoryList() { List<UUID> ret = new List<UUID>(); lock (m_itemsLock) { #if (!ISWIN) foreach (TaskInventoryItem item in m_items.Values) ret.Add(item.ItemID); #else ret.AddRange(m_items.Values.Select(item => item.ItemID)); #endif } return ret; } public List<TaskInventoryItem> GetInventoryItems() { List<TaskInventoryItem> ret = new List<TaskInventoryItem>(); lock (m_itemsLock) { ret.AddRange(m_items.Values); } return ret; } public void ResumeScripts() { List<TaskInventoryItem> scripts = GetInventoryScripts(); foreach (TaskInventoryItem item in scripts) { ResumeScript(item); } } private void ResumeScript(TaskInventoryItem item) { IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces<IScriptModule>(); if (engines == null) return; foreach (IScriptModule engine in engines) { if (engine != null) { engine.ResumeScript(item.ItemID); if (item.OwnerChanged) engine.PostScriptEvent(item.ItemID, m_part.UUID, "changed", new Object[] { (int)Changed.OWNER }); item.OwnerChanged = false; } } } } }
// 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.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Sockets.Tests { public class SendReceive { private readonly ITestOutputHelper _log; public SendReceive(ITestOutputHelper output) { _log = output; } private static void SendToRecvFromAsync_Datagram_UDP(IPAddress leftAddress, IPAddress rightAddress) { const int DatagramSize = 256; const int DatagramsToSend = 256; const int AckTimeout = 1000; const int TestTimeout = 30000; var left = new Socket(leftAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp); var leftEventArgs = new SocketAsyncEventArgs(); left.BindToAnonymousPort(leftAddress); var right = new Socket(rightAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp); var rightEventArgs = new SocketAsyncEventArgs(); right.BindToAnonymousPort(rightAddress); var leftEndpoint = (IPEndPoint)left.LocalEndPoint; var rightEndpoint = (IPEndPoint)right.LocalEndPoint; var receiverAck = new ManualResetEventSlim(); var senderAck = new ManualResetEventSlim(); EndPoint receiveRemote = leftEndpoint.Create(leftEndpoint.Serialize()); var receiverFinished = new TaskCompletionSource<bool>(); var receivedChecksums = new uint?[DatagramsToSend]; var receiveBuffer = new byte[DatagramSize]; int receivedDatagrams = -1; Action<int, EndPoint> receiveHandler = null; receiveHandler = (received, remote) => { try { if (receivedDatagrams != -1) { Assert.Equal(DatagramSize, received); Assert.Equal(rightEndpoint, remote); int datagramId = (int)receiveBuffer[0]; Assert.Null(receivedChecksums[datagramId]); receivedChecksums[datagramId] = Fletcher32.Checksum(receiveBuffer, 0, received); receiverAck.Set(); Assert.True(senderAck.Wait(AckTimeout)); senderAck.Reset(); receivedDatagrams++; if (receivedDatagrams == DatagramsToSend) { left.Dispose(); receiverFinished.SetResult(true); return; } } else { receivedDatagrams = 0; } left.ReceiveFromAsync(leftEventArgs, receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, receiveRemote, receiveHandler); } catch (Exception ex) { receiverFinished.SetException(ex); } }; receiveHandler(0, null); var random = new Random(); var senderFinished = new TaskCompletionSource<bool>(); var sentChecksums = new uint[DatagramsToSend]; var sendBuffer = new byte[DatagramSize]; int sentDatagrams = -1; Action<int> sendHandler = null; sendHandler = sent => { try { if (sentDatagrams != -1) { Assert.True(receiverAck.Wait(AckTimeout)); receiverAck.Reset(); senderAck.Set(); Assert.Equal(DatagramSize, sent); sentChecksums[sentDatagrams] = Fletcher32.Checksum(sendBuffer, 0, sent); sentDatagrams++; if (sentDatagrams == DatagramsToSend) { right.Dispose(); senderFinished.SetResult(true); return; } } else { sentDatagrams = 0; } random.NextBytes(sendBuffer); sendBuffer[0] = (byte)sentDatagrams; right.SendToAsync(rightEventArgs, sendBuffer, 0, sendBuffer.Length, SocketFlags.None, leftEndpoint, sendHandler); } catch (Exception ex) { senderFinished.SetException(ex); } }; sendHandler(0); Assert.True(receiverFinished.Task.Wait(TestTimeout)); Assert.True(senderFinished.Task.Wait(TestTimeout)); for (int i = 0; i < DatagramsToSend; i++) { Assert.NotNull(receivedChecksums[i]); Assert.Equal(sentChecksums[i], (uint)receivedChecksums[i]); } } private static void SendRecvAsync_Stream_TCP(IPAddress listenAt, bool useMultipleBuffers) { const int BytesToSend = 123456; const int ListenBacklog = 1; const int LingerTime = 60; const int TestTimeout = 30000; var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp); server.BindToAnonymousPort(listenAt); server.Listen(ListenBacklog); var serverFinished = new TaskCompletionSource<bool>(); int bytesReceived = 0; var receivedChecksum = new Fletcher32(); var serverEventArgs = new SocketAsyncEventArgs(); server.AcceptAsync(serverEventArgs, remote => { Action<int> recvHandler = null; bool first = true; if (!useMultipleBuffers) { var recvBuffer = new byte[256]; recvHandler = received => { if (!first) { if (received == 0) { remote.Dispose(); server.Dispose(); serverFinished.SetResult(true); return; } bytesReceived += received; receivedChecksum.Add(recvBuffer, 0, received); } else { first = false; } remote.ReceiveAsync(serverEventArgs, recvBuffer, 0, recvBuffer.Length, SocketFlags.None, recvHandler); }; } else { var recvBuffers = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[123]), new ArraySegment<byte>(new byte[256], 2, 100), new ArraySegment<byte>(new byte[1], 0, 0), new ArraySegment<byte>(new byte[64], 9, 33) }; recvHandler = received => { if (!first) { if (received == 0) { remote.Dispose(); server.Dispose(); serverFinished.SetResult(true); return; } bytesReceived += received; for (int i = 0, remaining = received; i < recvBuffers.Count && remaining > 0; i++) { ArraySegment<byte> buffer = recvBuffers[i]; int toAdd = Math.Min(buffer.Count, remaining); receivedChecksum.Add(buffer.Array, buffer.Offset, toAdd); remaining -= toAdd; } } else { first = false; } remote.ReceiveAsync(serverEventArgs, recvBuffers, SocketFlags.None, recvHandler); }; } recvHandler(0); }); EndPoint clientEndpoint = server.LocalEndPoint; var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); int bytesSent = 0; var sentChecksum = new Fletcher32(); var clientEventArgs = new SocketAsyncEventArgs(); client.ConnectAsync(clientEventArgs, clientEndpoint, () => { Action<int> sendHandler = null; var random = new Random(); var remaining = BytesToSend; bool first = true; if (!useMultipleBuffers) { var sendBuffer = new byte[512]; sendHandler = sent => { if (!first) { bytesSent += sent; sentChecksum.Add(sendBuffer, 0, sent); remaining -= sent; Assert.True(remaining >= 0); if (remaining == 0) { client.LingerState = new LingerOption(true, LingerTime); client.Dispose(); return; } } else { first = false; } random.NextBytes(sendBuffer); client.SendAsync(clientEventArgs, sendBuffer, 0, Math.Min(sendBuffer.Length, remaining), SocketFlags.None, sendHandler); }; } else { var sendBuffers = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[23]), new ArraySegment<byte>(new byte[256], 2, 100), new ArraySegment<byte>(new byte[1], 0, 0), new ArraySegment<byte>(new byte[64], 9, 9) }; sendHandler = sent => { if (!first) { bytesSent += sent; for (int i = 0, r = sent; i < sendBuffers.Count && r > 0; i++) { ArraySegment<byte> buffer = sendBuffers[i]; int toAdd = Math.Min(buffer.Count, r); sentChecksum.Add(buffer.Array, buffer.Offset, toAdd); r -= toAdd; } remaining -= sent; if (remaining <= 0) { client.LingerState = new LingerOption(true, LingerTime); client.Dispose(); return; } } else { first = false; } for (int i = 0; i < sendBuffers.Count; i++) { random.NextBytes(sendBuffers[i].Array); } client.SendAsync(clientEventArgs, sendBuffers, SocketFlags.None, sendHandler); }; } sendHandler(0); }); Assert.True(serverFinished.Task.Wait(TestTimeout), "Completed within allowed time"); Assert.Equal(bytesSent, bytesReceived); Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum); } private static void SendRecvAsync_TcpListener_TcpClient(IPAddress listenAt) { const int BytesToSend = 123456; const int ListenBacklog = 1; const int LingerTime = 10; const int TestTimeout = 30000; var listener = new TcpListener(listenAt, 0); listener.Start(ListenBacklog); int bytesReceived = 0; var receivedChecksum = new Fletcher32(); Task serverTask = Task.Run(async () => { using (TcpClient remote = await listener.AcceptTcpClientAsync()) using (NetworkStream stream = remote.GetStream()) { var recvBuffer = new byte[256]; for (;;) { int received = await stream.ReadAsync(recvBuffer, 0, recvBuffer.Length); if (received == 0) { break; } bytesReceived += received; receivedChecksum.Add(recvBuffer, 0, received); } } }); int bytesSent = 0; var sentChecksum = new Fletcher32(); Task clientTask = Task.Run(async () => { var clientEndpoint = (IPEndPoint)listener.LocalEndpoint; using (var client = new TcpClient(clientEndpoint.AddressFamily)) { await client.ConnectAsync(clientEndpoint.Address, clientEndpoint.Port); using (NetworkStream stream = client.GetStream()) { var random = new Random(); var sendBuffer = new byte[512]; for (int remaining = BytesToSend, sent = 0; remaining > 0; remaining -= sent) { random.NextBytes(sendBuffer); sent = Math.Min(sendBuffer.Length, remaining); await stream.WriteAsync(sendBuffer, 0, sent); bytesSent += sent; sentChecksum.Add(sendBuffer, 0, sent); } client.LingerState = new LingerOption(true, LingerTime); } } }); Assert.True(Task.WaitAll(new[] { serverTask, clientTask }, TestTimeout)); Assert.Equal(bytesSent, bytesReceived); Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum); } [Fact] public void SendToRecvFromAsync_Single_Datagram_UDP_IPv6() { SendToRecvFromAsync_Datagram_UDP(IPAddress.IPv6Loopback, IPAddress.IPv6Loopback); } [Fact] public void SendToRecvFromAsync_Single_Datagram_UDP_IPv4() { SendToRecvFromAsync_Datagram_UDP(IPAddress.Loopback, IPAddress.Loopback); } [Fact] public void SendRecvAsync_Multiple_Stream_TCP_IPv6() { SendRecvAsync_Stream_TCP(IPAddress.IPv6Loopback, useMultipleBuffers: true); } [Fact] public void SendRecvAsync_Single_Stream_TCP_IPv6() { SendRecvAsync_Stream_TCP(IPAddress.IPv6Loopback, useMultipleBuffers: false); } [Fact] public void SendRecvAsync_TcpListener_TcpClient_IPv6() { SendRecvAsync_TcpListener_TcpClient(IPAddress.IPv6Loopback); } [Fact] public void SendRecvAsync_Multiple_Stream_TCP_IPv4() { SendRecvAsync_Stream_TCP(IPAddress.Loopback, useMultipleBuffers: true); } [Fact] public void SendRecvAsync_Single_Stream_TCP_IPv4() { SendRecvAsync_Stream_TCP(IPAddress.Loopback, useMultipleBuffers: false); } [Fact] public void SendRecvAsync_TcpListener_TcpClient_IPv4() { SendRecvAsync_TcpListener_TcpClient(IPAddress.Loopback); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace SampleWebAPIApp.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Simple JPEG resizer // Copyright (C) 2006-2009, Aleh Dzenisiuk // http://dzenisiuk.info/jpegator/ using System; using System.Drawing; using System.Collections; using System.Windows.Forms; namespace resizer { public class ResizerForm : System.Windows.Forms.Form { private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.SaveFileDialog saveFileDialog; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox sourceFileNameTextBox; private System.Windows.Forms.Button selectSourceButton; private System.Windows.Forms.Label label2; private System.Windows.Forms.Button selectDestinationButton; private System.Windows.Forms.TextBox sourceWidthTextBox; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox sourceHeightTextBox; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.Button goButton; private System.Windows.Forms.ProgressBar progressBar; private System.Windows.Forms.Label label8; private System.Windows.Forms.NumericUpDown destWidthUpDown; private System.Windows.Forms.NumericUpDown destHeightUpDown; private System.Windows.Forms.MainMenu mainMenu1; private System.Windows.Forms.TextBox destinationFileNameTextBox; private System.Windows.Forms.NumericUpDown scaleUpDown; public ResizerForm() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { 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.mainMenu1 = new System.Windows.Forms.MainMenu(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.label1 = new System.Windows.Forms.Label(); this.sourceFileNameTextBox = new System.Windows.Forms.TextBox(); this.selectSourceButton = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.destinationFileNameTextBox = new System.Windows.Forms.TextBox(); this.selectDestinationButton = new System.Windows.Forms.Button(); this.sourceWidthTextBox = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.sourceHeightTextBox = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.goButton = new System.Windows.Forms.Button(); this.progressBar = new System.Windows.Forms.ProgressBar(); this.scaleUpDown = new System.Windows.Forms.NumericUpDown(); this.label8 = new System.Windows.Forms.Label(); this.destWidthUpDown = new System.Windows.Forms.NumericUpDown(); this.destHeightUpDown = new System.Windows.Forms.NumericUpDown(); // // openFileDialog // this.openFileDialog.Filter = "JPEG images (*.JPG; *.JPEG)|*.JPG; *.JPEG"; // // saveFileDialog // this.saveFileDialog.Filter = "JPEG images (*.JPG; *.JPEG)|*.JPG; *.JPEG"; // // label1 // this.label1.Location = new System.Drawing.Point(8, 8); this.label1.Size = new System.Drawing.Size(224, 16); this.label1.Text = "Source file name:"; // // sourceFileNameTextBox // this.sourceFileNameTextBox.Location = new System.Drawing.Point(8, 24); this.sourceFileNameTextBox.ReadOnly = true; this.sourceFileNameTextBox.Size = new System.Drawing.Size(200, 20); this.sourceFileNameTextBox.Text = ""; // // selectSourceButton // this.selectSourceButton.Location = new System.Drawing.Point(208, 24); this.selectSourceButton.Size = new System.Drawing.Size(24, 20); this.selectSourceButton.Text = "..."; this.selectSourceButton.Click += new System.EventHandler(this.selectSourceButton_Click); // // label2 // this.label2.Location = new System.Drawing.Point(8, 88); this.label2.Size = new System.Drawing.Size(224, 16); this.label2.Text = "Destination file name:"; // // destinationFileNameTextBox // this.destinationFileNameTextBox.Location = new System.Drawing.Point(8, 104); this.destinationFileNameTextBox.ReadOnly = true; this.destinationFileNameTextBox.Size = new System.Drawing.Size(200, 20); this.destinationFileNameTextBox.Text = ""; // // selectDestinationButton // this.selectDestinationButton.Location = new System.Drawing.Point(208, 104); this.selectDestinationButton.Size = new System.Drawing.Size(24, 20); this.selectDestinationButton.Text = "..."; // // sourceWidthTextBox // this.sourceWidthTextBox.Location = new System.Drawing.Point(72, 56); this.sourceWidthTextBox.ReadOnly = true; this.sourceWidthTextBox.Size = new System.Drawing.Size(72, 20); this.sourceWidthTextBox.Text = ""; // // label4 // this.label4.Location = new System.Drawing.Point(8, 56); this.label4.Size = new System.Drawing.Size(56, 16); this.label4.Text = "Size:"; // // sourceHeightTextBox // this.sourceHeightTextBox.Location = new System.Drawing.Point(160, 56); this.sourceHeightTextBox.ReadOnly = true; this.sourceHeightTextBox.Size = new System.Drawing.Size(72, 20); this.sourceHeightTextBox.Text = ""; // // label3 // this.label3.Location = new System.Drawing.Point(144, 59); this.label3.Size = new System.Drawing.Size(16, 14); this.label3.Text = "x"; this.label3.TextAlign = System.Drawing.ContentAlignment.TopCenter; // // label5 // this.label5.Location = new System.Drawing.Point(8, 138); this.label5.Size = new System.Drawing.Size(56, 16); this.label5.Text = "Size:"; // // label6 // this.label6.Location = new System.Drawing.Point(144, 136); this.label6.Size = new System.Drawing.Size(16, 16); this.label6.Text = "x"; this.label6.TextAlign = System.Drawing.ContentAlignment.TopCenter; // // goButton // this.goButton.Location = new System.Drawing.Point(8, 232); this.goButton.Size = new System.Drawing.Size(224, 20); this.goButton.Text = "Go!"; this.goButton.Click += new System.EventHandler(this.goButton_Click); // // progressBar // this.progressBar.Location = new System.Drawing.Point(8, 256); this.progressBar.Size = new System.Drawing.Size(224, 8); this.progressBar.Visible = false; // // scaleUpDown // this.scaleUpDown.Increment = new System.Decimal(new int[] { 5, 0, 0, 0}); this.scaleUpDown.Location = new System.Drawing.Point(72, 168); this.scaleUpDown.Minimum = new System.Decimal(new int[] { 1, 0, 0, 0}); this.scaleUpDown.Size = new System.Drawing.Size(72, 20); this.scaleUpDown.Value = new System.Decimal(new int[] { 100, 0, 0, 0}); this.scaleUpDown.ValueChanged += new System.EventHandler(this.scaleUpDown_ValueChanged); // // label8 // this.label8.Location = new System.Drawing.Point(144, 170); this.label8.Size = new System.Drawing.Size(88, 16); this.label8.Text = "%"; // // destWidthUpDown // this.destWidthUpDown.Location = new System.Drawing.Point(72, 136); this.destWidthUpDown.Maximum = new System.Decimal(new int[] { 16384, 0, 0, 0}); this.destWidthUpDown.Size = new System.Drawing.Size(72, 20); this.destWidthUpDown.ValueChanged += new System.EventHandler(this.destWidthUpDown_ValueChanged); // // destHeightUpDown // this.destHeightUpDown.Location = new System.Drawing.Point(160, 136); this.destHeightUpDown.Maximum = new System.Decimal(new int[] { 16384, 0, 0, 0}); this.destHeightUpDown.Size = new System.Drawing.Size(72, 20); this.destHeightUpDown.ValueChanged += new System.EventHandler(this.destHeightUpDown_ValueChanged); // // ResizerForm // this.Controls.Add(this.destHeightUpDown); this.Controls.Add(this.destWidthUpDown); this.Controls.Add(this.label8); this.Controls.Add(this.scaleUpDown); this.Controls.Add(this.progressBar); this.Controls.Add(this.goButton); this.Controls.Add(this.label6); this.Controls.Add(this.label5); this.Controls.Add(this.label3); this.Controls.Add(this.sourceHeightTextBox); this.Controls.Add(this.label4); this.Controls.Add(this.sourceWidthTextBox); this.Controls.Add(this.selectDestinationButton); this.Controls.Add(this.destinationFileNameTextBox); this.Controls.Add(this.label2); this.Controls.Add(this.selectSourceButton); this.Controls.Add(this.sourceFileNameTextBox); this.Controls.Add(this.label1); this.Menu = this.mainMenu1; this.MinimizeBox = false; this.Text = "Resizer"; } #endregion /// <summary> /// The main entry point for the application. /// </summary> static void Main() { Application.Run(new ResizerForm()); } private int sourceWidth; private int sourceHeight; private void selectSourceButton_Click(object sender, System.EventArgs e) { if (this.openFileDialog.ShowDialog() == DialogResult.OK) { try { // Obtain source image size using decompressor using (JPEGator.Decompress decomp = new JPEGator.Decompress()) { decomp.Start(System.IO.File.OpenRead(openFileDialog.FileName)); sourceWidth = decomp.InputWidth; sourceHeight = decomp.InputHeight; } // Setup source controls sourceFileNameTextBox.Text = openFileDialog.FileName; sourceWidthTextBox.Text = sourceWidth.ToString(); sourceHeightTextBox.Text = sourceHeight.ToString(); // Initial setup for destination controls destinationFileNameTextBox.Text = System.IO.Path.ChangeExtension(openFileDialog.FileName, ".resized" + System.IO.Path.GetExtension(openFileDialog.FileName)); scaleUpDown_ValueChanged(this, EventArgs.Empty); } catch (JPEGator.JpegException ex) { MessageBox.Show( string.Format( "Failed to open {0} to obtain its size: {1}", openFileDialog.FileName, ex.Message ), "Resizer", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1 ); } } } private bool lockChanges; // Handle changes in destination picture scale private void scaleUpDown_ValueChanged(object sender, System.EventArgs e) { if (lockChanges) return; lockChanges = true; this.destWidthUpDown.Value = sourceWidth * this.scaleUpDown.Value / 100; this.destHeightUpDown.Value = sourceHeight * this.scaleUpDown.Value / 100; lockChanges = false; } // Handle changes of destination picture width private void destWidthUpDown_ValueChanged(object sender, System.EventArgs e) { if (lockChanges) return; lockChanges = true; this.destHeightUpDown.Value = destWidthUpDown.Value * sourceHeight / sourceWidth; this.scaleUpDown.Value = 100 * destWidthUpDown.Value / sourceWidth; lockChanges = false; } // Handle changes of destination picture height private void destHeightUpDown_ValueChanged(object sender, System.EventArgs e) { if (lockChanges) return; lockChanges = true; this.destWidthUpDown.Value = destHeightUpDown.Value * sourceWidth / sourceHeight; this.scaleUpDown.Value = 100 * destHeightUpDown.Value / sourceHeight; lockChanges = false; } // Squeeze single scanline of source image private void SqueezeLine(byte[] line, uint[] destLine, uint sourWidth, uint destWidth) { uint stepW = sourWidth; uint stepR = (uint)(stepW % destWidth); uint destWidth3 = destWidth * 3; int s = 0; int d3 = 0; int s3 = 0; uint l = 0; uint nextW = stepW; uint r = stepR; while (true) { // Squeeze whole pixels while ((s + 1) * destWidth <= nextW) { destLine[d3 + 0] += line[s3++]; destLine[d3 + 1] += line[s3++]; destLine[d3 + 2] += line[s3++]; s++; } if (s >= sourceWidth) break; // Add left part of partial pixel destLine[d3++] += line[s3 + 0] * r / destWidth; destLine[d3++] += line[s3 + 1] * r / destWidth; destLine[d3++] += line[s3 + 2] * r / destWidth; if (d3 >= destWidth3) break; l = destWidth - r; r += stepR; if (r >= destWidth) r -= destWidth; // Set next pixel to the right part of partial pixel destLine[d3 + 0] += line[s3++] * l / destWidth; destLine[d3 + 1] += line[s3++] * l / destWidth; destLine[d3 + 2] += line[s3++] * l / destWidth; s++; nextW += stepW; } } private void goButton_Click(object sender, System.EventArgs e) { try { progressBar.Value = 0; progressBar.Visible = true; try { // Create decompressor instance JPEGator.Decompress decomp = new JPEGator.Decompress(); // Setup decompression progress handler decomp.Progress += new JPEGator.ProgressEventHandler(decomp_Progress); // Start decompression process (setup source stream, read source picture header) decomp.Start(System.IO.File.OpenRead(openFileDialog.FileName)); // Create compressor instance JPEGator.Compress comp = new JPEGator.Compress( (int)this.destWidthUpDown.Value, (int)this.destHeightUpDown.Value ); // Start compression (prepare destination stream, setup color space and other compression parameters) comp.Start(this.destinationFileNameTextBox.Text, 75, JPEGator.ColorSpace.YCbCr); // // Getting shortcuts for some values (not sure if they can be optimized by JIT) // uint sourWidth = (uint)decomp.InputWidth; uint sourHeight = (uint)decomp.InputHeight; uint sourWidthHeight = sourWidth * sourHeight; uint destWidth = (uint)comp.ImageWidth; uint destHeight = (uint)comp.ImageHeight; uint destWidthHeight = destWidth * destHeight; // // Prepare temporary buffers // byte[] line = new byte[sourWidth * 3]; // Scanline of source image uint[] destLine = new uint[destWidth * 3]; // Temp scanline of detination image byte[] destByteLine = new byte[destWidth * 3]; // Ready for output scanline of destination image // // Prepare scaling algorithm vars // uint stepH = sourHeight; uint stepB = (uint)(sourHeight % destHeight); uint nextH = stepH; uint b = stepB; int i = 0; int d = 0; // Go through scanlines and squeeze them while (true) { // Squeeze scanlines that fit into single scanline of destination image while ((i + 1) * destHeight <= nextH) { decomp.ReadScanline(line); SqueezeLine(line, destLine, sourWidth, destWidth); i++; } // // Squeeze source scanline that partially belongs to two scanlines of destination image // // Squeeze first part uint[] tempLine = new uint[destWidth * 3]; if (i < sourHeight) { decomp.ReadScanline(line); SqueezeLine(line, tempLine, sourWidth, destWidth); for (d = 0; d < destWidth * 3; d++) destByteLine[d] = (byte)((destLine[d] * destHeight + tempLine[d] * b) * destWidth / sourWidthHeight); comp.WriteScanline(destByteLine, 0); } else { System.Diagnostics.Trace.Assert(b == 0); for (d = 0; d < destWidth * 3; d++) destByteLine[d] = (byte)(destLine[d] * destWidthHeight / sourWidthHeight); comp.WriteScanline(destByteLine, 0); break; } // Squeeze second part uint t = destHeight - b; for (d = 0; d < destWidth * 3; d++) destLine[d] = tempLine[d] * t / destHeight; b += stepB; if (b >= destHeight) b -= destHeight; i++; nextH += stepH; } } finally { progressBar.Visible = false; } } catch (JPEGator.JpegException ex) { MessageBox.Show( string.Format( "Unable to resize {0} to {1}: {2}", openFileDialog.FileName, destinationFileNameTextBox.Text, ex.Message ), "Resizer", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1 ); } } // Decompression progress handler private void decomp_Progress(object sender, JPEGator.ProgressEventArgs e) { progressBar.Value = e.Percent; } } }
using System; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Security.Policy; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using Prism.Modularity; namespace Prism.Wpf.Tests.Modularity { [TestClass] public class DirectoryModuleCatalogFixture { private const string ModulesDirectory1 = @".\DynamicModules\MocksModules1"; private const string ModulesDirectory2 = @".\DynamicModules\AttributedModules"; private const string ModulesDirectory3 = @".\DynamicModules\DependantModules"; private const string ModulesDirectory4 = @".\DynamicModules\MocksModules2"; private const string ModulesDirectory5 = @".\DynamicModules\ModulesMainDomain\"; private const string InvalidModulesDirectory = @".\Modularity"; public DirectoryModuleCatalogFixture() { } [TestInitialize] [TestCleanup] public void CleanUpDirectories() { CompilerHelper.CleanUpDirectory(ModulesDirectory1); CompilerHelper.CleanUpDirectory(ModulesDirectory2); CompilerHelper.CleanUpDirectory(ModulesDirectory3); CompilerHelper.CleanUpDirectory(ModulesDirectory4); CompilerHelper.CleanUpDirectory(ModulesDirectory5); CompilerHelper.CleanUpDirectory(InvalidModulesDirectory); } [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void NullPathThrows() { DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.Load(); } [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void EmptyPathThrows() { DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.Load(); } [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void NonExistentPathThrows() { DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = "NonExistentPath"; catalog.Load(); } [TestMethod] public void ShouldReturnAListOfModuleInfo() { CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockModuleA.cs", ModulesDirectory1 + @"\MockModuleA.dll"); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory1; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.IsNotNull(modules); Assert.AreEqual(1, modules.Length); Assert.IsNotNull(modules[0].Ref); StringAssert.StartsWith(modules[0].Ref, "file://"); Assert.IsTrue(modules[0].Ref.Contains(@"MockModuleA.dll")); Assert.IsNotNull(modules[0].ModuleType); StringAssert.Contains(modules[0].ModuleType, "Prism.Wpf.Tests.Mocks.Modules.MockModuleA"); } [TestMethod] [DeploymentItem(@"Modularity\NotAValidDotNetDll.txt.dll", @".\Modularity")] public void ShouldNotThrowWithNonValidDotNetAssembly() { DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = InvalidModulesDirectory; try { catalog.Load(); } catch (Exception) { Assert.Fail("Should not have thrown."); } ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.IsNotNull(modules); Assert.AreEqual(0, modules.Length); } [TestMethod] [DeploymentItem(@"Modularity\NotAValidDotNetDll.txt.dll", InvalidModulesDirectory)] public void LoadsValidAssembliesWhenInvalidDllsArePresent() { CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockModuleA.cs", InvalidModulesDirectory + @"\MockModuleA.dll"); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = InvalidModulesDirectory; try { catalog.Load(); } catch (Exception) { Assert.Fail("Should not have thrown."); } ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.IsNotNull(modules); Assert.AreEqual(1, modules.Length); Assert.IsNotNull(modules[0].Ref); StringAssert.StartsWith(modules[0].Ref, "file://"); Assert.IsTrue(modules[0].Ref.Contains(@"MockModuleA.dll")); Assert.IsNotNull(modules[0].ModuleType); StringAssert.Contains(modules[0].ModuleType, "Prism.Wpf.Tests.Mocks.Modules.MockModuleA"); } [TestMethod] public void ShouldNotThrowWithLoadFromByteAssemblies() { CompilerHelper.CleanUpDirectory(@".\CompileOutput\"); CompilerHelper.CleanUpDirectory(@".\IgnoreLoadFromByteAssembliesTestDir\"); var results = CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockModuleA.cs", @".\CompileOutput\MockModuleA.dll"); CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockAttributedModule.cs", @".\IgnoreLoadFromByteAssembliesTestDir\MockAttributedModule.dll"); string path = @".\IgnoreLoadFromByteAssembliesTestDir"; AppDomain testDomain = null; try { testDomain = CreateAppDomain(); RemoteDirectoryLookupCatalog remoteEnum = CreateRemoteDirectoryModuleCatalogInAppDomain(testDomain); remoteEnum.LoadDynamicEmittedModule(); remoteEnum.LoadAssembliesByByte(@".\CompileOutput\MockModuleA.dll"); ModuleInfo[] infos = remoteEnum.DoEnumeration(path); Assert.IsNotNull( infos.FirstOrDefault(x => x.ModuleType.IndexOf("Prism.Wpf.Tests.Mocks.Modules.MockAttributedModule") >= 0) ); } finally { if (testDomain != null) AppDomain.Unload(testDomain); } } [TestMethod] public void ShouldGetModuleNameFromAttribute() { CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockAttributedModule.cs", ModulesDirectory2 + @"\MockAttributedModule.dll"); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory2; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.AreEqual(1, modules.Length); Assert.AreEqual("TestModule", modules[0].ModuleName); } [TestMethod] public void ShouldGetDependantModulesFromAttribute() { CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockDependencyModule.cs", ModulesDirectory3 + @"\DependencyModule.dll"); CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockDependantModule.cs", ModulesDirectory3 + @"\DependantModule.dll"); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory3; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.AreEqual(2, modules.Length); var dependantModule = modules.First(module => module.ModuleName == "DependantModule"); var dependencyModule = modules.First(module => module.ModuleName == "DependencyModule"); Assert.IsNotNull(dependantModule); Assert.IsNotNull(dependencyModule); Assert.IsNotNull(dependantModule.DependsOn); Assert.AreEqual(1, dependantModule.DependsOn.Count); Assert.AreEqual(dependencyModule.ModuleName, dependantModule.DependsOn[0]); } [TestMethod] public void UseClassNameAsModuleNameWhenNotSpecifiedInAttribute() { CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockModuleA.cs", ModulesDirectory1 + @"\MockModuleA.dll"); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory1; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.IsNotNull(modules); Assert.AreEqual("MockModuleA", modules[0].ModuleName); } [TestMethod] public void ShouldDefaultInitializationModeToWhenAvailable() { CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockModuleA.cs", ModulesDirectory1 + @"\MockModuleA.dll"); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory1; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.IsNotNull(modules); Assert.AreEqual(InitializationMode.WhenAvailable, modules[0].InitializationMode); } [TestMethod] public void ShouldGetOnDemandFromAttribute() { CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockAttributedModule.cs", ModulesDirectory3 + @"\MockAttributedModule.dll"); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory3; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.AreEqual(1, modules.Length); Assert.AreEqual(InitializationMode.OnDemand, modules[0].InitializationMode); } [TestMethod] public void ShouldNotLoadAssembliesInCurrentAppDomain() { CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockModuleA.cs", ModulesDirectory4 + @"\MockModuleA.dll"); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory4; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); // filtering out dynamic assemblies due to using a dynamic mocking framework. Assembly loadedAssembly = AppDomain.CurrentDomain.GetAssemblies().Where(assembly => !assembly.IsDynamic) .Where(assembly => assembly.Location.Equals(modules[0].Ref, StringComparison.InvariantCultureIgnoreCase)) .FirstOrDefault(); Assert.IsNull(loadedAssembly); } [TestMethod] public void ShouldNotGetModuleInfoForAnAssemblyAlreadyLoadedInTheMainDomain() { var assemblyPath = Assembly.GetCallingAssembly().Location; DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory5; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.AreEqual(0, modules.Length); } [TestMethod] public void ShouldLoadAssemblyEvenIfTheyAreReferencingEachOther() { CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockModuleA.cs", ModulesDirectory4 + @"\MockModuleZZZ.dll"); CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockModuleReferencingOtherModule.cs", ModulesDirectory4 + @"\MockModuleReferencingOtherModule.dll", ModulesDirectory4 + @"\MockModuleZZZ.dll"); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory4; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.AreEqual(2, modules.Count()); } //Disabled Warning // 'System.Security.Policy.Evidence.Count' is obsolete: ' // "Evidence should not be treated as an ICollection. Please use GetHostEnumerator and GetAssemblyEnumerator to // iterate over the evidence to collect a count."' #pragma warning disable 0618 [TestMethod] public void CreateChildAppDomainHasParentEvidenceAndSetup() { TestableDirectoryModuleCatalog catalog = new TestableDirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory4; catalog.Load(); Evidence parentEvidence = new Evidence(); AppDomainSetup parentSetup = new AppDomainSetup(); parentSetup.ApplicationName = "Test Parent"; AppDomain parentAppDomain = AppDomain.CreateDomain("Parent", parentEvidence, parentSetup); AppDomain childDomain = catalog.BuildChildDomain(parentAppDomain); Assert.AreEqual(parentEvidence.Count, childDomain.Evidence.Count); Assert.AreEqual("Test Parent", childDomain.SetupInformation.ApplicationName); Assert.AreNotEqual(AppDomain.CurrentDomain.Evidence.Count, childDomain.Evidence.Count); Assert.AreNotEqual(AppDomain.CurrentDomain.SetupInformation.ApplicationName, childDomain.SetupInformation.ApplicationName); } #pragma warning restore 0618 [TestMethod] public void ShouldLoadFilesEvenIfDynamicAssemblyExists() { CompilerHelper.CleanUpDirectory(@".\CompileOutput\"); CompilerHelper.CleanUpDirectory(@".\IgnoreDynamicGeneratedFilesTestDir\"); CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockAttributedModule.cs", @".\IgnoreDynamicGeneratedFilesTestDir\MockAttributedModule.dll"); string path = @".\IgnoreDynamicGeneratedFilesTestDir"; AppDomain testDomain = null; try { testDomain = CreateAppDomain(); RemoteDirectoryLookupCatalog remoteEnum = CreateRemoteDirectoryModuleCatalogInAppDomain(testDomain); remoteEnum.LoadDynamicEmittedModule(); ModuleInfo[] infos = remoteEnum.DoEnumeration(path); Assert.IsNotNull( infos.FirstOrDefault(x => x.ModuleType.IndexOf("Prism.Wpf.Tests.Mocks.Modules.MockAttributedModule") >= 0) ); } finally { if (testDomain != null) AppDomain.Unload(testDomain); } } [TestMethod] public void ShouldLoadAssemblyEvenIfIsExposingTypesFromAnAssemblyInTheGac() { CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockExposingTypeFromGacAssemblyModule.cs", ModulesDirectory4 + @"\MockExposingTypeFromGacAssemblyModule.dll", @"System.Transactions.dll"); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory4; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.AreEqual(1, modules.Count()); } [TestMethod] public void ShouldNotFailWhenAlreadyLoadedAssembliesAreAlsoFoundOnTargetDirectory() { CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockModuleA.cs", ModulesDirectory1 + @"\MockModuleA.dll"); string filename = typeof(DirectoryModuleCatalog).Assembly.Location; string destinationFileName = Path.Combine(ModulesDirectory1, Path.GetFileName(filename)); File.Copy(filename, destinationFileName); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory1; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.AreEqual(1, modules.Length); } [TestMethod] public void ShouldIgnoreAbstractClassesThatImplementIModule() { CompilerHelper.CleanUpDirectory(ModulesDirectory1); CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockAbstractModule.cs", ModulesDirectory1 + @"\MockAbstractModule.dll"); string filename = typeof(DirectoryModuleCatalog).Assembly.Location; string destinationFileName = Path.Combine(ModulesDirectory1, Path.GetFileName(filename)); File.Copy(filename, destinationFileName); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory1; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.AreEqual(1, modules.Length); Assert.AreEqual("MockInheritingModule", modules[0].ModuleName); CompilerHelper.CleanUpDirectory(ModulesDirectory1); } private AppDomain CreateAppDomain() { Evidence evidence = AppDomain.CurrentDomain.Evidence; AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation; return AppDomain.CreateDomain("TestDomain", evidence, setup); } private RemoteDirectoryLookupCatalog CreateRemoteDirectoryModuleCatalogInAppDomain(AppDomain testDomain) { RemoteDirectoryLookupCatalog remoteEnum; Type remoteEnumType = typeof(RemoteDirectoryLookupCatalog); remoteEnum = (RemoteDirectoryLookupCatalog)testDomain.CreateInstanceFrom( remoteEnumType.Assembly.Location, remoteEnumType.FullName).Unwrap(); return remoteEnum; } private class TestableDirectoryModuleCatalog : DirectoryModuleCatalog { public new AppDomain BuildChildDomain(AppDomain currentDomain) { return base.BuildChildDomain(currentDomain); } } private class RemoteDirectoryLookupCatalog : MarshalByRefObject { public void LoadAssembliesByByte(string assemblyPath) { byte[] assemblyBytes = File.ReadAllBytes(assemblyPath); AppDomain.CurrentDomain.Load(assemblyBytes); } public ModuleInfo[] DoEnumeration(string path) { DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = path; catalog.Load(); return catalog.Modules.ToArray(); } public void LoadDynamicEmittedModule() { // create a dynamic assembly and module AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = "DynamicBuiltAssembly"; AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave); ModuleBuilder module = assemblyBuilder.DefineDynamicModule("DynamicBuiltAssembly.dll"); // create a new type TypeBuilder typeBuilder = module.DefineType("DynamicBuiltType", TypeAttributes.Public | TypeAttributes.Class); // Create the type Type helloWorldType = typeBuilder.CreateType(); } } } }
#region Copyright // // This framework is based on log4j see http://jakarta.apache.org/log4j // Copyright (C) The Apache Software Foundation. All rights reserved. // // This software is published under the terms of the Apache Software // License version 1.1, a copy of which has been included with this // distribution in the LICENSE.txt file. // #endregion using System; using log4net.ObjectRenderer; using log4net.spi; using log4net.helpers; namespace log4net.Repository.Hierarchy { #region LoggerCreationEvent /// <summary> /// Delegate used to handle logger creation event notifications. /// </summary> /// <param name="sender">The <see cref="Hierarchy"/> in which the <see cref="Logger"/> has been created.</param> /// <param name="e">The <see cref="LoggerCreationEventArgs"/> event args that hold the <see cref="Logger"/> instance that has been created.</param> public delegate void LoggerCreationEventHandler(object sender, LoggerCreationEventArgs e); /// <summary> /// Provides data for the <see cref="Hierarchy.LoggerCreatedEvent"/> event. /// </summary> /// <remarks> /// A <see cref="Hierarchy.LoggerCreatedEvent"/> event is raised every time a /// <see cref="Logger"/> is created. /// </remarks> public class LoggerCreationEventArgs : EventArgs { /// <summary> /// The <see cref="Logger"/> created /// </summary> private Logger m_log; /// <summary> /// Initializes a new instance of the <see cref="LoggerCreationEventArgs" /> event argument /// class,with the specified <see cref="Logger"/>. /// </summary> /// <param name="log">The <see cref="Logger"/> that has been created.</param> public LoggerCreationEventArgs(Logger log) { m_log = log; } /// <summary> /// Gets the <see cref="Logger"/> that has been created. /// </summary> /// <value> /// The <see cref="Logger"/> that has been created. /// </value> public Logger Logger { get { return m_log; } } } #endregion LoggerCreationEvent #region HierarchyConfigurationChangedEvent /// <summary> /// Delegate used to handle event notifications for hierarchy configuration changes. /// </summary> /// <param name="sender">The <see cref="Hierarchy"/> that has had its configuration changed.</param> /// <param name="e">Empty event arguments.</param> public delegate void HierarchyConfigurationChangedEventHandler(object sender, EventArgs e); #endregion HierarchyConfigurationChangedEvent /// <summary> /// This class is specialized in retrieving loggers by name and /// also maintaining the logger hierarchy. Implements the /// <see cref="ILoggerRepository"/> interface. /// </summary> /// <remarks> /// <para><i>The casual user should not have to deal with this class /// directly.</i></para> /// /// <para>The structure of the logger hierarchy is maintained by the /// <see cref="GetLogger"/> method. The hierarchy is such that children /// link to their parent but parents do not have any references to their /// children. Moreover, loggers can be instantiated in any order, in /// particular descendant before ancestor.</para> /// /// <para>In case a descendant is created before a particular ancestor, /// then it creates a provision node for the ancestor and adds itself /// to the provision node. Other descendants of the same ancestor add /// themselves to the previously created provision node.</para> /// </remarks> public class Hierarchy : LoggerRepositorySkeleton, IBasicRepositoryConfigurator, IDOMRepositoryConfigurator { #region Public Events /// <summary> /// Event used to notify that a logger has been created. /// </summary> public event LoggerCreationEventHandler LoggerCreatedEvent { add { m_loggerCreatedEvent += value; } remove { m_loggerCreatedEvent -= value; } } /// <summary> /// Event to notify that the hierarchy has had its configuration changed. /// </summary> /// <value> /// Event to notify that the hierarchy has had its configuration changed. /// </value> public event HierarchyConfigurationChangedEventHandler ConfigurationChangedEvent { add { m_configurationChangedEvent += value; } remove { m_configurationChangedEvent -= value; } } #endregion Public Events #region Public Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="Hierarchy" /> class. /// </summary> public Hierarchy() : this(new DefaultLoggerFactory()) { } /// <summary> /// Initializes a new instance of the <see cref="Hierarchy" /> class. /// </summary> /// <param name="properties">The properties to pass to this repository.</param> public Hierarchy(PropertiesCollection properties) : this(properties, new DefaultLoggerFactory()) { } /// <summary> /// Initializes a new instance of the <see cref="Hierarchy" /> class with /// the specified <see cref="ILoggerFactory" />. /// </summary> /// <param name="loggerFactory">The factory to use to create new logger instances.</param> public Hierarchy(ILoggerFactory loggerFactory) : this(new PropertiesCollection(), loggerFactory) { } /// <summary> /// Initializes a new instance of the <see cref="Hierarchy" /> class with /// the specified <see cref="ILoggerFactory" />. /// </summary> /// <param name="properties">The properties to pass to this repository.</param> /// <param name="loggerFactory">The factory to use to create new logger instances.</param> public Hierarchy(PropertiesCollection properties, ILoggerFactory loggerFactory) : base(properties) { if (loggerFactory == null) { throw new ArgumentNullException("loggerFactory"); } m_defaultFactory = loggerFactory; m_ht = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); m_root = new RootLogger(Level.DEBUG); m_root.Hierarchy = this; } #endregion Public Instance Constructors #region Public Instance Properties /// <summary> /// Flag to indicate if we have already issued a warning /// about not having an appender warning. /// </summary> public bool EmittedNoAppenderWarning { get { return m_emittedNoAppenderWarning; } set { m_emittedNoAppenderWarning = value; } } /// <summary> /// Gets the root of this hierarchy. /// </summary> public Logger Root { get { return m_root; } } /// <summary> /// Gets or sets the default <see cref="ILoggerFactory" /> instance. /// </summary> /// <value>The default <see cref="ILoggerFactory" />.</value> public ILoggerFactory LoggerFactory { get { return m_defaultFactory; } set { if (value == null) { throw new ArgumentNullException("value"); } m_defaultFactory = value; } } #endregion Public Instance Properties #region Override Implementation of LoggerRepositorySkeleton /// <summary> /// Check if the named logger exists in the hierarchy. If so return /// its reference, otherwise returns <c>null</c>. /// </summary> /// <param name="name">The name of the logger to lookup</param> /// <returns>The Logger object with the name specified</returns> override public ILogger Exists(string name) { if (name == null) { throw new ArgumentNullException("name"); } return m_ht[new LoggerKey(name)] as Logger; } /// <summary> /// Returns all the currently defined loggers in the hierarchy as an Array /// </summary> /// <remarks> /// Returns all the currently defined loggers in the hierarchy as an Array. /// The root logger is <b>not</b> included in the returned /// enumeration. /// </remarks> /// <returns>All the defined loggers</returns> override public ILogger[] GetCurrentLoggers() { // The accumulation in loggers is necessary because not all elements in // ht are Logger objects as there might be some ProvisionNodes // as well. System.Collections.ArrayList loggers = new System.Collections.ArrayList(m_ht.Count); // Iterate through m_ht values foreach(object node in m_ht.Values) { if (node is Logger) { loggers.Add(node); } } return (Logger[])loggers.ToArray(typeof(Logger)); } /// <summary> /// Return a new logger instance named as the first parameter using /// the default factory. /// </summary> /// <remarks> /// Return a new logger instance named as the first parameter using /// the default factory. /// /// <para>If a logger of that name already exists, then it will be /// returned. Otherwise, a new logger will be instantiated and /// then linked with its existing ancestors as well as children.</para> /// </remarks> /// <param name="name">The name of the logger to retrieve</param> /// <returns>The logger object with the name specified</returns> override public ILogger GetLogger(string name) { if (name == null) { throw new ArgumentNullException("name"); } return GetLogger(name, m_defaultFactory); } /// <summary> /// Shutting down a hierarchy will <i>safely</i> close and remove /// all appenders in all loggers including the root logger. /// </summary> /// <remarks> /// Shutting down a hierarchy will <i>safely</i> close and remove /// all appenders in all loggers including the root logger. /// /// <para>Some appenders need to be closed before the /// application exists. Otherwise, pending logging events might be /// lost.</para> /// /// <para>The <c>Shutdown</c> method is careful to close nested /// appenders before closing regular appenders. This is allows /// configurations where a regular appender is attached to a logger /// and again to a nested appender.</para> /// </remarks> override public void Shutdown() { // begin by closing nested appenders Root.CloseNestedAppenders(); lock(m_ht) { foreach(Logger l in this.GetCurrentLoggers()) { l.CloseNestedAppenders(); } // then, remove all appenders Root.RemoveAllAppenders(); foreach(Logger l in this.GetCurrentLoggers()) { l.RemoveAllAppenders(); } } base.Shutdown(); } /// <summary> /// Reset all values contained in this hierarchy instance to their default. /// </summary> /// <remarks> /// Reset all values contained in this hierarchy instance to their /// default. This removes all appenders from all loggers, sets /// the level of all non-root loggers to <c>null</c>, /// sets their additivity flag to <c>true</c> and sets the level /// of the root logger to <see cref="Level.DEBUG"/>. Moreover, /// message disabling is set its default "off" value. /// /// <para>Existing loggers are not removed. They are just reset.</para> /// /// <para>This method should be used sparingly and with care as it will /// block all logging until it is completed.</para> /// </remarks> override public void ResetConfiguration() { Root.Level = Level.DEBUG; Threshold = Level.ALL; // the synchronization is needed to prevent hashtable surprises lock(m_ht) { Shutdown(); // nested locks are OK foreach(Logger l in this.GetCurrentLoggers()) { l.Level = null; l.Additivity = true; } } base.ResetConfiguration(); } /// <summary> /// Log the logEvent through this hierarchy. /// </summary> /// <param name="logEvent">the event to log</param> /// <remarks> /// <para> /// This method should not normally be used to log. /// The <see cref="ILog"/> interface should be used /// for routine logging. This interface can be obtained /// using the <see cref="log4net.LogManager.GetLogger(string)"/> method. /// </para> /// <para> /// The <c>logEvent</c> is delivered to the appropriate logger and /// that logger is then responsible for logging the event. /// </para> /// </remarks> override public void Log(LoggingEvent logEvent) { if (logEvent == null) { throw new ArgumentNullException("logEvent"); } this.GetLogger(logEvent.LoggerName, m_defaultFactory).Log(logEvent); } #endregion Override Implementation of LoggerRepositorySkeleton #region Implementation of IBasicRepositoryConfigurator /// <summary> /// Initialise the log4net system using the specified appender /// </summary> /// <param name="appender">the appender to use to log all logging events</param> void IBasicRepositoryConfigurator.Configure(log4net.Appender.IAppender appender) { Root.AddAppender(appender); Configured = true; // Notify listeners FireConfigurationChangedEvent(); } #endregion Implementation of IBasicRepositoryConfigurator #region Implementation of IDOMRepositoryConfigurator /// <summary> /// Initialise the log4net system using the specified config /// </summary> /// <param name="element">the element containing the root of the config</param> void IDOMRepositoryConfigurator.Configure(System.Xml.XmlElement element) { DOMHierarchyConfigurator config = new DOMHierarchyConfigurator(this); config.Configure(element); Configured = true; // Notify listeners FireConfigurationChangedEvent(); } #endregion Implementation of IDOMRepositoryConfigurator #region Public Instance Methods /// <summary> /// Test if this hierarchy is disabled for the specified <see cref="Level"/>. /// </summary> /// <param name="level">The level to check against.</param> /// <returns> /// <c>true</c> if the repository is disabled for the level argument, <c>false</c> otherwise. /// </returns> /// <remarks> /// <para> /// If this hierarchy has not been configured then this method will /// always return <c>true</c>. /// </para> /// <para> /// This method will return <c>true</c> if this repository is /// disabled for <c>level</c> object passed as parameter and /// <c>false</c> otherwise. /// </para> /// <para> /// See also the <see cref="ILoggerRepository.Threshold"/> property. /// </para> /// </remarks> public bool IsDisabled(Level level) { if (level == null) { throw new ArgumentNullException("level"); } if (Configured) { return Threshold > level; } else { // If not configured the hierarchy is effectivly disabled return true; } } /// <summary> /// Clear all logger definitions from the internal hashtable /// </summary> /// <remarks> /// This call will clear all logger definitions from the internal /// hashtable. Invoking this method will irrevocably mess up the /// logger hierarchy. /// /// <para>You should <b>really</b> know what you are doing before /// invoking this method.</para> /// </remarks> public void Clear() { m_ht.Clear(); } /// <summary> /// Return a new logger instance named as the first parameter using /// <paramref name="factory"/>. /// </summary> /// <remarks> /// If a logger of that name already exists, then it will be /// returned. Otherwise, a new logger will be instantiated by the /// <paramref name="factory"/> parameter and linked with its existing /// ancestors as well as children. /// </remarks> /// <param name="name">The name of the logger to retrieve</param> /// <param name="factory">The factory that will make the new logger instance</param> /// <returns>The logger object with the name specified</returns> public Logger GetLogger(string name, ILoggerFactory factory) { if (name == null) { throw new ArgumentNullException("name"); } if (factory == null) { throw new ArgumentNullException("factory"); } LoggerKey key = new LoggerKey(name); // Synchronize to prevent write conflicts. Read conflicts (in // GetEffectiveLevel() method) are possible only if variable // assignments are non-atomic. Logger logger; lock(m_ht) { Object node = m_ht[key]; if (node == null) { logger = factory.MakeNewLoggerInstance(name); logger.Hierarchy = this; m_ht[key] = logger; UpdateParents(logger); FireLoggerCreationEvent(logger); return logger; } else if (node is Logger) { return (Logger)node; } else if (node is ProvisionNode) { logger = factory.MakeNewLoggerInstance(name); logger.Hierarchy = this; m_ht[key] = logger; UpdateChildren((ProvisionNode)node, logger); UpdateParents(logger); FireLoggerCreationEvent(logger); return logger; } else { // It should be impossible to arrive here return null; // but let's keep the compiler happy. } } } #endregion Public Instance Methods #region Protected Instance Methods /// <summary> /// Notify the registered listeners that the hierarchy has had its configuration changed /// </summary> protected void FireConfigurationChangedEvent() { if (m_configurationChangedEvent != null) { m_configurationChangedEvent(this, EventArgs.Empty); } } #endregion Protected Instance Methods #region Private Instance Methods /// <summary> /// Sends a logger creation event to all registered listeners /// </summary> /// <param name="logger">The newly created logger</param> private void FireLoggerCreationEvent(Logger logger) { if (m_loggerCreatedEvent != null) { m_loggerCreatedEvent(this, new LoggerCreationEventArgs(logger)); } } /// <summary> /// Updates all the parents of the specified logger /// </summary> /// <remarks> /// This method loops through all the <i>potential</i> parents of /// 'log'. There 3 possible cases: /// <list type="number"> /// <item> /// <term>No entry for the potential parent of 'log' exists</term> /// <description>We create a ProvisionNode for this potential /// parent and insert 'log' in that provision node.</description> /// </item> /// <item> /// <term>There entry is of type Logger for the potential parent.</term> /// <description>The entry is 'log's nearest existing parent. We /// update log's parent field with this entry. We also break from /// he loop because updating our parent's parent is our parent's /// responsibility.</description> /// </item> /// <item> /// <term>There entry is of type ProvisionNode for this potential parent.</term> /// <description>We add 'log' to the list of children for this /// potential parent.</description> /// </item> /// </list> /// </remarks> /// <param name="log">The logger to update the parents for</param> private void UpdateParents(Logger log) { string name = log.Name; int length = name.Length; bool parentFound = false; // if name = "w.x.y.z", loop through "w.x.y", "w.x" and "w", but not "w.x.y.z" for(int i = name.LastIndexOf('.', length-1); i >= 0; i = name.LastIndexOf('.', i-1)) { string substr = name.Substring(0, i); LoggerKey key = new LoggerKey(substr); // simple constructor Object node = m_ht[key]; // Create a provision node for a future parent. if (node == null) { ProvisionNode pn = new ProvisionNode(log); m_ht[key] = pn; } else if (node is Logger) { parentFound = true; log.Parent = (Logger)node; break; // no need to update the ancestors of the closest ancestor } else if (node is ProvisionNode) { ((ProvisionNode)node).Add(log); } else { LogLog.Error("unexpected object type ["+node.GetType()+"] in ht.", new LogException()); } } // If we could not find any existing parents, then link with root. if (!parentFound) { log.Parent = m_root; } } /// <summary> /// Replace a <see cref="ProvisionNode"/> with a <see cref="Logger"/> in the hierarchy. /// </summary> /// <remarks> /// <para>We update the links for all the children that placed themselves /// in the provision node 'pn'. The second argument 'log' is a /// reference for the newly created Logger, parent of all the /// children in 'pn'</para> /// /// <para>We loop on all the children 'c' in 'pn':</para> /// /// <para>If the child 'c' has been already linked to a child of /// 'log' then there is no need to update 'c'.</para> /// /// <para>Otherwise, we set log's parent field to c's parent and set /// c's parent field to log.</para> /// </remarks> /// <param name="pn"></param> /// <param name="log"></param> private void UpdateChildren(ProvisionNode pn, Logger log) { for(int i = 0; i < pn.Count; i++) { Logger childLogger = (Logger)pn[i]; // Unless this child already points to a correct (lower) parent, // make log.Parent point to childLogger.Parent and childLogger.Parent to log. if (!childLogger.Parent.Name.StartsWith(log.Name)) { log.Parent = childLogger.Parent; childLogger.Parent = log; } } } #endregion Private Instance Methods #region Private Instance Fields private ILoggerFactory m_defaultFactory; private System.Collections.Hashtable m_ht; private Logger m_root; private bool m_emittedNoAppenderWarning = false; private event LoggerCreationEventHandler m_loggerCreatedEvent; private event HierarchyConfigurationChangedEventHandler m_configurationChangedEvent; #endregion Private Instance Fields } }
// Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 UnityEngine; using UnityEngine.EventSystems; /// Draws a circular reticle in front of any object that the user points at. /// The circle dilates if the object is clickable. public class GvrReticlePointer : GvrBasePointer { /// The constants below are expsed for testing. Minimum inner angle of the reticle (in degrees). public const float RETICLE_MIN_INNER_ANGLE = 0.0f; /// Minimum outer angle of the reticle (in degrees). public const float RETICLE_MIN_OUTER_ANGLE = 0.5f; /// Angle at which to expand the reticle when intersecting with an object (in degrees). public const float RETICLE_GROWTH_ANGLE = 1.5f; /// Minimum distance of the reticle (in meters). public const float RETICLE_DISTANCE_MIN = 0.45f; /// Maximum distance of the reticle (in meters). public float maxReticleDistance = 10.0f; /// Number of segments making the reticle circle. public int reticleSegments = 20; /// Growth speed multiplier for the reticle/ public float reticleGrowthSpeed = 8.0f; /// Sorting order to use for the reticle's renderer. /// Range values come from https://docs.unity3d.com/ScriptReference/Renderer-sortingOrder.html. /// Default value 32767 ensures gaze reticle is always rendered on top. [Range(-32767, 32767)] public int reticleSortingOrder = 32767; public Material MaterialComp { private get; set; } // Current inner angle of the reticle (in degrees). // Exposed for testing. public float ReticleInnerAngle { get; private set; } // Current outer angle of the reticle (in degrees). // Exposed for testing. public float ReticleOuterAngle { get; private set; } // Current distance of the reticle (in meters). // Getter exposed for testing. public float ReticleDistanceInMeters { get; private set; } // Current inner and outer diameters of the reticle, before distance multiplication. // Getters exposed for testing. public float ReticleInnerDiameter { get; private set; } public float ReticleOuterDiameter { get; private set; } public override float MaxPointerDistance { get { return maxReticleDistance; } } public override void OnPointerEnter(RaycastResult raycastResultResult, bool isInteractive) { SetPointerTarget(raycastResultResult.worldPosition, isInteractive); } public override void OnPointerHover(RaycastResult raycastResultResult, bool isInteractive) { SetPointerTarget(raycastResultResult.worldPosition, isInteractive); } public override void OnPointerExit(GameObject previousObject) { ReticleDistanceInMeters = maxReticleDistance; ReticleInnerAngle = RETICLE_MIN_INNER_ANGLE; ReticleOuterAngle = RETICLE_MIN_OUTER_ANGLE; } public override void OnPointerClickDown() {} public override void OnPointerClickUp() {} public override void GetPointerRadius(out float enterRadius, out float exitRadius) { float min_inner_angle_radians = Mathf.Deg2Rad * RETICLE_MIN_INNER_ANGLE; float max_inner_angle_radians = Mathf.Deg2Rad * (RETICLE_MIN_INNER_ANGLE + RETICLE_GROWTH_ANGLE); enterRadius = 2.0f * Mathf.Tan(min_inner_angle_radians); exitRadius = 2.0f * Mathf.Tan(max_inner_angle_radians); } public void UpdateDiameters() { ReticleDistanceInMeters = Mathf.Clamp(ReticleDistanceInMeters, RETICLE_DISTANCE_MIN, maxReticleDistance); if (ReticleInnerAngle < RETICLE_MIN_INNER_ANGLE) { ReticleInnerAngle = RETICLE_MIN_INNER_ANGLE; } if (ReticleOuterAngle < RETICLE_MIN_OUTER_ANGLE) { ReticleOuterAngle = RETICLE_MIN_OUTER_ANGLE; } float inner_half_angle_radians = Mathf.Deg2Rad * ReticleInnerAngle * 0.5f; float outer_half_angle_radians = Mathf.Deg2Rad * ReticleOuterAngle * 0.5f; float inner_diameter = 2.0f * Mathf.Tan(inner_half_angle_radians); float outer_diameter = 2.0f * Mathf.Tan(outer_half_angle_radians); ReticleInnerDiameter = Mathf.Lerp(ReticleInnerDiameter, inner_diameter, Time.deltaTime * reticleGrowthSpeed); ReticleOuterDiameter = Mathf.Lerp(ReticleOuterDiameter, outer_diameter, Time.deltaTime * reticleGrowthSpeed); MaterialComp.SetFloat("_InnerDiameter", ReticleInnerDiameter * ReticleDistanceInMeters); MaterialComp.SetFloat("_OuterDiameter", ReticleOuterDiameter * ReticleDistanceInMeters); MaterialComp.SetFloat("_DistanceInMeters", ReticleDistanceInMeters); } void Awake() { ReticleInnerAngle = RETICLE_MIN_INNER_ANGLE; ReticleOuterAngle = RETICLE_MIN_OUTER_ANGLE; } protected override void Start() { base.Start(); Renderer rendererComponent = GetComponent<Renderer>(); rendererComponent.sortingOrder = reticleSortingOrder; MaterialComp = rendererComponent.material; CreateReticleVertices(); } void Update() { UpdateDiameters(); } private bool SetPointerTarget(Vector3 target, bool interactive) { if (base.PointerTransform == null) { Debug.LogWarning("Cannot operate on a null pointer transform"); return false; } Vector3 targetLocalPosition = base.PointerTransform.InverseTransformPoint(target); ReticleDistanceInMeters = Mathf.Clamp(targetLocalPosition.z, RETICLE_DISTANCE_MIN, maxReticleDistance); if (interactive) { ReticleInnerAngle = RETICLE_MIN_INNER_ANGLE + RETICLE_GROWTH_ANGLE; ReticleOuterAngle = RETICLE_MIN_OUTER_ANGLE + RETICLE_GROWTH_ANGLE; } else { ReticleInnerAngle = RETICLE_MIN_INNER_ANGLE; ReticleOuterAngle = RETICLE_MIN_OUTER_ANGLE; } return true; } private void CreateReticleVertices() { Mesh mesh = new Mesh(); gameObject.AddComponent<MeshFilter>(); GetComponent<MeshFilter>().mesh = mesh; int segments_count = reticleSegments; int vertex_count = (segments_count+1)*2; #region Vertices Vector3[] vertices = new Vector3[vertex_count]; const float kTwoPi = Mathf.PI * 2.0f; int vi = 0; for (int si = 0; si <= segments_count; ++si) { // Add two vertices for every circle segment: one at the beginning of the // prism, and one at the end of the prism. float angle = (float)si / (float)(segments_count) * kTwoPi; float x = Mathf.Sin(angle); float y = Mathf.Cos(angle); vertices[vi++] = new Vector3(x, y, 0.0f); // Outer vertex. vertices[vi++] = new Vector3(x, y, 1.0f); // Inner vertex. } #endregion #region Triangles int indices_count = (segments_count+1)*3*2; int[] indices = new int[indices_count]; int vert = 0; int idx = 0; for (int si = 0; si < segments_count; ++si) { indices[idx++] = vert+1; indices[idx++] = vert; indices[idx++] = vert+2; indices[idx++] = vert+1; indices[idx++] = vert+2; indices[idx++] = vert+3; vert += 2; } #endregion mesh.vertices = vertices; mesh.triangles = indices; mesh.RecalculateBounds(); #if !UNITY_5_5_OR_NEWER // Optimize() is deprecated as of Unity 5.5.0p1. mesh.Optimize(); #endif // !UNITY_5_5_OR_NEWER } }
using Content.Server.Access; using Content.Server.Atmos.Components; using Content.Server.Atmos.EntitySystems; using Content.Server.Construction; using Content.Server.Construction.Components; using Content.Server.Tools; using Content.Server.Tools.Components; using Content.Server.Doors.Components; using Content.Shared.Access.Components; using Content.Shared.Access.Systems; using Content.Shared.Doors; using Content.Shared.Doors.Components; using Content.Shared.Doors.Systems; using Content.Shared.Emag.Systems; using Content.Shared.Interaction; using Content.Shared.Tag; using Robust.Shared.Audio; using Robust.Shared.Containers; using Robust.Shared.Physics.Dynamics; using Robust.Shared.Player; using System.Linq; namespace Content.Server.Doors.Systems; public sealed class DoorSystem : SharedDoorSystem { [Dependency] private readonly ConstructionSystem _constructionSystem = default!; [Dependency] private readonly ToolSystem _toolSystem = default!; [Dependency] private readonly AirtightSystem _airtightSystem = default!; [Dependency] private readonly AccessReaderSystem _accessReaderSystem = default!; [Dependency] private readonly TagSystem _tagSystem = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<DoorComponent, MapInitEvent>(OnMapInit); SubscribeLocalEvent<DoorComponent, InteractUsingEvent>(OnInteractUsing, after: new[] { typeof(ConstructionSystem) }); SubscribeLocalEvent<DoorComponent, PryFinishedEvent>(OnPryFinished); SubscribeLocalEvent<DoorComponent, PryCancelledEvent>(OnPryCancelled); SubscribeLocalEvent<DoorComponent, WeldFinishedEvent>(OnWeldFinished); SubscribeLocalEvent<DoorComponent, WeldCancelledEvent>(OnWeldCancelled); SubscribeLocalEvent<DoorComponent, GotEmaggedEvent>(OnEmagged); } protected override void OnActivate(EntityUid uid, DoorComponent door, ActivateInWorldEvent args) { // TODO once access permissions are shared, move this back to shared. if (args.Handled || !door.ClickOpen) return; TryToggleDoor(uid, door, args.User); args.Handled = true; } protected override void SetCollidable(EntityUid uid, bool collidable, DoorComponent? door = null, PhysicsComponent? physics = null, OccluderComponent? occluder = null) { if (!Resolve(uid, ref door)) return; if (door.ChangeAirtight && TryComp(uid, out AirtightComponent? airtight)) _airtightSystem.SetAirblocked(airtight, collidable); // Pathfinding / AI stuff. RaiseLocalEvent(new AccessReaderChangeMessage(uid, collidable)); base.SetCollidable(uid, collidable, door, physics, occluder); } // TODO AUDIO PREDICT Figure out a better way to handle sound and prediction. For now, this works well enough? // // Currently a client will predict when a door is going to close automatically. So any client in PVS range can just // play their audio locally. Playing it server-side causes an odd delay, while in shared it causes double-audio. // // But if we just do that, then if a door is closed prematurely as the result of an interaction (i.e., using "E" on // an open door), then the audio would only be played for the client performing the interaction. // // So we do this: // - Play audio client-side IF the closing is being predicted (auto-close or predicted interaction) // - Server assumes automated closing is predicted by clients and does not play audio unless otherwise specified. // - Major exception is player interactions, which other players cannot predict // - In that case, send audio to all players, except possibly the interacting player if it was a predicted // interaction. /// <summary> /// Selectively send sound to clients, taking care to not send the double-audio. /// </summary> /// <param name="uid">The audio source</param> /// <param name="sound">The sound</param> /// <param name="predictingPlayer">The user (if any) that instigated an interaction</param> /// <param name="predicted">Whether this interaction would have been predicted. If the predicting player is null, /// this assumes it would have been predicted by all players in PVS range.</param> protected override void PlaySound(EntityUid uid, string sound, AudioParams audioParams, EntityUid? predictingPlayer, bool predicted) { // If this sound would have been predicted by all clients, do not play any audio. if (predicted && predictingPlayer == null) return; var filter = Filter.Pvs(uid); if (predicted) { // This interaction is predicted, but only by the instigating user, who will have played their own sounds. filter.RemoveWhereAttachedEntity(e => e == predictingPlayer); } // send the sound to players. SoundSystem.Play(filter, sound, uid, audioParams); } #region DoAfters /// <summary> /// Weld or pry open a door. /// </summary> private void OnInteractUsing(EntityUid uid, DoorComponent door, InteractUsingEvent args) { if (args.Handled) return; if (!TryComp(args.Used, out ToolComponent? tool)) return; if (tool.Qualities.Contains(door.PryingQuality)) { args.Handled = TryPryDoor(uid, args.Used, args.User, door); return; } if (door.Weldable && tool.Qualities.Contains(door.WeldingQuality)) { args.Handled = TryWeldDoor(uid, args.Used, args.User, door); } } /// <summary> /// Attempt to weld a door shut, or unweld it if it is already welded. This does not actually check if the user /// is holding the correct tool. /// </summary> private bool TryWeldDoor(EntityUid target, EntityUid used, EntityUid user, DoorComponent door) { if (!door.Weldable || door.BeingWelded || door.CurrentlyCrushing.Count > 0) return false; // is the door in a weld-able state? if (door.State != DoorState.Closed && door.State != DoorState.Welded) return false; // perform a do-after delay door.BeingWelded = true; _toolSystem.UseTool(used, user, target, 3f, 3f, door.WeldingQuality, new WeldFinishedEvent(), new WeldCancelledEvent(), target); return true; // we might not actually succeeded, but a do-after has started } /// <summary> /// Pry open a door. This does not check if the user is holding the required tool. /// </summary> private bool TryPryDoor(EntityUid target, EntityUid tool, EntityUid user, DoorComponent door) { if (door.State == DoorState.Welded) return false; var canEv = new BeforeDoorPryEvent(user); RaiseLocalEvent(target, canEv, false); if (canEv.Cancelled) // mark handled, as airlock component will cancel after generating a pop-up & you don't want to pry a tile // under a windoor. return true; var modEv = new DoorGetPryTimeModifierEvent(); RaiseLocalEvent(target, modEv, false); _toolSystem.UseTool(tool, user, target, 0f, modEv.PryTimeModifier * door.PryTime, door.PryingQuality, new PryFinishedEvent(), new PryCancelledEvent(), target); return true; // we might not actually succeeded, but a do-after has started } private void OnWeldCancelled(EntityUid uid, DoorComponent door, WeldCancelledEvent args) { door.BeingWelded = false; } private void OnWeldFinished(EntityUid uid, DoorComponent door, WeldFinishedEvent args) { door.BeingWelded = false; if (!door.Weldable) return; if (door.State == DoorState.Closed) SetState(uid, DoorState.Welded, door); else if (door.State == DoorState.Welded) SetState(uid, DoorState.Closed, door); } private void OnPryCancelled(EntityUid uid, DoorComponent door, PryCancelledEvent args) { door.BeingPried = false; } private void OnPryFinished(EntityUid uid, DoorComponent door, PryFinishedEvent args) { door.BeingPried = false; if (door.State == DoorState.Closed) StartOpening(uid, door); else if (door.State == DoorState.Open) StartClosing(uid, door); } #endregion /// <summary> /// Does the user have the permissions required to open this door? /// </summary> public override bool HasAccess(EntityUid uid, EntityUid? user = null, AccessReaderComponent? access = null) { // TODO network AccessComponent for predicting doors // if there is no "user" we skip the access checks. Access is also ignored in some game-modes. if (user == null || AccessType == AccessTypes.AllowAll) return true; // If the door is on emergency access we skip the checks. if (TryComp<SharedAirlockComponent>(uid, out var airlock) && airlock.EmergencyAccess) return true; if (!Resolve(uid, ref access, false)) return true; var isExternal = access.AccessLists.Any(list => list.Contains("External")); return AccessType switch { // Some game modes modify access rules. AccessTypes.AllowAllIdExternal => !isExternal || _accessReaderSystem.IsAllowed(access, user.Value), AccessTypes.AllowAllNoExternal => !isExternal, _ => _accessReaderSystem.IsAllowed(access, user.Value) }; } /// <summary> /// Open a door if a player or door-bumper (PDA, ID-card) collide with the door. Sadly, bullets no longer /// generate "access denied" sounds as you fire at a door. /// </summary> protected override void HandleCollide(EntityUid uid, DoorComponent door, StartCollideEvent args) { // TODO ACCESS READER move access reader to shared and predict door opening/closing // Then this can be moved to the shared system without mispredicting. if (!door.BumpOpen) return; if (door.State != DoorState.Closed) return; var otherUid = args.OtherFixture.Body.Owner; if (_tagSystem.HasTag(otherUid, "DoorBumpOpener")) TryOpen(uid, door, otherUid); } private void OnMapInit(EntityUid uid, DoorComponent door, MapInitEvent args) { // Ensure that the construction component is aware of the board container. if (TryComp(uid, out ConstructionComponent? construction)) _constructionSystem.AddContainer(uid, "board", construction); // We don't do anything if this is null or empty. if (string.IsNullOrEmpty(door.BoardPrototype)) return; var container = uid.EnsureContainer<Container>("board", out var existed); if (existed & container.ContainedEntities.Count != 0) { // We already contain a board. Note: We don't check if it's the right one! return; } var board = EntityManager.SpawnEntity(door.BoardPrototype, Transform(uid).Coordinates); if(!container.Insert(board)) Logger.Warning($"Couldn't insert board {ToPrettyString(board)} into door {ToPrettyString(uid)}!"); } private void OnEmagged(EntityUid uid, DoorComponent door, GotEmaggedEvent args) { if(TryComp<AirlockComponent>(uid, out var airlockComponent)) { if (door.State == DoorState.Closed) { StartOpening(uid); airlockComponent?.SetBoltsWithAudio(!airlockComponent.IsBolted()); args.Handled = true; } } } } public sealed class PryFinishedEvent : EntityEventArgs { } public sealed class PryCancelledEvent : EntityEventArgs { } public sealed class WeldFinishedEvent : EntityEventArgs { } public sealed class WeldCancelledEvent : EntityEventArgs { }
using System; using System.IO; using System.Collections.Specialized; using System.Net; using System.Text; using System.Web; using System.Security.Cryptography; using Newtonsoft.Json; using System.Security.Cryptography.X509Certificates; using System.Net.Security; using SteamKit2; namespace SteamTrade { public class SteamWeb { public static string Fetch (string url, string method, NameValueCollection data = null, CookieContainer cookies = null, bool ajax = true) { HttpWebResponse response = Request (url, method, data, cookies, ajax); StreamReader reader = new StreamReader (response.GetResponseStream ()); return reader.ReadToEnd (); } public static HttpWebResponse Request (string url, string method, NameValueCollection data = null, CookieContainer cookies = null, bool ajax = true) { HttpWebRequest request = WebRequest.Create (url) as HttpWebRequest; request.Method = method; request.Accept = "text/javascript, text/html, application/xml, text/xml, */*"; request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; request.Host = "steamcommunity.com"; request.UserAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11"; request.Referer = "http://steamcommunity.com/trade/1"; if (ajax) { request.Headers.Add ("X-Requested-With", "XMLHttpRequest"); request.Headers.Add ("X-Prototype-Version", "1.7"); } // Cookies request.CookieContainer = cookies ?? new CookieContainer (); // Request data if (data != null) { string dataString = String.Join ("&", Array.ConvertAll (data.AllKeys, key => String.Format ("{0}={1}", HttpUtility.UrlEncode (key), HttpUtility.UrlEncode (data [key])) ) ); byte[] dataBytes = Encoding.ASCII.GetBytes (dataString); request.ContentLength = dataBytes.Length; Stream requestStream = request.GetRequestStream (); requestStream.Write (dataBytes, 0, dataBytes.Length); } // Get the response return request.GetResponse () as HttpWebResponse; } /// <summary> /// Executes the login by using the Steam Website. /// </summary> public static CookieCollection DoLogin (string username, string password) { var data = new NameValueCollection (); data.Add ("username", username); string response = Fetch ("https://steamcommunity.com/login/getrsakey", "POST", data, null, false); GetRsaKey rsaJSON = JsonConvert.DeserializeObject<GetRsaKey> (response); // Validate if (rsaJSON.success != true) { return null; } //RSA Encryption RSACryptoServiceProvider rsa = new RSACryptoServiceProvider (); RSAParameters rsaParameters = new RSAParameters (); rsaParameters.Exponent = HexToByte (rsaJSON.publickey_exp); rsaParameters.Modulus = HexToByte (rsaJSON.publickey_mod); rsa.ImportParameters (rsaParameters); byte[] bytePassword = Encoding.ASCII.GetBytes (password); byte[] encodedPassword = rsa.Encrypt (bytePassword, false); string encryptedBase64Password = Convert.ToBase64String (encodedPassword); SteamResult loginJson = null; CookieCollection cookies; string steamGuardText = ""; string steamGuardId = ""; do { Console.WriteLine ("SteamWeb: Logging In..."); bool captcha = loginJson != null && loginJson.captcha_needed == true; bool steamGuard = loginJson != null && loginJson.emailauth_needed == true; string time = Uri.EscapeDataString (rsaJSON.timestamp); string capGID = loginJson == null ? null : Uri.EscapeDataString (loginJson.captcha_gid); data = new NameValueCollection (); data.Add ("password", encryptedBase64Password); data.Add ("username", username); // Captcha string capText = ""; if (captcha) { Console.WriteLine ("SteamWeb: Captcha is needed."); System.Diagnostics.Process.Start ("https://steamcommunity.com/public/captcha.php?gid=" + loginJson.captcha_gid); Console.WriteLine ("SteamWeb: Type the captcha:"); capText = Uri.EscapeDataString (Console.ReadLine ()); } data.Add ("captcha_gid", captcha ? capGID : ""); data.Add ("captcha_text", captcha ? capText : ""); // Captcha end // SteamGuard if (steamGuard) { Console.WriteLine ("SteamWeb: SteamGuard is needed."); Console.WriteLine ("SteamWeb: Type the code:"); steamGuardText = Uri.EscapeDataString (Console.ReadLine ()); steamGuardId = loginJson.emailsteamid; } data.Add ("emailauth", steamGuardText); data.Add ("emailsteamid", steamGuardId); // SteamGuard end data.Add ("rsatimestamp", time); HttpWebResponse webResponse = Request ("https://steamcommunity.com/login/dologin/", "POST", data, null, false); StreamReader reader = new StreamReader (webResponse.GetResponseStream ()); string json = reader.ReadToEnd (); loginJson = JsonConvert.DeserializeObject<SteamResult> (json); cookies = webResponse.Cookies; } while (loginJson.captcha_needed == true || loginJson.emailauth_needed == true); if (loginJson.success == true) { CookieContainer c = new CookieContainer (); foreach (Cookie cookie in cookies) { c.Add (cookie); } SubmitCookies (c); return cookies; } else { Console.WriteLine ("SteamWeb Error: " + loginJson.message); return null; } } ///<summary> /// Authenticate using SteamKit2 and ISteamUserAuth. /// This does the same as SteamWeb.DoLogin(), but without contacting the Steam Website. /// </summary> /// <remarks>Should this one doesnt work anymore, use <see cref="SteamWeb.DoLogin"/></remarks> public static bool Authenticate (SteamUser.LoginKeyCallback callback, SteamClient client, out string sessionId, out string token) { sessionId = Convert.ToBase64String (Encoding.UTF8.GetBytes (callback.UniqueID.ToString ())); using (dynamic userAuth = WebAPI.GetInterface ("ISteamUserAuth")) { // generate an AES session key var sessionKey = CryptoHelper.GenerateRandomBlock (32); // rsa encrypt it with the public key for the universe we're on byte[] cryptedSessionKey = null; using (RSACrypto rsa = new RSACrypto (KeyDictionary.GetPublicKey (client.ConnectedUniverse))) { cryptedSessionKey = rsa.Encrypt (sessionKey); } byte[] loginKey = new byte[20]; Array.Copy (Encoding.ASCII.GetBytes (callback.LoginKey), loginKey, callback.LoginKey.Length); // aes encrypt the loginkey with our session key byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt (loginKey, sessionKey); KeyValue authResult; try { authResult = userAuth.AuthenticateUser ( steamid: client.SteamID.ConvertToUInt64 (), sessionkey: HttpUtility.UrlEncode (cryptedSessionKey), encrypted_loginkey: HttpUtility.UrlEncode (cryptedLoginKey), method: "POST" ); } catch (Exception) { token = null; return false; } token = authResult ["token"].AsString (); return true; } } static void SubmitCookies (CookieContainer cookies) { HttpWebRequest w = WebRequest.Create ("https://steamcommunity.com/") as HttpWebRequest; w.Method = "POST"; w.ContentType = "application/x-www-form-urlencoded"; w.CookieContainer = cookies; w.GetResponse ().Close (); return; } static byte[] HexToByte (string hex) { if (hex.Length % 2 == 1) throw new Exception ("The binary key cannot have an odd number of digits"); byte[] arr = new byte[hex.Length >> 1]; int l = hex.Length; for (int i = 0; i < (l >> 1); ++i) { arr [i] = (byte)((GetHexVal (hex [i << 1]) << 4) + (GetHexVal (hex [(i << 1) + 1]))); } return arr; } static int GetHexVal (char hex) { int val = (int)hex; return val - (val < 58 ? 48 : 55); } public static bool ValidateRemoteCertificate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) { // allow all certificates return true; } } // JSON Classes public class GetRsaKey { public bool success { get; set; } public string publickey_mod { get; set; } public string publickey_exp { get; set; } public string timestamp { get; set; } } public class SteamResult { public bool success { get; set; } public string message { get; set; } public bool captcha_needed { get; set; } public string captcha_gid { get; set; } public bool emailauth_needed { get; set; } public string emailsteamid { get; set; } } }
namespace Thinktecture.IdentityServer.Core.Repositories.Migrations.SqlServer { using System.Data.Entity.Migrations; public partial class InitialMigration : DbMigration { public override void Up() { CreateTable( "dbo.GlobalConfiguration", c => new { Id = c.Int(nullable: false, identity: true), SiteName = c.String(nullable: false), IssuerUri = c.String(nullable: false), IssuerContactEmail = c.String(nullable: false), DefaultWSTokenType = c.String(nullable: false), DefaultHttpTokenType = c.String(nullable: false), DefaultTokenLifetime = c.Int(nullable: false), MaximumTokenLifetime = c.Int(nullable: false), SsoCookieLifetime = c.Int(nullable: false), RequireEncryption = c.Boolean(nullable: false), RequireRelyingPartyRegistration = c.Boolean(nullable: false), EnableClientCertificateAuthentication = c.Boolean(nullable: false), EnforceUsersGroupMembership = c.Boolean(nullable: false), HttpPort = c.Int(nullable: false), HttpsPort = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.WSFederationConfiguration", c => new { Id = c.Int(nullable: false, identity: true), Enabled = c.Boolean(nullable: false), EnableAuthentication = c.Boolean(nullable: false), EnableFederation = c.Boolean(nullable: false), EnableHrd = c.Boolean(nullable: false), AllowReplyTo = c.Boolean(nullable: false), RequireReplyToWithinRealm = c.Boolean(nullable: false), RequireSslForReplyTo = c.Boolean(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.KeyMaterialConfiguration", c => new { Id = c.Int(nullable: false, identity: true), SigningCertificateName = c.String(), DecryptionCertificateName = c.String(), RSASigningKey = c.String(), SymmetricSigningKey = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.WSTrustConfiguration", c => new { Id = c.Int(nullable: false, identity: true), Enabled = c.Boolean(nullable: false), EnableMessageSecurity = c.Boolean(nullable: false), EnableMixedModeSecurity = c.Boolean(nullable: false), EnableClientCertificateAuthentication = c.Boolean(nullable: false), EnableFederatedAuthentication = c.Boolean(nullable: false), EnableDelegation = c.Boolean(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.FederationMetadataConfiguration", c => new { Id = c.Int(nullable: false, identity: true), Enabled = c.Boolean(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.OAuth2Configuration", c => new { Id = c.Int(nullable: false, identity: true), Enabled = c.Boolean(nullable: false), EnableConsent = c.Boolean(nullable: false), EnableResourceOwnerFlow = c.Boolean(nullable: false), EnableImplicitFlow = c.Boolean(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.SimpleHttpConfiguration", c => new { Id = c.Int(nullable: false, identity: true), Enabled = c.Boolean(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.DiagnosticsConfiguration", c => new { Id = c.Int(nullable: false, identity: true), EnableFederationMessageTracing = c.Boolean(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.ClientCertificates", c => new { Id = c.Int(nullable: false, identity: true), UserName = c.String(nullable: false), Thumbprint = c.String(nullable: false), Description = c.String(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Delegation", c => new { Id = c.Int(nullable: false, identity: true), UserName = c.String(nullable: false), Realm = c.String(nullable: false), Description = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.RelyingParties", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false), Enabled = c.Boolean(nullable: false), Realm = c.String(nullable: false), TokenLifeTime = c.Int(nullable: false), ReplyTo = c.String(), EncryptingCertificate = c.String(), SymmetricSigningKey = c.String(), ExtraData1 = c.String(), ExtraData2 = c.String(), ExtraData3 = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.IdentityProvider", c => new { ID = c.Int(nullable: false, identity: true), Name = c.String(nullable: false), DisplayName = c.String(nullable: false), Type = c.Int(nullable: false), ShowInHrdSelection = c.Boolean(nullable: false), WSFederationEndpoint = c.String(), IssuerThumbprint = c.String(), ClientID = c.String(), ClientSecret = c.String(), OAuth2ProviderType = c.Int(), Enabled = c.Boolean(nullable: false), }) .PrimaryKey(t => t.ID); CreateTable( "dbo.Client", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false), Description = c.String(nullable: false), ClientId = c.String(nullable: false), ClientSecret = c.String(nullable: false), RedirectUri = c.String(), NativeClient = c.Boolean(nullable: false), AllowImplicitFlow = c.Boolean(nullable: false), AllowResourceOwnerFlow = c.Boolean(nullable: false), AllowCodeFlow = c.Boolean(nullable: false), }) .PrimaryKey(t => t.Id); } public override void Down() { DropTable("dbo.Client"); DropTable("dbo.IdentityProvider"); DropTable("dbo.RelyingParties"); DropTable("dbo.Delegation"); DropTable("dbo.ClientCertificates"); DropTable("dbo.DiagnosticsConfiguration"); DropTable("dbo.SimpleHttpConfiguration"); DropTable("dbo.OAuth2Configuration"); DropTable("dbo.FederationMetadataConfiguration"); DropTable("dbo.WSTrustConfiguration"); DropTable("dbo.KeyMaterialConfiguration"); DropTable("dbo.WSFederationConfiguration"); DropTable("dbo.GlobalConfiguration"); } } }
using MS.Utility; using System; using System.Runtime.InteropServices; using System.Security; using System.Globalization; using System.Windows; using System.Windows.Input; using System.Collections.Generic; using System.Windows.Ink; using MS.Internal.Ink.InkSerializedFormat; using System.Diagnostics; using SR = MS.Internal.PresentationCore.SR; using SRID = MS.Internal.PresentationCore.SRID; namespace MS.Internal.Ink.InkSerializedFormat { /// <summary> /// HuffCodec /// </summary> internal class HuffCodec { /// <summary> /// HuffCodec /// </summary> /// <param name="defaultIndex"></param> internal HuffCodec(uint defaultIndex) { HuffBits bits = new HuffBits(); bits.InitBits(defaultIndex); InitHuffTable(bits); } /// <summary> /// InitHuffTable /// </summary> /// <param name="huffBits"></param> private void InitHuffTable(HuffBits huffBits) { _huffBits = huffBits; uint bitSize = _huffBits.GetSize(); int lowerBound = 1; _mins[0] = 0; for (uint n = 1; n < bitSize; n++) { _mins[n] = (uint)lowerBound; lowerBound += (1 << (_huffBits.GetBitsAtIndex(n) - 1)); } } /// <summary> /// Compress /// </summary> /// <param name="dataXf">can be null</param> /// <param name="input">input array to compress</param> /// <param name="compressedData"></param> internal void Compress(DataXform dataXf, int[] input, List<byte> compressedData) { // // use the writer to write to the list<byte> // BitStreamWriter writer = new BitStreamWriter(compressedData); if (null != dataXf) { dataXf.ResetState(); int xfData = 0; int xfExtra = 0; for (uint i = 0; i < input.Length; i++) { dataXf.Transform(input[i], ref xfData, ref xfExtra); Encode(xfData, xfExtra, writer); } } else { for (uint i = 0; i < input.Length; i++) { Encode(input[i], 0, writer); } } } /// <summary> /// Uncompress /// </summary> /// <param name="dtxf"></param> /// <param name="input"></param> /// <param name="startIndex"></param> /// <param name="outputBuffer"></param> internal uint Uncompress(DataXform dtxf, byte[] input, int startIndex, int[] outputBuffer) { Debug.Assert(input != null); Debug.Assert(input.Length >= 2); Debug.Assert(startIndex == 1); Debug.Assert(outputBuffer != null); Debug.Assert(outputBuffer.Length != 0); BitStreamReader reader = new BitStreamReader(input, startIndex); int xfExtra = 0, xfData = 0; int outputBufferIndex = 0; if (null != dtxf) { dtxf.ResetState(); while (!reader.EndOfStream) { Decode(ref xfData, ref xfExtra, reader); int uncompressed = dtxf.InverseTransform(xfData, xfExtra); Debug.Assert(outputBufferIndex < outputBuffer.Length); outputBuffer[outputBufferIndex++] = uncompressed; if (outputBufferIndex == outputBuffer.Length) { //only write as much as the outputbuffer can hold //this is assumed by calling code break; } } } else { while (!reader.EndOfStream) { Decode(ref xfData, ref xfExtra, reader); Debug.Assert(outputBufferIndex < outputBuffer.Length); outputBuffer[outputBufferIndex++] = xfData; if (outputBufferIndex == outputBuffer.Length) { //only write as much as the outputbuffer can hold //this is assumed by calling code break; } } } return (uint)((reader.CurrentIndex + 1) - startIndex); //we include startIndex in the read count } /// <summary> /// Encode /// </summary> /// <param name="data"></param> /// <param name="extra"></param> /// <param name="writer"></param> /// <returns>number of bits encoded, 0 for failure</returns> internal byte Encode(int data, int extra, BitStreamWriter writer) { if (writer == null) { throw new ArgumentNullException("writer"); } if (data == 0) { writer.Write((byte)0, 1); //more efficent return (byte)1; } // First, encode extra if non-ZERO uint bitSize = _huffBits.GetSize(); if (0 != extra) { // Prefix lenght is 1 more than table size byte extraPrefixLength = (byte)(bitSize + 1); int extraPrefix = ((1 << extraPrefixLength) - 2); writer.Write((uint)extraPrefix, (int)extraPrefixLength); // Encode the extra data first byte extraCodeLength = Encode(extra, 0, writer); // Encode the actual data next byte dataCodeLength = Encode(data, 0, writer); // Return the total code lenght return (byte)((int)extraPrefixLength + (int)extraCodeLength + (int)dataCodeLength); } // Find the absolute value of the data // IMPORTANT : It is extremely important that nData is uint, and NOT int // If it is int, the LONG_MIN will be encoded erroneaouly uint nData = (uint)MathHelper.AbsNoThrow(data); // Find the prefix lenght byte nPrefLen = 1; for (; (nPrefLen < bitSize) && (nData >= _mins[nPrefLen]); ++nPrefLen) ; // Get the data length uint nDataLen = _huffBits.GetBitsAtIndex((uint)nPrefLen - 1); // Find the prefix int nPrefix = ((1 << nPrefLen) - 2); // Append the prefix to the bit stream writer.Write((uint)nPrefix, (int)nPrefLen); // Find the data offset by lower bound // and append sign bit at LSB Debug.Assert(nDataLen > 0 && nDataLen - 1 <= Int32.MaxValue); int dataLenMinusOne = (int)(nDataLen - 1); //can't left shift by a uint, we need to thunk to an int nData = ((((nData - _mins[nPrefLen - 1]) & (uint)((1 << dataLenMinusOne) - 1)) << 1) | (uint)((data < 0) ? 1 : 0)); // Append data into the bit streamdataLenMinusOne Debug.Assert(nDataLen <= Int32.MaxValue); writer.Write(nData, (int)nDataLen); return (byte)((uint)nPrefLen + nDataLen); } /// <summary> /// Decode /// </summary> /// <param name="data"></param> /// <param name="extra"></param> /// <param name="reader"></param> /// <returns>number of bits decoded, 0 for error</returns> internal void Decode(ref int data, ref int extra, BitStreamReader reader) { // Find the prefix length byte prefIndex = 0; while (reader.ReadBit()) { prefIndex++; } // First indicate there is no extra data extra = 0; // More efficient for 0 if (0 == prefIndex) { data = 0; return; } else if (prefIndex < _huffBits.GetSize()) { // Find the data lenght uint nDataLen = _huffBits.GetBitsAtIndex(prefIndex); // Extract the offset data by lower dound with sign bit at LSB long nData = reader.ReadUInt64((int)(byte)nDataLen); // Find the sign bit bool bNeg = ((nData & 0x01) != 0); // Construct the data nData = (nData >> 1) + _mins[prefIndex]; // Adjust the sign bit data = bNeg ? -((int)nData) : (int)nData; // return the bit count read from stream return; } else if (prefIndex == _huffBits.GetSize()) { // This is the special prefix for extra data. // Decode the prefix first int extra2 = 0; int extra2Ignored = 0; Decode(ref extra2, ref extra2Ignored, reader); extra = extra2; // Following is the actual data int data2 = 0; Decode(ref data2, ref extra2Ignored, reader); data = data2; return; } throw new ArgumentException(StrokeCollectionSerializer.ISFDebugMessage("invalid huffman encoded data")); } /// <summary> /// Privates /// </summary> private HuffBits _huffBits; private uint[] _mins = new uint[MaxBAASize]; /// <summary> /// Private statics /// </summary> private static readonly byte MaxBAASize = 10; /// <summary> /// Private helper class /// </summary> private class HuffBits { /// <summary> /// HuffBits /// </summary> internal HuffBits() { _size = 2; _bits[0] = 0; _bits[1] = 32; _matchIndex = 0; _prefixCount = 1; //_findMatch = true; } /// <summary> /// InitBits /// </summary> /// <param name="defaultIndex"></param> /// <returns></returns> internal bool InitBits(uint defaultIndex) { if (defaultIndex < DefaultBAACount && DefaultBAASize[defaultIndex] <= MaxBAASize) { _size = DefaultBAASize[defaultIndex]; _matchIndex = defaultIndex; _prefixCount = _size; //_findMatch = true; _bits = DefaultBAAData[defaultIndex]; return true; } return false; } /// <summary> /// GetSize /// </summary> internal uint GetSize() { return _size; } /// <summary> /// GetBitsAtIndex /// </summary> internal byte GetBitsAtIndex(uint index) { return _bits[(int)index]; } /// <summary> /// Privates /// </summary> private byte[] _bits = new byte[MaxBAASize]; private uint _size; private uint _matchIndex; private uint _prefixCount; //private bool _findMatch; /// <summary> /// Private statics /// </summary> private static readonly byte MaxBAASize = 10; private static readonly byte DefaultBAACount = 8; private static readonly byte[][] DefaultBAAData = new byte[][] { new byte[]{0, 1, 2, 4, 6, 8, 12, 16, 24, 32}, new byte[]{0, 1, 1, 2, 4, 8, 12, 16, 24, 32}, new byte[]{0, 1, 1, 1, 2, 4, 8, 14, 22, 32}, new byte[]{0, 2, 2, 3, 5, 8, 12, 16, 24, 32}, new byte[]{0, 3, 4, 5, 8, 12, 16, 24, 32, 0}, new byte[]{0, 4, 6, 8, 12, 16, 24, 32, 0, 0}, new byte[]{0, 6, 8, 12, 16, 24, 32, 0, 0, 0}, new byte[]{0, 7, 8, 12, 16, 24, 32, 0, 0, 0}, }; private static readonly byte[] DefaultBAASize = new byte[] { 10, 10, 10, 10, 9, 8, 7, 7 }; } } }
// 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 gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.NetworkSecurity.V1Beta1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedNetworkSecurityClientTest { [xunit::FactAttribute] public void GetAuthorizationPolicyRequestObject() { moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAuthorizationPolicyRequest request = new GetAuthorizationPolicyRequest { AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"), }; AuthorizationPolicy expectedResponse = new AuthorizationPolicy { AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Action = AuthorizationPolicy.Types.Action.Deny, Rules = { new AuthorizationPolicy.Types.Rule(), }, }; mockGrpcClient.Setup(x => x.GetAuthorizationPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null); AuthorizationPolicy response = client.GetAuthorizationPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAuthorizationPolicyRequestObjectAsync() { moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAuthorizationPolicyRequest request = new GetAuthorizationPolicyRequest { AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"), }; AuthorizationPolicy expectedResponse = new AuthorizationPolicy { AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Action = AuthorizationPolicy.Types.Action.Deny, Rules = { new AuthorizationPolicy.Types.Rule(), }, }; mockGrpcClient.Setup(x => x.GetAuthorizationPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AuthorizationPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null); AuthorizationPolicy responseCallSettings = await client.GetAuthorizationPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AuthorizationPolicy responseCancellationToken = await client.GetAuthorizationPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetAuthorizationPolicy() { moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAuthorizationPolicyRequest request = new GetAuthorizationPolicyRequest { AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"), }; AuthorizationPolicy expectedResponse = new AuthorizationPolicy { AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Action = AuthorizationPolicy.Types.Action.Deny, Rules = { new AuthorizationPolicy.Types.Rule(), }, }; mockGrpcClient.Setup(x => x.GetAuthorizationPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null); AuthorizationPolicy response = client.GetAuthorizationPolicy(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAuthorizationPolicyAsync() { moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAuthorizationPolicyRequest request = new GetAuthorizationPolicyRequest { AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"), }; AuthorizationPolicy expectedResponse = new AuthorizationPolicy { AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Action = AuthorizationPolicy.Types.Action.Deny, Rules = { new AuthorizationPolicy.Types.Rule(), }, }; mockGrpcClient.Setup(x => x.GetAuthorizationPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AuthorizationPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null); AuthorizationPolicy responseCallSettings = await client.GetAuthorizationPolicyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AuthorizationPolicy responseCancellationToken = await client.GetAuthorizationPolicyAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetAuthorizationPolicyResourceNames() { moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAuthorizationPolicyRequest request = new GetAuthorizationPolicyRequest { AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"), }; AuthorizationPolicy expectedResponse = new AuthorizationPolicy { AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Action = AuthorizationPolicy.Types.Action.Deny, Rules = { new AuthorizationPolicy.Types.Rule(), }, }; mockGrpcClient.Setup(x => x.GetAuthorizationPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null); AuthorizationPolicy response = client.GetAuthorizationPolicy(request.AuthorizationPolicyName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAuthorizationPolicyResourceNamesAsync() { moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAuthorizationPolicyRequest request = new GetAuthorizationPolicyRequest { AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"), }; AuthorizationPolicy expectedResponse = new AuthorizationPolicy { AuthorizationPolicyName = AuthorizationPolicyName.FromProjectLocationAuthorizationPolicy("[PROJECT]", "[LOCATION]", "[AUTHORIZATION_POLICY]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Action = AuthorizationPolicy.Types.Action.Deny, Rules = { new AuthorizationPolicy.Types.Rule(), }, }; mockGrpcClient.Setup(x => x.GetAuthorizationPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AuthorizationPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null); AuthorizationPolicy responseCallSettings = await client.GetAuthorizationPolicyAsync(request.AuthorizationPolicyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AuthorizationPolicy responseCancellationToken = await client.GetAuthorizationPolicyAsync(request.AuthorizationPolicyName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetServerTlsPolicyRequestObject() { moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetServerTlsPolicyRequest request = new GetServerTlsPolicyRequest { ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"), }; ServerTlsPolicy expectedResponse = new ServerTlsPolicy { ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, AllowOpen = false, ServerCertificate = new CertificateProvider(), MtlsPolicy = new ServerTlsPolicy.Types.MTLSPolicy(), }; mockGrpcClient.Setup(x => x.GetServerTlsPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null); ServerTlsPolicy response = client.GetServerTlsPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetServerTlsPolicyRequestObjectAsync() { moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetServerTlsPolicyRequest request = new GetServerTlsPolicyRequest { ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"), }; ServerTlsPolicy expectedResponse = new ServerTlsPolicy { ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, AllowOpen = false, ServerCertificate = new CertificateProvider(), MtlsPolicy = new ServerTlsPolicy.Types.MTLSPolicy(), }; mockGrpcClient.Setup(x => x.GetServerTlsPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ServerTlsPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null); ServerTlsPolicy responseCallSettings = await client.GetServerTlsPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ServerTlsPolicy responseCancellationToken = await client.GetServerTlsPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetServerTlsPolicy() { moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetServerTlsPolicyRequest request = new GetServerTlsPolicyRequest { ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"), }; ServerTlsPolicy expectedResponse = new ServerTlsPolicy { ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, AllowOpen = false, ServerCertificate = new CertificateProvider(), MtlsPolicy = new ServerTlsPolicy.Types.MTLSPolicy(), }; mockGrpcClient.Setup(x => x.GetServerTlsPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null); ServerTlsPolicy response = client.GetServerTlsPolicy(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetServerTlsPolicyAsync() { moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetServerTlsPolicyRequest request = new GetServerTlsPolicyRequest { ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"), }; ServerTlsPolicy expectedResponse = new ServerTlsPolicy { ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, AllowOpen = false, ServerCertificate = new CertificateProvider(), MtlsPolicy = new ServerTlsPolicy.Types.MTLSPolicy(), }; mockGrpcClient.Setup(x => x.GetServerTlsPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ServerTlsPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null); ServerTlsPolicy responseCallSettings = await client.GetServerTlsPolicyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ServerTlsPolicy responseCancellationToken = await client.GetServerTlsPolicyAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetServerTlsPolicyResourceNames() { moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetServerTlsPolicyRequest request = new GetServerTlsPolicyRequest { ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"), }; ServerTlsPolicy expectedResponse = new ServerTlsPolicy { ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, AllowOpen = false, ServerCertificate = new CertificateProvider(), MtlsPolicy = new ServerTlsPolicy.Types.MTLSPolicy(), }; mockGrpcClient.Setup(x => x.GetServerTlsPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null); ServerTlsPolicy response = client.GetServerTlsPolicy(request.ServerTlsPolicyName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetServerTlsPolicyResourceNamesAsync() { moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetServerTlsPolicyRequest request = new GetServerTlsPolicyRequest { ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"), }; ServerTlsPolicy expectedResponse = new ServerTlsPolicy { ServerTlsPolicyName = ServerTlsPolicyName.FromProjectLocationServerTlsPolicy("[PROJECT]", "[LOCATION]", "[SERVER_TLS_POLICY]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, AllowOpen = false, ServerCertificate = new CertificateProvider(), MtlsPolicy = new ServerTlsPolicy.Types.MTLSPolicy(), }; mockGrpcClient.Setup(x => x.GetServerTlsPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ServerTlsPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null); ServerTlsPolicy responseCallSettings = await client.GetServerTlsPolicyAsync(request.ServerTlsPolicyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ServerTlsPolicy responseCancellationToken = await client.GetServerTlsPolicyAsync(request.ServerTlsPolicyName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetClientTlsPolicyRequestObject() { moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetClientTlsPolicyRequest request = new GetClientTlsPolicyRequest { ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"), }; ClientTlsPolicy expectedResponse = new ClientTlsPolicy { ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Sni = "snif6a20ff7", ClientCertificate = new CertificateProvider(), ServerValidationCa = { new ValidationCA(), }, }; mockGrpcClient.Setup(x => x.GetClientTlsPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null); ClientTlsPolicy response = client.GetClientTlsPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetClientTlsPolicyRequestObjectAsync() { moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetClientTlsPolicyRequest request = new GetClientTlsPolicyRequest { ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"), }; ClientTlsPolicy expectedResponse = new ClientTlsPolicy { ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Sni = "snif6a20ff7", ClientCertificate = new CertificateProvider(), ServerValidationCa = { new ValidationCA(), }, }; mockGrpcClient.Setup(x => x.GetClientTlsPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ClientTlsPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null); ClientTlsPolicy responseCallSettings = await client.GetClientTlsPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ClientTlsPolicy responseCancellationToken = await client.GetClientTlsPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetClientTlsPolicy() { moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetClientTlsPolicyRequest request = new GetClientTlsPolicyRequest { ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"), }; ClientTlsPolicy expectedResponse = new ClientTlsPolicy { ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Sni = "snif6a20ff7", ClientCertificate = new CertificateProvider(), ServerValidationCa = { new ValidationCA(), }, }; mockGrpcClient.Setup(x => x.GetClientTlsPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null); ClientTlsPolicy response = client.GetClientTlsPolicy(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetClientTlsPolicyAsync() { moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetClientTlsPolicyRequest request = new GetClientTlsPolicyRequest { ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"), }; ClientTlsPolicy expectedResponse = new ClientTlsPolicy { ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Sni = "snif6a20ff7", ClientCertificate = new CertificateProvider(), ServerValidationCa = { new ValidationCA(), }, }; mockGrpcClient.Setup(x => x.GetClientTlsPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ClientTlsPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null); ClientTlsPolicy responseCallSettings = await client.GetClientTlsPolicyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ClientTlsPolicy responseCancellationToken = await client.GetClientTlsPolicyAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetClientTlsPolicyResourceNames() { moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetClientTlsPolicyRequest request = new GetClientTlsPolicyRequest { ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"), }; ClientTlsPolicy expectedResponse = new ClientTlsPolicy { ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Sni = "snif6a20ff7", ClientCertificate = new CertificateProvider(), ServerValidationCa = { new ValidationCA(), }, }; mockGrpcClient.Setup(x => x.GetClientTlsPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null); ClientTlsPolicy response = client.GetClientTlsPolicy(request.ClientTlsPolicyName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetClientTlsPolicyResourceNamesAsync() { moq::Mock<NetworkSecurity.NetworkSecurityClient> mockGrpcClient = new moq::Mock<NetworkSecurity.NetworkSecurityClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetClientTlsPolicyRequest request = new GetClientTlsPolicyRequest { ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"), }; ClientTlsPolicy expectedResponse = new ClientTlsPolicy { ClientTlsPolicyName = ClientTlsPolicyName.FromProjectLocationClientTlsPolicy("[PROJECT]", "[LOCATION]", "[CLIENT_TLS_POLICY]"), Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Sni = "snif6a20ff7", ClientCertificate = new CertificateProvider(), ServerValidationCa = { new ValidationCA(), }, }; mockGrpcClient.Setup(x => x.GetClientTlsPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ClientTlsPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NetworkSecurityClient client = new NetworkSecurityClientImpl(mockGrpcClient.Object, null); ClientTlsPolicy responseCallSettings = await client.GetClientTlsPolicyAsync(request.ClientTlsPolicyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ClientTlsPolicy responseCancellationToken = await client.GetClientTlsPolicyAsync(request.ClientTlsPolicyName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
#define PRETTY //Comment out when you no longer need to read JSON to disable pretty Print system-wide //Using doubles will cause errors in VectorTemplates.cs; Unity speaks floats #define USEFLOAT //Use floats for numbers instead of doubles (enable if you're getting too many significant digits in string output) //#define POOLING //Currently using a build setting for this one (also it's experimental) using System.Diagnostics; using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Text; using Debug = UnityEngine.Debug; /* * http://www.opensource.org/licenses/lgpl-2.1.php * JSONObject class * for use with Unity * Copyright Matt Schoen 2010 - 2013 */ public class JSONObject { #if POOLING const int MAX_POOL_SIZE = 10000; public static Queue<JSONObject> releaseQueue = new Queue<JSONObject>(); #endif const int MAX_DEPTH = 100; const string INFINITY = "\"INFINITY\""; const string NEGINFINITY = "\"NEGINFINITY\""; const string NaN = "\"NaN\""; static readonly char[] WHITESPACE = new[] { ' ', '\r', '\n', '\t' }; public enum Type { NULL, STRING, NUMBER, OBJECT, ARRAY, BOOL, BAKED } public bool isContainer { get { return (type == Type.ARRAY || type == Type.OBJECT); } } public Type type = Type.NULL; public int Count { get { if(list == null) return -1; return list.Count; } } public List<JSONObject> list; public List<string> keys; public string str; #if USEFLOAT public float n; public float f { get { return n; } } #else public double n; public float f { get { return (float)n; } } #endif public bool b; public delegate void AddJSONConents(JSONObject self); public static JSONObject nullJO { get { return Create(Type.NULL); } } //an empty, null object public static JSONObject obj { get { return Create(Type.OBJECT); } } //an empty object public static JSONObject arr { get { return Create(Type.ARRAY); } } //an empty array public JSONObject(Type t) { type = t; switch(t) { case Type.ARRAY: list = new List<JSONObject>(); break; case Type.OBJECT: list = new List<JSONObject>(); keys = new List<string>(); break; } } public JSONObject(bool b) { type = Type.BOOL; this.b = b; } #if USEFLOAT public JSONObject(float f) { type = Type.NUMBER; n = f; } #else public JSONObject(double d) { type = Type.NUMBER; n = d; } #endif public JSONObject(Dictionary<string, string> dic) { type = Type.OBJECT; keys = new List<string>(); list = new List<JSONObject>(); //Not sure if it's worth removing the foreach here foreach(KeyValuePair<string, string> kvp in dic) { keys.Add(kvp.Key); list.Add(CreateStringObject(kvp.Value)); } } public JSONObject(Dictionary<string, JSONObject> dic) { type = Type.OBJECT; keys = new List<string>(); list = new List<JSONObject>(); //Not sure if it's worth removing the foreach here foreach(KeyValuePair<string, JSONObject> kvp in dic) { keys.Add(kvp.Key); list.Add(kvp.Value); } } public JSONObject(AddJSONConents content) { content.Invoke(this); } public JSONObject(JSONObject[] objs) { type = Type.ARRAY; list = new List<JSONObject>(objs); } //Convenience function for creating a JSONObject containing a string. This is not part of the constructor so that malformed JSON data doesn't just turn into a string object public static JSONObject StringObject(string val) { return CreateStringObject(val); } public void Absorb(JSONObject obj) { list.AddRange(obj.list); keys.AddRange(obj.keys); str = obj.str; n = obj.n; b = obj.b; type = obj.type; } public static JSONObject Create() { #if POOLING JSONObject result = null; while(result == null && releaseQueue.Count > 0) { result = releaseQueue.Dequeue(); #if DEV //The following cases should NEVER HAPPEN (but they do...) if(result == null) Debug.Log("wtf " + releaseQueue.Count); else if(result.list != null) Debug.Log("wtflist " + result.list.Count); #endif } if(result != null) return result; #endif return new JSONObject(); } public static JSONObject Create(Type t) { JSONObject obj = Create(); obj.type = t; switch(t) { case Type.ARRAY: obj.list = new List<JSONObject>(); break; case Type.OBJECT: obj.list = new List<JSONObject>(); obj.keys = new List<string>(); break; } return obj; } public static JSONObject Create(bool val) { JSONObject obj = Create(); obj.type = Type.BOOL; obj.b = val; return obj; } public static JSONObject Create(float val) { JSONObject obj = Create(); obj.type = Type.NUMBER; obj.n = val; return obj; } public static JSONObject Create(int val) { JSONObject obj = Create(); obj.type = Type.NUMBER; obj.n = val; return obj; } public static JSONObject CreateStringObject(string val) { JSONObject obj = Create(); obj.type = Type.STRING; obj.str = val; return obj; } public static JSONObject CreateBakedObject(string val) { JSONObject bakedObject = Create(); bakedObject.type = Type.BAKED; bakedObject.str = val; return bakedObject; } /// <summary> /// Create a JSONObject by parsing string data /// </summary> /// <param name="val">The string to be parsed</param> /// <param name="maxDepth">The maximum depth for the parser to search. Set this to to 1 for the first level, /// 2 for the first 2 levels, etc. It defaults to -2 because -1 is the depth value that is parsed (see below)</param> /// <param name="storeExcessLevels">Whether to store levels beyond maxDepth in baked JSONObjects</param> /// <param name="strict">Whether to be strict in the parsing. For example, non-strict parsing will successfully /// parse "a string" into a string-type </param> /// <returns></returns> /// // Default parameters fix public static JSONObject Create(string val) { return Create(val, -2, false, false); } public static JSONObject Create(string val, int maxDepth) { return Create(val, maxDepth, false, false); } public static JSONObject Create(string val, int maxDepth, bool storeExcessLevels) { return Create(val, maxDepth, storeExcessLevels, false); } public static JSONObject Create(string val, int maxDepth, bool storeExcessLevels, bool strict) { JSONObject obj = Create(); obj.Parse(val, maxDepth, storeExcessLevels, strict); return obj; } public static JSONObject Create(AddJSONConents content) { JSONObject obj = Create(); content.Invoke(obj); return obj; } public static JSONObject Create(Dictionary<string, string> dic) { JSONObject obj = Create(); obj.type = Type.OBJECT; obj.keys = new List<string>(); obj.list = new List<JSONObject>(); //Not sure if it's worth removing the foreach here foreach(KeyValuePair<string, string> kvp in dic) { obj.keys.Add(kvp.Key); obj.list.Add(CreateStringObject(kvp.Value)); } return obj; } public JSONObject() { } #region PARSE // Default parameters fix public JSONObject(string str){ Parse(str, -2, false, false); } public JSONObject(string str, int maxDepth, bool storeExcessLevels, bool strict) { //create a new JSONObject from a string (this will also create any children, and parse the whole string) Parse(str, maxDepth, storeExcessLevels, strict); } // Default parameters fix void Parse(string str) { Parse(str, -2, false, false); } void Parse(string str, int maxDepth, bool storeExcessLevels, bool strict) { if(!string.IsNullOrEmpty(str)) { str = str.Trim(WHITESPACE); if(strict) { if(str[0] != '[' && str[0] != '{') { type = Type.NULL; Debug.LogWarning("Improper (strict) JSON formatting. First character must be [ or {"); return; } } if(str.Length > 0) { if(string.Compare(str, "true", true) == 0) { type = Type.BOOL; b = true; } else if(string.Compare(str, "false", true) == 0) { type = Type.BOOL; b = false; } else if(string.Compare(str, "null", true) == 0) { type = Type.NULL; #if USEFLOAT } else if(str == INFINITY) { type = Type.NUMBER; n = float.PositiveInfinity; } else if(str == NEGINFINITY) { type = Type.NUMBER; n = float.NegativeInfinity; } else if(str == NaN) { type = Type.NUMBER; n = float.NaN; #else } else if(str == INFINITY) { type = Type.NUMBER; n = double.PositiveInfinity; } else if(str == NEGINFINITY) { type = Type.NUMBER; n = double.NegativeInfinity; } else if(str == NaN) { type = Type.NUMBER; n = double.NaN; #endif } else if(str[0] == '"') { type = Type.STRING; this.str = str.Substring(1, str.Length - 2); } else { int tokenTmp = 1; /* * Checking for the following formatting (www.json.org) * object - {"field1":value,"field2":value} * array - [value,value,value] * value - string - "string" * - number - 0.0 * - bool - true -or- false * - null - null */ int offset = 0; switch(str[offset]) { case '{': type = Type.OBJECT; keys = new List<string>(); list = new List<JSONObject>(); break; case '[': type = Type.ARRAY; list = new List<JSONObject>(); break; default: try { #if USEFLOAT n = System.Convert.ToSingle(str); #else n = System.Convert.ToDouble(str); #endif type = Type.NUMBER; } catch(System.FormatException) { type = Type.NULL; Debug.LogWarning("improper JSON formatting:" + str); } return; } string propName = ""; bool openQuote = false; bool inProp = false; int depth = 0; while(++offset < str.Length) { if(System.Array.IndexOf(WHITESPACE, str[offset]) > -1) continue; if(str[offset] == '\\') { offset += 1; continue; } if(str[offset] == '"') { if(openQuote) { if(!inProp && depth == 0 && type == Type.OBJECT) propName = str.Substring(tokenTmp + 1, offset - tokenTmp - 1); openQuote = false; } else { if(depth == 0 && type == Type.OBJECT) tokenTmp = offset; openQuote = true; } } if(openQuote) continue; if(type == Type.OBJECT && depth == 0) { if(str[offset] == ':') { tokenTmp = offset + 1; inProp = true; } } if(str[offset] == '[' || str[offset] == '{') { depth++; } else if(str[offset] == ']' || str[offset] == '}') { depth--; } //if (encounter a ',' at top level) || a closing ]/} if((str[offset] == ',' && depth == 0) || depth < 0) { inProp = false; string inner = str.Substring(tokenTmp, offset - tokenTmp).Trim(WHITESPACE); if(inner.Length > 0) { if(type == Type.OBJECT) keys.Add(propName); if(maxDepth != -1) //maxDepth of -1 is the end of the line list.Add(Create(inner, (maxDepth < -1) ? -2 : maxDepth - 1)); else if(storeExcessLevels) list.Add(CreateBakedObject(inner)); } tokenTmp = offset + 1; } } } } else type = Type.NULL; } else type = Type.NULL; //If the string is missing, this is a null //Profiler.EndSample(); } #endregion public bool IsNumber { get { return type == Type.NUMBER; } } public bool IsNull { get { return type == Type.NULL; } } public bool IsString { get { return type == Type.STRING; } } public bool IsBool { get { return type == Type.BOOL; } } public bool IsArray { get { return type == Type.ARRAY; } } public bool IsObject { get { return type == Type.OBJECT; } } public void Add(bool val) { Add(Create(val)); } public void Add(float val) { Add(Create(val)); } public void Add(int val) { Add(Create(val)); } public void Add(string str) { Add(CreateStringObject(str)); } public void Add(AddJSONConents content) { Add(Create(content)); } public void Add(JSONObject obj) { if(obj) { //Don't do anything if the object is null if(type != Type.ARRAY) { type = Type.ARRAY; //Congratulations, son, you're an ARRAY now if(list == null) list = new List<JSONObject>(); } list.Add(obj); } } public void AddField(string name, bool val) { AddField(name, Create(val)); } public void AddField(string name, float val) { AddField(name, Create(val)); } public void AddField(string name, int val) { AddField(name, Create(val)); } public void AddField(string name, AddJSONConents content) { AddField(name, Create(content)); } public void AddField(string name, string val) { AddField(name, CreateStringObject(val)); } public void AddField(string name, JSONObject obj) { if(obj) { //Don't do anything if the object is null if(type != Type.OBJECT) { if(keys == null) keys = new List<string>(); if(type == Type.ARRAY) { for(int i = 0; i < list.Count; i++) keys.Add(i + ""); } else if(list == null) list = new List<JSONObject>(); type = Type.OBJECT; //Congratulations, son, you're an OBJECT now } keys.Add(name); list.Add(obj); } } public void SetField(string name, bool val) { SetField(name, Create(val)); } public void SetField(string name, float val) { SetField(name, Create(val)); } public void SetField(string name, int val) { SetField(name, Create(val)); } public void SetField(string name, JSONObject obj) { if(HasField(name)) { list.Remove(this[name]); keys.Remove(name); } AddField(name, obj); } public void RemoveField(string name) { if(keys.IndexOf(name) > -1) { list.RemoveAt(keys.IndexOf(name)); keys.Remove(name); } } public delegate void FieldNotFound(string name); public delegate void GetFieldResponse(JSONObject obj); // Default parameters fix public void GetField(ref bool field, string name) { GetField(ref field, name, null); } public void GetField(ref bool field, string name, FieldNotFound fail) { if(type == Type.OBJECT) { int index = keys.IndexOf(name); if(index >= 0) { field = list[index].b; return; } } if(fail != null) fail.Invoke(name); } #if USEFLOAT // Default parameters fix public void GetField(ref float field, string name) { GetField(ref field, name, null); } public void GetField(ref float field, string name, FieldNotFound fail) { #else // Default parameters fix public void GetField(ref double field, string name) { GetField(ref field, name, null); } public void GetField(ref double field, string name, FieldNotFound fail) { #endif if(type == Type.OBJECT) { int index = keys.IndexOf(name); if(index >= 0) { field = list[index].n; return; } } if(fail != null) fail.Invoke(name); } // Default parameters fix public void GetField(ref int field, string name) { GetField(ref field, name, null); } public void GetField(ref int field, string name, FieldNotFound fail) { if(type == Type.OBJECT) { int index = keys.IndexOf(name); if(index >= 0) { field = (int)list[index].n; return; } } if(fail != null) fail.Invoke(name); } // Default parameters fix public void GetField(ref uint field, string name) { GetField(ref field, name, null); } public void GetField(ref uint field, string name, FieldNotFound fail) { if(type == Type.OBJECT) { int index = keys.IndexOf(name); if(index >= 0) { field = (uint)list[index].n; return; } } if(fail != null) fail.Invoke(name); } // Default parameters fix public void GetField(ref string field, string name) { GetField(ref field, name, null); } public void GetField(ref string field, string name, FieldNotFound fail) { if(type == Type.OBJECT) { int index = keys.IndexOf(name); if(index >= 0) { field = list[index].str; return; } } if(fail != null) fail.Invoke(name); } // Default parameters fix public void GetField(string name, GetFieldResponse response) { GetField(name, response, null); } public void GetField(string name, GetFieldResponse response, FieldNotFound fail) { if(response != null && type == Type.OBJECT) { int index = keys.IndexOf(name); if(index >= 0) { response.Invoke(list[index]); return; } } if(fail != null) fail.Invoke(name); } public JSONObject GetField(string name) { if(type == Type.OBJECT) for(int i = 0; i < keys.Count; i++) if(keys[i] == name) return list[i]; return null; } public bool HasFields(string[] names) { for(int i = 0; i < names.Length; i++) if(!keys.Contains(names[i])) return false; return true; } public bool HasField(string name) { if(type == Type.OBJECT) for(int i = 0; i < keys.Count; i++) if(keys[i] == name) return true; return false; } public void Clear() { type = Type.NULL; if(list != null) list.Clear(); if(keys != null) keys.Clear(); str = ""; n = 0; b = false; } /// <summary> /// Copy a JSONObject. This could probably work better /// </summary> /// <returns></returns> public JSONObject Copy() { return Create(Print()); } /* * The Merge function is experimental. Use at your own risk. */ public void Merge(JSONObject obj) { MergeRecur(this, obj); } /// <summary> /// Merge object right into left recursively /// </summary> /// <param name="left">The left (base) object</param> /// <param name="right">The right (new) object</param> static void MergeRecur(JSONObject left, JSONObject right) { if(left.type == Type.NULL) left.Absorb(right); else if(left.type == Type.OBJECT && right.type == Type.OBJECT) { for(int i = 0; i < right.list.Count; i++) { string key = right.keys[i]; if(right[i].isContainer) { if(left.HasField(key)) MergeRecur(left[key], right[i]); else left.AddField(key, right[i]); } else { if(left.HasField(key)) left.SetField(key, right[i]); else left.AddField(key, right[i]); } } } else if(left.type == Type.ARRAY && right.type == Type.ARRAY) { if(right.Count > left.Count) { Debug.LogError("Cannot merge arrays when right object has more elements"); return; } for(int i = 0; i < right.list.Count; i++) { if(left[i].type == right[i].type) { //Only overwrite with the same type if(left[i].isContainer) MergeRecur(left[i], right[i]); else { left[i] = right[i]; } } } } } public void Bake() { if(type != Type.BAKED) { str = Print(); type = Type.BAKED; } } public IEnumerable BakeAsync() { if(type != Type.BAKED) { foreach(string s in PrintAsync()) { if(s == null) yield return s; else { str = s; } } type = Type.BAKED; } } #pragma warning disable 219 // Default parameters fix public string Print() { return Print(false); } public string Print(bool pretty) { StringBuilder builder = new StringBuilder(); Stringify(0, builder, pretty); return builder.ToString(); } // Default parameters fix public IEnumerable<string> PrintAsync() { return PrintAsync(false); } public IEnumerable<string> PrintAsync(bool pretty) { StringBuilder builder = new StringBuilder(); printWatch.Reset(); printWatch.Start(); foreach(IEnumerable e in StringifyAsync(0, builder, pretty)) { yield return null; } yield return builder.ToString(); } #pragma warning restore 219 #region STRINGIFY const float maxFrameTime = 0.008f; static readonly Stopwatch printWatch = new Stopwatch(); // Default parameters fix IEnumerable StringifyAsync(int depth, StringBuilder builder) { return StringifyAsync(depth, builder, false); } IEnumerable StringifyAsync(int depth, StringBuilder builder, bool pretty) { //Convert the JSONObject into a string //Profiler.BeginSample("JSONprint"); if(depth++ > MAX_DEPTH) { Debug.Log("reached max depth!"); yield break; } if(printWatch.Elapsed.TotalSeconds > maxFrameTime) { printWatch.Reset(); yield return null; printWatch.Start(); } switch(type) { case Type.BAKED: builder.Append(str); break; case Type.STRING: builder.AppendFormat("\"{0}\"", str); break; case Type.NUMBER: #if USEFLOAT if(float.IsInfinity(n)) builder.Append(INFINITY); else if(float.IsNegativeInfinity(n)) builder.Append(NEGINFINITY); else if(float.IsNaN(n)) builder.Append(NaN); #else if(double.IsInfinity(n)) builder.Append(INFINITY); else if(double.IsNegativeInfinity(n)) builder.Append(NEGINFINITY); else if(double.IsNaN(n)) builder.Append(NaN); #endif else builder.Append(n.ToString()); break; case Type.OBJECT: builder.Append("{"); if(list.Count > 0) { #if(PRETTY) //for a bit more readability, comment the define above to disable system-wide if(pretty) builder.Append("\n"); #endif for(int i = 0; i < list.Count; i++) { string key = keys[i]; JSONObject obj = list[i]; if(obj) { #if(PRETTY) if(pretty) for(int j = 0; j < depth; j++) builder.Append("\t"); //for a bit more readability #endif builder.AppendFormat("\"{0}\":", key); foreach(IEnumerable e in obj.StringifyAsync(depth, builder, pretty)) yield return e; builder.Append(","); #if(PRETTY) if(pretty) builder.Append("\n"); #endif } } #if(PRETTY) if(pretty) builder.Length -= 2; else #endif builder.Length--; } #if(PRETTY) if(pretty && list.Count > 0) { builder.Append("\n"); for(int j = 0; j < depth - 1; j++) builder.Append("\t"); //for a bit more readability } #endif builder.Append("}"); break; case Type.ARRAY: builder.Append("["); if(list.Count > 0) { #if(PRETTY) if(pretty) builder.Append("\n"); //for a bit more readability #endif for(int i = 0; i < list.Count; i++) { if(list[i]) { #if(PRETTY) if(pretty) for(int j = 0; j < depth; j++) builder.Append("\t"); //for a bit more readability #endif foreach(IEnumerable e in list[i].StringifyAsync(depth, builder, pretty)) yield return e; builder.Append(","); #if(PRETTY) if(pretty) builder.Append("\n"); //for a bit more readability #endif } } #if(PRETTY) if(pretty) builder.Length -= 2; else #endif builder.Length--; } #if(PRETTY) if(pretty && list.Count > 0) { builder.Append("\n"); for(int j = 0; j < depth - 1; j++) builder.Append("\t"); //for a bit more readability } #endif builder.Append("]"); break; case Type.BOOL: if(b) builder.Append("true"); else builder.Append("false"); break; case Type.NULL: builder.Append("null"); break; } //Profiler.EndSample(); } //TODO: Refactor Stringify functions to share core logic /* * I know, I know, this is really bad form. It turns out that there is a * significant amount of garbage created when calling as a coroutine, so this * method is duplicated. Hopefully there won't be too many future changes, but * I would still like a more elegant way to optionaly yield */ // Default parameters fix void Stringify(int depth, StringBuilder builder){ Stringify(depth, builder, false); } void Stringify(int depth, StringBuilder builder, bool pretty) { //Convert the JSONObject into a string //Profiler.BeginSample("JSONprint"); if(depth++ > MAX_DEPTH) { Debug.Log("reached max depth!"); return; } switch(type) { case Type.BAKED: builder.Append(str); break; case Type.STRING: builder.AppendFormat("\"{0}\"", str); break; case Type.NUMBER: #if USEFLOAT if(float.IsInfinity(n)) builder.Append(INFINITY); else if(float.IsNegativeInfinity(n)) builder.Append(NEGINFINITY); else if(float.IsNaN(n)) builder.Append(NaN); #else if(double.IsInfinity(n)) builder.Append(INFINITY); else if(double.IsNegativeInfinity(n)) builder.Append(NEGINFINITY); else if(double.IsNaN(n)) builder.Append(NaN); #endif else builder.Append(n.ToString()); break; case Type.OBJECT: builder.Append("{"); if(list.Count > 0) { #if(PRETTY) //for a bit more readability, comment the define above to disable system-wide if(pretty) builder.Append("\n"); #endif for(int i = 0; i < list.Count; i++) { string key = keys[i]; JSONObject obj = list[i]; if(obj) { #if(PRETTY) if(pretty) for(int j = 0; j < depth; j++) builder.Append("\t"); //for a bit more readability #endif builder.AppendFormat("\"{0}\":", key); obj.Stringify(depth, builder, pretty); builder.Append(","); #if(PRETTY) if(pretty) builder.Append("\n"); #endif } } #if(PRETTY) if(pretty) builder.Length -= 2; else #endif builder.Length--; } #if(PRETTY) if(pretty && list.Count > 0) { builder.Append("\n"); for(int j = 0; j < depth - 1; j++) builder.Append("\t"); //for a bit more readability } #endif builder.Append("}"); break; case Type.ARRAY: builder.Append("["); if(list.Count > 0) { #if(PRETTY) if(pretty) builder.Append("\n"); //for a bit more readability #endif for(int i = 0; i < list.Count; i++) { if(list[i]) { #if(PRETTY) if(pretty) for(int j = 0; j < depth; j++) builder.Append("\t"); //for a bit more readability #endif list[i].Stringify(depth, builder, pretty); builder.Append(","); #if(PRETTY) if(pretty) builder.Append("\n"); //for a bit more readability #endif } } #if(PRETTY) if(pretty) builder.Length -= 2; else #endif builder.Length--; } #if(PRETTY) if(pretty && list.Count > 0) { builder.Append("\n"); for(int j = 0; j < depth - 1; j++) builder.Append("\t"); //for a bit more readability } #endif builder.Append("]"); break; case Type.BOOL: if(b) builder.Append("true"); else builder.Append("false"); break; case Type.NULL: builder.Append("null"); break; } //Profiler.EndSample(); } #endregion public static implicit operator WWWForm(JSONObject obj) { WWWForm form = new WWWForm(); for(int i = 0; i < obj.list.Count; i++) { string key = i + ""; if(obj.type == Type.OBJECT) key = obj.keys[i]; string val = obj.list[i].ToString(); if(obj.list[i].type == Type.STRING) val = val.Replace("\"", ""); form.AddField(key, val); } return form; } public JSONObject this[int index] { get { if(list.Count > index) return list[index]; return null; } set { if(list.Count > index) list[index] = value; } } public JSONObject this[string index] { get { return GetField(index); } set { SetField(index, value); } } public override string ToString() { return Print(); } public string ToString(bool pretty) { return Print(pretty); } public Dictionary<string, string> ToDictionary() { if(type == Type.OBJECT) { Dictionary<string, string> result = new Dictionary<string, string>(); for(int i = 0; i < list.Count; i++) { JSONObject val = list[i]; switch(val.type) { case Type.STRING: result.Add(keys[i], val.str); break; case Type.NUMBER: result.Add(keys[i], val.n + ""); break; case Type.BOOL: result.Add(keys[i], val.b + ""); break; default: Debug.LogWarning("Omitting object: " + keys[i] + " in dictionary conversion"); break; } } return result; } Debug.LogWarning("Tried to turn non-Object JSONObject into a dictionary"); return null; } public static implicit operator bool(JSONObject o) { return o != null; } #if POOLING static bool pool = true; public static void ClearPool() { pool = false; releaseQueue.Clear(); pool = true; } ~JSONObject() { if(pool && releaseQueue.Count < MAX_POOL_SIZE) { type = Type.NULL; list = null; keys = null; str = ""; n = 0; b = false; releaseQueue.Enqueue(this); } } #endif }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== #if FEATURE_ENCODINGNLS namespace System.Text { using System; using System.Diagnostics.Contracts; using System.Collections; using System.Runtime.Remoting; using System.Globalization; using System.Threading; using Win32Native = Microsoft.Win32.Win32Native; // This class overrides Encoding with the things we need for our NLS Encodings // // All of the GetBytes/Chars GetByte/CharCount methods are just wrappers for the pointer // plus decoder/encoder method that is our real workhorse. Note that this is an internal // class, so our public classes cannot derive from this class. Because of this, all of the // GetBytes/Chars GetByte/CharCount wrapper methods are duplicated in all of our public // encodings, which currently include: // // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, & UnicodeEncoding // // So if you change the wrappers in this class, you must change the wrappers in the other classes // as well because they should have the same behavior. // [System.Runtime.InteropServices.ComVisible(true)] [Serializable] internal abstract class EncodingNLS : Encoding { protected EncodingNLS(int codePage) : base(codePage) { } // Returns the number of bytes required to encode a range of characters in // a character array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetByteCount(char[] chars, int index, int count) { // Validate input parameters if (chars == null) throw new ArgumentNullException("chars", Environment.GetResourceString("ArgumentNull_Array")); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (chars.Length - index < count) throw new ArgumentOutOfRangeException("chars", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); Contract.EndContractBlock(); // If no input, return 0, avoid fixed empty array problem if (chars.Length == 0) return 0; // Just call the pointer version fixed (char* pChars = chars) return GetByteCount(pChars + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetByteCount(String s) { // Validate input if (s==null) throw new ArgumentNullException("s"); Contract.EndContractBlock(); fixed (char* pChars = s) return GetByteCount(pChars, s.Length, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecurityCritical] // auto-generated public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters if (chars == null) throw new ArgumentNullException("chars", Environment.GetResourceString("ArgumentNull_Array")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // Call it with empty encoder return GetByteCount(chars, count, null); } // Parent method is safe. // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) throw new ArgumentNullException((s == null ? "s" : "bytes"), Environment.GetResourceString("ArgumentNull_Array")); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (s.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("s", Environment.GetResourceString("ArgumentOutOfRange_IndexCount")); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.EndContractBlock(); int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty arrays if (bytes.Length == 0) bytes = new byte[1]; fixed (char* pChars = s) fixed ( byte* pBytes = bytes) return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), Environment.GetResourceString("ArgumentNull_Array")); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("chars", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.EndContractBlock(); // If nothing to encode return 0, avoid fixed problem if (chars.Length == 0) return 0; // Just call pointer version int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty arrays if (bytes.Length == 0) bytes = new byte[1]; fixed (char* pChars = chars) fixed (byte* pBytes = bytes) // Remember that byteCount is # to decode, not size of array. return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecurityCritical] // auto-generated public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array")); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); return GetBytes(chars, charCount, bytes, byteCount, null); } // Returns the number of characters produced by decoding a range of bytes // in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetCharCount(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array")); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index<0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); Contract.EndContractBlock(); // If no input just return 0, fixed doesn't like 0 length arrays if (bytes.Length == 0) return 0; // Just call pointer version fixed (byte* pBytes = bytes) return GetCharCount(pBytes + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecurityCritical] // auto-generated public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); return GetCharCount(bytes, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array")); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if ( bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException("charIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.EndContractBlock(); // If no input, return 0 & avoid fixed problem if (bytes.Length == 0) return 0; // Just call pointer version int charCount = chars.Length - charIndex; // Fixed doesn't like empty arrays if (chars.Length == 0) chars = new char[1]; fixed (byte* pBytes = bytes) fixed (char* pChars = chars) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [System.Security.SecurityCritical] // auto-generated public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array")); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount<0 ? "charCount" : "byteCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); return GetChars(bytes, byteCount, chars, charCount, null); } // Returns a string containing the decoded representation of a range of // bytes in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe [System.Security.SecuritySafeCritical] // overrides public transparent member public override unsafe String GetString(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array")); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); Contract.EndContractBlock(); // Avoid problems with empty input buffer if (bytes.Length == 0) return String.Empty; fixed (byte* pBytes = bytes) return String.CreateStringFromEncoding( pBytes + index, count, this); } public override Decoder GetDecoder() { return new DecoderNLS(this); } public override Encoder GetEncoder() { return new EncoderNLS(this); } } } #endif // FEATURE_ENCODINGNLS
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Linq.Expressions; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using ComTypes = System.Runtime.InteropServices.ComTypes; namespace System.Management.Automation.ComInterop { /// <summary> /// A wrapper around a COM object that implements IDispatch /// /// This currently has the following issues: /// 1. IDispatch cannot distinguish between properties and methods with 0 arguments (and non-0 /// default arguments?). So obj.foo() is ambiguous as it could mean invoking method foo, /// or it could mean invoking the function pointer returned by property foo. /// We are attempting to find whether we need to call a method or a property by examining /// the ITypeInfo associated with the IDispatch. ITypeInfo tell's use what parameters the method /// expects, is it a method or a property, what is the default property of the object, how to /// create an enumerator for collections etc. /// /// We also support events for IDispatch objects: /// Background: /// COM objects support events through a mechanism known as Connect Points. /// Connection Points are separate objects created off the actual COM /// object (this is to prevent circular references between event sink /// and event source). When clients want to sink events generated by /// COM object they would implement callback interfaces (aka source /// interfaces) and hand it over (advise) to the Connection Point. /// /// Implementation details: /// When IDispatchComObject.TryGetMember request is received we first check /// whether the requested member is a property or a method. If this check /// fails we will try to determine whether an event is requested. To do /// so we will do the following set of steps: /// 1. Verify the COM object implements IConnectionPointContainer /// 2. Attempt to find COM object's coclass's description /// a. Query the object for IProvideClassInfo interface. Go to 3, if found /// b. From object's IDispatch retrieve primary interface description /// c. Scan coclasses declared in object's type library. /// d. Find coclass implementing this particular primary interface /// 3. Scan coclass for all its source interfaces. /// 4. Check whether to any of the methods on the source interfaces matches /// the request name /// /// Once we determine that TryGetMember requests an event we will return /// an instance of BoundDispEvent class. This class has InPlaceAdd and /// InPlaceSubtract operators defined. Calling InPlaceAdd operator will: /// 1. An instance of ComEventSinksContainer class is created (unless /// RCW already had one). This instance is associated to the RCW in attempt /// to bind the lifetime of event sinks to the lifetime of the RCW itself, /// meaning event sink will be collected once the RCW is collected (this /// is the same way event sinks lifetime is controlled by PIAs). /// Notice: ComEventSinksContainer contains a Finalizer which will go and /// unadvise all event sinks. /// Notice: ComEventSinksContainer is a list of ComEventSink objects. /// 2. Unless we have already created a ComEventSink for the required /// source interface, we will create and advise a new ComEventSink. Each /// ComEventSink implements a single source interface that COM object /// supports. /// 3. ComEventSink contains a map between method DISPIDs to the /// multicast delegate that will be invoked when the event is raised. /// 4. ComEventSink implements IReflect interface which is exposed as /// custom IDispatch to COM consumers. This allows us to intercept calls /// to IDispatch.Invoke and apply custom logic - in particular we will /// just find and invoke the multicast delegate corresponding to the invoked /// dispid. /// </summary> internal sealed class IDispatchComObject : ComObject, IDynamicMetaObjectProvider { private ComTypeDesc _comTypeDesc; private static readonly Dictionary<Guid, ComTypeDesc> s_cacheComTypeDesc = new Dictionary<Guid, ComTypeDesc>(); internal IDispatchComObject(IDispatch rcw) : base(rcw) { DispatchObject = rcw; } public override string ToString() { ComTypeDesc ctd = _comTypeDesc; string typeName = null; if (ctd != null) { typeName = ctd.TypeName; } if (string.IsNullOrEmpty(typeName)) { typeName = "IDispatch"; } return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", RuntimeCallableWrapper.ToString(), typeName); } public ComTypeDesc ComTypeDesc { get { EnsureScanDefinedMethods(); return _comTypeDesc; } } public IDispatch DispatchObject { get; } private static int GetIDsOfNames(IDispatch dispatch, string name, out int dispId) { int[] dispIds = new int[1]; Guid emptyRiid = Guid.Empty; int hresult = dispatch.TryGetIDsOfNames( ref emptyRiid, new string[] { name }, 1, 0, dispIds); dispId = dispIds[0]; return hresult; } internal bool TryGetGetItem(out ComMethodDesc value) { ComMethodDesc methodDesc = _comTypeDesc.GetItem; if (methodDesc != null) { value = methodDesc; return true; } return SlowTryGetGetItem(out value); } private bool SlowTryGetGetItem(out ComMethodDesc value) { EnsureScanDefinedMethods(); ComMethodDesc methodDesc = _comTypeDesc.GetItem; // Without type information, we really don't know whether or not we have a property getter. if (methodDesc == null) { string name = "[PROPERTYGET, DISPID(0)]"; _comTypeDesc.EnsureGetItem(new ComMethodDesc(name, ComDispIds.DISPID_VALUE, ComTypes.INVOKEKIND.INVOKE_PROPERTYGET)); methodDesc = _comTypeDesc.GetItem; } value = methodDesc; return true; } internal bool TryGetSetItem(out ComMethodDesc value) { ComMethodDesc methodDesc = _comTypeDesc.SetItem; if (methodDesc != null) { value = methodDesc; return true; } return SlowTryGetSetItem(out value); } private bool SlowTryGetSetItem(out ComMethodDesc value) { EnsureScanDefinedMethods(); ComMethodDesc methodDesc = _comTypeDesc.SetItem; // Without type information, we really don't know whether or not we have a property setter. if (methodDesc == null) { string name = "[PROPERTYPUT, DISPID(0)]"; _comTypeDesc.EnsureSetItem(new ComMethodDesc(name, ComDispIds.DISPID_VALUE, ComTypes.INVOKEKIND.INVOKE_PROPERTYPUT)); methodDesc = _comTypeDesc.SetItem; } value = methodDesc; return true; } internal bool TryGetMemberMethod(string name, out ComMethodDesc method) { EnsureScanDefinedMethods(); return _comTypeDesc.TryGetFunc(name, out method); } internal bool TryGetMemberEvent(string name, out ComEventDesc @event) { EnsureScanDefinedEvents(); return _comTypeDesc.TryGetEvent(name, out @event); } internal bool TryGetMemberMethodExplicit(string name, out ComMethodDesc method) { EnsureScanDefinedMethods(); int hresult = GetIDsOfNames(DispatchObject, name, out int dispId); if (hresult == ComHresults.S_OK) { ComMethodDesc cmd = new ComMethodDesc(name, dispId, ComTypes.INVOKEKIND.INVOKE_FUNC); _comTypeDesc.AddFunc(name, cmd); method = cmd; return true; } if (hresult == ComHresults.DISP_E_UNKNOWNNAME) { method = null; return false; } throw Error.CouldNotGetDispId(name, string.Format(CultureInfo.InvariantCulture, "0x{0:X})", hresult)); } internal bool TryGetPropertySetterExplicit(string name, out ComMethodDesc method, Type limitType, bool holdsNull) { EnsureScanDefinedMethods(); int hresult = GetIDsOfNames(DispatchObject, name, out int dispId); if (hresult == ComHresults.S_OK) { // we do not know whether we have put or putref here // and we will not guess and pretend we found both. ComMethodDesc put = new ComMethodDesc(name, dispId, ComTypes.INVOKEKIND.INVOKE_PROPERTYPUT); _comTypeDesc.AddPut(name, put); ComMethodDesc putref = new ComMethodDesc(name, dispId, ComTypes.INVOKEKIND.INVOKE_PROPERTYPUTREF); _comTypeDesc.AddPutRef(name, putref); if (ComBinderHelpers.PreferPut(limitType, holdsNull)) { method = put; } else { method = putref; } return true; } if (hresult == ComHresults.DISP_E_UNKNOWNNAME) { method = null; return false; } throw Error.CouldNotGetDispId(name, string.Format(CultureInfo.InvariantCulture, "0x{0:X})", hresult)); } internal override IList<string> GetMemberNames(bool dataOnly) { EnsureScanDefinedMethods(); EnsureScanDefinedEvents(); return ComTypeDesc.GetMemberNames(dataOnly); } internal override IList<KeyValuePair<string, object>> GetMembers(IEnumerable<string> names) { if (names == null) { names = GetMemberNames(true); } Type comType = RuntimeCallableWrapper.GetType(); var members = new List<KeyValuePair<string, object>>(); foreach (string name in names) { if (name == null) { continue; } if (ComTypeDesc.TryGetFunc(name, out ComMethodDesc method) && method.IsDataMember) { try { object value = comType.InvokeMember( method.Name, BindingFlags.GetProperty, null, RuntimeCallableWrapper, Array.Empty<object>(), CultureInfo.InvariantCulture ); members.Add(new KeyValuePair<string, object>(method.Name, value)); //evaluation failed for some reason. pass exception out } catch (Exception ex) { members.Add(new KeyValuePair<string, object>(method.Name, ex)); } } } return members.ToArray(); } DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) { EnsureScanDefinedMethods(); return new IDispatchMetaObject(parameter, this); } private static void GetFuncDescForDescIndex(ComTypes.ITypeInfo typeInfo, int funcIndex, out ComTypes.FUNCDESC funcDesc, out IntPtr funcDescHandle) { IntPtr pFuncDesc; typeInfo.GetFuncDesc(funcIndex, out pFuncDesc); // GetFuncDesc should never return null, this is just to be safe if (pFuncDesc == IntPtr.Zero) { throw Error.CannotRetrieveTypeInformation(); } funcDesc = (ComTypes.FUNCDESC)Marshal.PtrToStructure(pFuncDesc, typeof(ComTypes.FUNCDESC)); funcDescHandle = pFuncDesc; } private void EnsureScanDefinedEvents() { // _comTypeDesc.Events is null if we have not yet attempted // to scan the object for events. if (_comTypeDesc?.Events != null) { return; } // check type info in the type descriptions cache ComTypes.ITypeInfo typeInfo = ComRuntimeHelpers.GetITypeInfoFromIDispatch(DispatchObject); if (typeInfo == null) { _comTypeDesc = ComTypeDesc.CreateEmptyTypeDesc(); return; } ComTypes.TYPEATTR typeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(typeInfo); if (_comTypeDesc == null) { lock (s_cacheComTypeDesc) { if (s_cacheComTypeDesc.TryGetValue(typeAttr.guid, out _comTypeDesc) && _comTypeDesc.Events != null) { return; } } } ComTypeDesc typeDesc = ComTypeDesc.FromITypeInfo(typeInfo, typeAttr); ComTypes.ITypeInfo classTypeInfo; Dictionary<string, ComEventDesc> events; var cpc = RuntimeCallableWrapper as ComTypes.IConnectionPointContainer; if (cpc == null) { // No ICPC - this object does not support events events = ComTypeDesc.EmptyEvents; } else if ((classTypeInfo = GetCoClassTypeInfo(RuntimeCallableWrapper, typeInfo)) == null) { // no class info found - this object may support events // but we could not discover those events = ComTypeDesc.EmptyEvents; } else { events = new Dictionary<string, ComEventDesc>(); ComTypes.TYPEATTR classTypeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(classTypeInfo); for (int i = 0; i < classTypeAttr.cImplTypes; i++) { classTypeInfo.GetRefTypeOfImplType(i, out int hRefType); classTypeInfo.GetRefTypeInfo(hRefType, out ComTypes.ITypeInfo interfaceTypeInfo); classTypeInfo.GetImplTypeFlags(i, out ComTypes.IMPLTYPEFLAGS flags); if ((flags & ComTypes.IMPLTYPEFLAGS.IMPLTYPEFLAG_FSOURCE) != 0) { ScanSourceInterface(interfaceTypeInfo, ref events); } } if (events.Count == 0) { events = ComTypeDesc.EmptyEvents; } } lock (s_cacheComTypeDesc) { if (s_cacheComTypeDesc.TryGetValue(typeAttr.guid, out ComTypeDesc cachedTypeDesc)) { _comTypeDesc = cachedTypeDesc; } else { _comTypeDesc = typeDesc; s_cacheComTypeDesc.Add(typeAttr.guid, _comTypeDesc); } _comTypeDesc.Events = events; } } private static void ScanSourceInterface(ComTypes.ITypeInfo sourceTypeInfo, ref Dictionary<string, ComEventDesc> events) { ComTypes.TYPEATTR sourceTypeAttribute = ComRuntimeHelpers.GetTypeAttrForTypeInfo(sourceTypeInfo); for (int index = 0; index < sourceTypeAttribute.cFuncs; index++) { IntPtr funcDescHandleToRelease = IntPtr.Zero; try { GetFuncDescForDescIndex(sourceTypeInfo, index, out ComTypes.FUNCDESC funcDesc, out funcDescHandleToRelease); // we are not interested in hidden or restricted functions for now. if ((funcDesc.wFuncFlags & (int)ComTypes.FUNCFLAGS.FUNCFLAG_FHIDDEN) != 0) { continue; } if ((funcDesc.wFuncFlags & (int)ComTypes.FUNCFLAGS.FUNCFLAG_FRESTRICTED) != 0) { continue; } string name = ComRuntimeHelpers.GetNameOfMethod(sourceTypeInfo, funcDesc.memid); name = name.ToUpper(System.Globalization.CultureInfo.InvariantCulture); // Sometimes coclass has multiple source interfaces. Usually this is caused by // adding new events and putting them on new interfaces while keeping the // old interfaces around. This may cause name collisions which we are // resolving by keeping only the first event with the same name. if (!events.ContainsKey(name)) { ComEventDesc eventDesc = new ComEventDesc { Dispid = funcDesc.memid, SourceIID = sourceTypeAttribute.guid }; events.Add(name, eventDesc); } } finally { if (funcDescHandleToRelease != IntPtr.Zero) { sourceTypeInfo.ReleaseFuncDesc(funcDescHandleToRelease); } } } } private static ComTypes.ITypeInfo GetCoClassTypeInfo(object rcw, ComTypes.ITypeInfo typeInfo) { Debug.Assert(typeInfo != null); if (rcw is IProvideClassInfo provideClassInfo) { IntPtr typeInfoPtr = IntPtr.Zero; try { provideClassInfo.GetClassInfo(out typeInfoPtr); if (typeInfoPtr != IntPtr.Zero) { return Marshal.GetObjectForIUnknown(typeInfoPtr) as ComTypes.ITypeInfo; } } finally { if (typeInfoPtr != IntPtr.Zero) { Marshal.Release(typeInfoPtr); } } } // retrieving class information through IPCI has failed - // we can try scanning the typelib to find the coclass typeInfo.GetContainingTypeLib(out ComTypes.ITypeLib typeLib, out int _); string typeName = ComRuntimeHelpers.GetNameOfType(typeInfo); ComTypeLibDesc typeLibDesc = ComTypeLibDesc.GetFromTypeLib(typeLib); ComTypeClassDesc coclassDesc = typeLibDesc.GetCoClassForInterface(typeName); if (coclassDesc == null) { return null; } Guid coclassGuid = coclassDesc.Guid; typeLib.GetTypeInfoOfGuid(ref coclassGuid, out ComTypes.ITypeInfo typeInfoCoClass); return typeInfoCoClass; } private void EnsureScanDefinedMethods() { if (_comTypeDesc?.Funcs != null) { return; } ComTypes.ITypeInfo typeInfo = ComRuntimeHelpers.GetITypeInfoFromIDispatch(DispatchObject); if (typeInfo == null) { _comTypeDesc = ComTypeDesc.CreateEmptyTypeDesc(); return; } ComTypes.TYPEATTR typeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(typeInfo); if (_comTypeDesc == null) { lock (s_cacheComTypeDesc) { if (s_cacheComTypeDesc.TryGetValue(typeAttr.guid, out _comTypeDesc) && _comTypeDesc.Funcs != null) { return; } } } if (typeAttr.typekind == ComTypes.TYPEKIND.TKIND_INTERFACE) { // We have typeinfo for custom interface. Get typeinfo for Dispatch interface. typeInfo = ComTypeInfo.GetDispatchTypeInfoFromCustomInterfaceTypeInfo(typeInfo); typeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(typeInfo); } if (typeAttr.typekind == ComTypes.TYPEKIND.TKIND_COCLASS) { // We have typeinfo for the COClass. Find the default interface and get typeinfo for default interface. typeInfo = ComTypeInfo.GetDispatchTypeInfoFromCoClassTypeInfo(typeInfo); typeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(typeInfo); } ComTypeDesc typeDesc = ComTypeDesc.FromITypeInfo(typeInfo, typeAttr); ComMethodDesc getItem = null; ComMethodDesc setItem = null; Hashtable funcs = new Hashtable(typeAttr.cFuncs); Hashtable puts = new Hashtable(); Hashtable putrefs = new Hashtable(); for (int definedFuncIndex = 0; definedFuncIndex < typeAttr.cFuncs; definedFuncIndex++) { IntPtr funcDescHandleToRelease = IntPtr.Zero; try { GetFuncDescForDescIndex(typeInfo, definedFuncIndex, out ComTypes.FUNCDESC funcDesc, out funcDescHandleToRelease); if ((funcDesc.wFuncFlags & (int)ComTypes.FUNCFLAGS.FUNCFLAG_FRESTRICTED) != 0) { // This function is not meant for the script user to use. continue; } ComMethodDesc method = new ComMethodDesc(typeInfo, funcDesc); string name = method.Name.ToUpper(CultureInfo.InvariantCulture); if ((funcDesc.invkind & ComTypes.INVOKEKIND.INVOKE_PROPERTYPUT) != 0) { // If there is a getter for this put, use that ReturnType as the // PropertyType. if (funcs.ContainsKey(name)) { method.InputType = ((ComMethodDesc)funcs[name]).ReturnType; } puts.Add(name, method); // for the special dispId == 0, we need to store // the method descriptor for the Do(SetItem) binder. if (method.DispId == ComDispIds.DISPID_VALUE && setItem == null) { setItem = method; } continue; } if ((funcDesc.invkind & ComTypes.INVOKEKIND.INVOKE_PROPERTYPUTREF) != 0) { // If there is a getter for this put, use that ReturnType as the // PropertyType. if (funcs.ContainsKey(name)) { method.InputType = ((ComMethodDesc)funcs[name]).ReturnType; } putrefs.Add(name, method); // for the special dispId == 0, we need to store // the method descriptor for the Do(SetItem) binder. if (method.DispId == ComDispIds.DISPID_VALUE && setItem == null) { setItem = method; } continue; } if (funcDesc.memid == ComDispIds.DISPID_NEWENUM) { funcs.Add("GETENUMERATOR", method); continue; } // If there is a setter for this put, update the InputType from our // ReturnType. if (puts.ContainsKey(name)) { ((ComMethodDesc)puts[name]).InputType = method.ReturnType; } if (putrefs.ContainsKey(name)) { ((ComMethodDesc)putrefs[name]).InputType = method.ReturnType; } funcs.Add(name, method); // for the special dispId == 0, we need to store the method descriptor // for the Do(GetItem) binder. if (funcDesc.memid == ComDispIds.DISPID_VALUE) { getItem = method; } } finally { if (funcDescHandleToRelease != IntPtr.Zero) { typeInfo.ReleaseFuncDesc(funcDescHandleToRelease); } } } lock (s_cacheComTypeDesc) { if (s_cacheComTypeDesc.TryGetValue(typeAttr.guid, out ComTypeDesc cachedTypeDesc)) { _comTypeDesc = cachedTypeDesc; } else { _comTypeDesc = typeDesc; s_cacheComTypeDesc.Add(typeAttr.guid, _comTypeDesc); } _comTypeDesc.Funcs = funcs; _comTypeDesc.Puts = puts; _comTypeDesc.PutRefs = putrefs; _comTypeDesc.EnsureGetItem(getItem); _comTypeDesc.EnsureSetItem(setItem); } } internal bool TryGetPropertySetter(string name, out ComMethodDesc method, Type limitType, bool holdsNull) { EnsureScanDefinedMethods(); if (ComBinderHelpers.PreferPut(limitType, holdsNull)) { return _comTypeDesc.TryGetPut(name, out method) || _comTypeDesc.TryGetPutRef(name, out method); } return _comTypeDesc.TryGetPutRef(name, out method) || _comTypeDesc.TryGetPut(name, out method); } } }
// Copyright (c) Rotorz Limited. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root. using UnityEditor; using UnityEngine; namespace Rotorz.Tile.Editor { /// <exclude/> internal static class PlopUtility { /// <summary> /// Determines whether brush can be used to plop tiles. /// </summary> /// <param name="brush">The brush.</param> /// <returns> /// A value of <c>true</c> if tiles can be plopped with specified brush; otherwise /// a value of <c>false</c>. /// </returns> public static bool CanPlopWithBrush(Brush brush) { // Do not even attempt to 'plop' tiles with a tileset brush. //!TODO: This could be improved! var alias = brush as AliasBrush; if (alias != null && alias.target is TilesetBrush) { return false; } return brush != null && !(brush is TilesetBrush) && !brush.disableImmediatePreview; } /// <summary> /// Calculate placement point from local point. /// </summary> /// <param name="system">The tile system.</param> /// <param name="localPoint">Local point within tile system.</param> /// <returns> /// Placement point for plop. /// </returns> public static Vector3 PositionFromPlopPoint(TileSystem system, Vector3 localPoint) { localPoint.x -= system.CellSize.x / 2f; localPoint.y += system.CellSize.y / 2f; return localPoint; } private static TileSystem s_TempSystem; private static TileSystem GetTempSystem(TileSystem activeSystem) { // Get or create a temporary 1x1 tile system. if (s_TempSystem == null) { var go = GameObject.Find("{{Plop Tool}} Temp System"); if (go == null) { go = EditorUtility.CreateGameObjectWithHideFlags("{{Plop Tool}} Temp System", HideFlags.HideAndDontSave); s_TempSystem = go.AddComponent<TileSystem>(); s_TempSystem.CreateSystem(1, 1, 1, 1, 1, 1, 1); } else { s_TempSystem = go.GetComponent<TileSystem>(); } } // Mimic tile size and facing as active tile system. s_TempSystem.CellSize = activeSystem.CellSize; s_TempSystem.TilesFacing = activeSystem.TilesFacing; return s_TempSystem; } public static PlopInstance PaintPlop(TileSystem system, Vector3 localPoint, Brush brush, int rotation, int variation) { var tempSystem = GetTempSystem(system); try { // Align temporary tile system to mouse pointer. tempSystem.transform.SetParent(system.transform, false); tempSystem.transform.localPosition = PositionFromPlopPoint(system, localPoint); tempSystem.transform.localRotation = Quaternion.identity; tempSystem.transform.localScale = Vector3.one; // Paint tile! var tile = brush.PaintWithSimpleRotation(tempSystem, 0, 0, rotation, variation); if (tile != null && tile.gameObject != null) { // We can have undo/redo for plops! Undo.RegisterCreatedObjectUndo(tile.gameObject, TileLang.ParticularText("Action", "Plop Tile")); // Indicate that painted game object is a plop! var plop = tile.gameObject.AddComponent<PlopInstance>(); plop.Owner = system; var tileTransform = tile.gameObject.transform; // Disconnect game object from data structure of temporary system. SetParent(tileTransform, system.transform); tile.gameObject = null; // Store some additional data for plop! plop.PlopPointOffset = localPoint - tileTransform.localPosition; plop.Brush = brush; plop.VariationIndex = tile.variationIndex; plop.PaintedRotation = rotation; plop.Rotation = tile.Rotation; return plop; } return null; } finally { // We must cleanup before we finish! tempSystem.EraseTile(0, 0); tempSystem.transform.SetParent(null, false); } } public static int CountPlopVariations(TileSystem system, PlopInstance plop) { if (plop == null || plop.Brush == null) { return 0; } int orientation = OrientationUtility.DetermineTileOrientation(system, TileIndex.zero, plop.Brush, plop.PaintedRotation); return plop.Brush.CountTileVariations(orientation); } public static PlopInstance CyclePlop(TileSystem system, PlopInstance plop, Brush brush, int nextRotation, int nextVariation) { Undo.RecordObject(plop, TileLang.ParticularText("Action", "Cycle Plop")); var parentTransform = plop.transform.parent; var tileData = plop.ToTileData(); nextVariation = Brush.WrapVariationIndexForCycle(Brush.GetSharedContext(brush, GetTempSystem(system), TileIndex.zero), tileData, nextVariation); var newPlop = PaintPlop(system, plop.PlopPoint, brush, nextRotation, nextVariation); ErasePlop(plop); // New plop should have same parent as original plop. var newPlopTransform = newPlop.transform; if (newPlopTransform.parent != parentTransform) { newPlopTransform.SetParent(parentTransform); } return newPlop; } public static PlopInstance RefreshPlop(TileSystem system, PlopInstance plop) { return CyclePlop(system, plop, plop.Brush, plop.PaintedRotation, plop.VariationIndex); } public static void ErasePlop(PlopInstance plop) { var plopParent = plop.transform.parent; Undo.DestroyObjectImmediate(plop.gameObject); // Automatically erase container object when empty. AutoRemovePlopGroupIfEmpty(plopParent); } private static void SetParent(Transform obj, Transform system) { var plopTool = ToolManager.Instance.Find<PlopTool>(); // Assume default value if plop tool is for some reason unregistered. PlopTool.Location location = (plopTool != null) ? plopTool.PlopLocation : PlopTool.Location.ChildOfTileSystem; switch (location) { default: case PlopTool.Location.GroupInsideTileSystem: var group = system.Find(plopTool.PlopGroupName); if (group == null) { // Create 'Plops' group if necessary! var groupGO = new GameObject(plopTool.PlopGroupName); group = groupGO.transform; group.SetParent(system, false); groupGO.AddComponent<PlopGroup>(); Undo.RegisterCreatedObjectUndo(groupGO, "Create Group for Plops"); } obj.SetParent(group); break; case PlopTool.Location.ChildOfTileSystem: obj.SetParent(system); break; case PlopTool.Location.SceneRoot: obj.SetParent(null); break; } } private static void AutoRemovePlopGroupIfEmpty(Transform plopGroup) { // Was a valid group specified? if (plopGroup == null || plopGroup.GetComponent<PlopGroup>() == null) { return; } // Can only remove an empty group, i.e. one with no children and no extra components. if (plopGroup.childCount == 0 && plopGroup.GetComponents<Component>().Length <= 2) { Undo.DestroyObjectImmediate(plopGroup.gameObject); } } } }
/* Generated by MyraPad at 05.06.2020 22:34:38 */ using Myra.Graphics2D; using Myra.Graphics2D.TextureAtlases; using Myra.Graphics2D.UI; using Myra.Graphics2D.Brushes; namespace Myra.Graphics2D.UI.ColorPicker { partial class ColorPickerPanel: VerticalStackPanel { private void BuildUI() { _colorWheel = new Image(); _colorWheel.Id = "_colorWheel"; _hsPicker = new Image(); _hsPicker.BorderThickness = new Thickness(1); _hsPicker.Padding = new Thickness(4); _hsPicker.HorizontalAlignment = Myra.Graphics2D.UI.HorizontalAlignment.Center; _hsPicker.VerticalAlignment = Myra.Graphics2D.UI.VerticalAlignment.Center; _hsPicker.Enabled = false; _hsPicker.Background = new SolidBrush("#FFFFFFFF"); _hsPicker.Border = new SolidBrush("#000000"); _hsPicker.Id = "_hsPicker"; var panel1 = new Panel(); panel1.Width = 147; panel1.Height = 147; panel1.Widgets.Add(_colorWheel); panel1.Widgets.Add(_hsPicker); _gradient = new Image(); _gradient.Width = 10; _gradient.Height = 147; _gradient.BorderThickness = new Thickness(1); _gradient.Border = new SolidBrush("#000000"); _gradient.Id = "_gradient"; _vPicker = new Image(); _vPicker.Margin = new Thickness(0, 1); _vPicker.BorderThickness = new Thickness(1); _vPicker.Padding = new Thickness(4); _vPicker.HorizontalAlignment = Myra.Graphics2D.UI.HorizontalAlignment.Center; _vPicker.Enabled = false; _vPicker.Background = new SolidBrush("#FFFFFFFF"); _vPicker.Border = new SolidBrush("#000000"); _vPicker.Id = "_vPicker"; var panel2 = new Panel(); panel2.Widgets.Add(_gradient); panel2.Widgets.Add(_vPicker); _colorBackground = new Image(); _colorBackground.Width = 40; _colorBackground.HorizontalAlignment = Myra.Graphics2D.UI.HorizontalAlignment.Center; _colorBackground.VerticalAlignment = Myra.Graphics2D.UI.VerticalAlignment.Stretch; _colorBackground.GridColumnSpan = 3; _colorBackground.Background = new SolidBrush("#FFFFFFFF"); _colorBackground.Id = "_colorBackground"; _colorDisplay = new Image(); _colorDisplay.Width = 40; _colorDisplay.HorizontalAlignment = Myra.Graphics2D.UI.HorizontalAlignment.Center; _colorDisplay.VerticalAlignment = Myra.Graphics2D.UI.VerticalAlignment.Stretch; _colorDisplay.GridColumnSpan = 3; _colorDisplay.Id = "_colorDisplay"; var label1 = new Label(); label1.Text = "RGB"; label1.GridRow = 1; _inputRGB = new TextBox(); _inputRGB.GridColumn = 1; _inputRGB.GridRow = 1; _inputRGB.GridColumnSpan = 2; _inputRGB.Id = "_inputRGB"; var label2 = new Label(); label2.Text = "HSV"; label2.GridRow = 2; _inputHSV = new TextBox(); _inputHSV.GridColumn = 1; _inputHSV.GridRow = 2; _inputHSV.GridColumnSpan = 2; _inputHSV.Id = "_inputHSV"; var label3 = new Label(); label3.Text = "HEX"; label3.GridRow = 3; _inputHEX = new TextBox(); _inputHEX.GridColumn = 1; _inputHEX.GridRow = 3; _inputHEX.GridColumnSpan = 2; _inputHEX.Id = "_inputHEX"; var label4 = new Label(); label4.Text = "Alpha"; label4.GridRow = 4; _inputAlpha = new TextBox(); _inputAlpha.GridColumn = 2; _inputAlpha.GridRow = 4; _inputAlpha.Id = "_inputAlpha"; _sliderAlpha = new HorizontalSlider(); _sliderAlpha.Maximum = 255; _sliderAlpha.Height = 21; _sliderAlpha.GridColumn = 1; _sliderAlpha.GridRow = 4; _sliderAlpha.Id = "_sliderAlpha"; _saveColor = new TextButton(); _saveColor.Text = "Save Color"; _saveColor.HorizontalAlignment = Myra.Graphics2D.UI.HorizontalAlignment.Right; _saveColor.GridRow = 5; _saveColor.GridColumnSpan = 3; _saveColor.Id = "_saveColor"; var grid1 = new Grid(); grid1.ColumnSpacing = 8; grid1.RowSpacing = 6; grid1.ColumnsProportions.Add(new Proportion { Type = Myra.Graphics2D.UI.ProportionType.Auto, }); grid1.ColumnsProportions.Add(new Proportion { Type = Myra.Graphics2D.UI.ProportionType.Fill, }); grid1.ColumnsProportions.Add(new Proportion { Type = Myra.Graphics2D.UI.ProportionType.Pixels, Value = 60, }); grid1.RowsProportions.Add(new Proportion { Type = Myra.Graphics2D.UI.ProportionType.Pixels, Value = 40, }); grid1.RowsProportions.Add(new Proportion { Type = Myra.Graphics2D.UI.ProportionType.Auto, }); grid1.RowsProportions.Add(new Proportion { Type = Myra.Graphics2D.UI.ProportionType.Auto, }); grid1.RowsProportions.Add(new Proportion { Type = Myra.Graphics2D.UI.ProportionType.Auto, }); grid1.RowsProportions.Add(new Proportion { Type = Myra.Graphics2D.UI.ProportionType.Auto, }); grid1.RowsProportions.Add(new Proportion { Type = Myra.Graphics2D.UI.ProportionType.Auto, }); grid1.VerticalAlignment = Myra.Graphics2D.UI.VerticalAlignment.Top; grid1.Widgets.Add(_colorBackground); grid1.Widgets.Add(_colorDisplay); grid1.Widgets.Add(label1); grid1.Widgets.Add(_inputRGB); grid1.Widgets.Add(label2); grid1.Widgets.Add(_inputHSV); grid1.Widgets.Add(label3); grid1.Widgets.Add(_inputHEX); grid1.Widgets.Add(label4); grid1.Widgets.Add(_inputAlpha); grid1.Widgets.Add(_sliderAlpha); grid1.Widgets.Add(_saveColor); var horizontalStackPanel1 = new HorizontalStackPanel(); horizontalStackPanel1.Spacing = 8; horizontalStackPanel1.Proportions.Add(new Proportion { Type = Myra.Graphics2D.UI.ProportionType.Auto, }); horizontalStackPanel1.Proportions.Add(new Proportion { Type = Myra.Graphics2D.UI.ProportionType.Auto, }); horizontalStackPanel1.Proportions.Add(new Proportion { Type = Myra.Graphics2D.UI.ProportionType.Fill, }); horizontalStackPanel1.Widgets.Add(panel1); horizontalStackPanel1.Widgets.Add(panel2); horizontalStackPanel1.Widgets.Add(grid1); _userColors = new Grid(); _userColors.ColumnSpacing = 8; _userColors.RowSpacing = 8; _userColors.GridSelectionMode = Myra.Graphics2D.UI.GridSelectionMode.Cell; _userColors.Height = 80; _userColors.Padding = new Thickness(4); _userColors.Id = "_userColors"; Spacing = 8; HorizontalAlignment = Myra.Graphics2D.UI.HorizontalAlignment.Center; Width = 450; Padding = new Thickness(10, 0, 10, 5); Widgets.Add(horizontalStackPanel1); Widgets.Add(_userColors); } public Image _colorWheel; public Image _hsPicker; public Image _gradient; public Image _vPicker; public Image _colorBackground; public Image _colorDisplay; public TextBox _inputRGB; public TextBox _inputHSV; public TextBox _inputHEX; public TextBox _inputAlpha; public HorizontalSlider _sliderAlpha; public TextButton _saveColor; public Grid _userColors; } }
/* 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.Linq; using System.Web; using Adxstudio.Xrm.Cms; using Adxstudio.Xrm.Collections.Generic; using Adxstudio.Xrm.Data; using Adxstudio.Xrm.Tagging; using Adxstudio.Xrm.Web; using Microsoft.Xrm.Client.Security; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; using Adxstudio.Xrm.Services; using Adxstudio.Xrm.Services.Query; using Microsoft.Xrm.Sdk.Query; namespace Adxstudio.Xrm.Blogs { public class WebsiteBlogAggregationDataAdapter : IBlogAggregationDataAdapter { public WebsiteBlogAggregationDataAdapter(IDataAdapterDependencies dependencies) { if (dependencies == null) { throw new ArgumentNullException("dependencies"); } Website = dependencies.GetWebsite(); if (Website == null) { throw new ArgumentException("Unable to get website reference.", "dependencies"); } Dependencies = dependencies; } public WebsiteBlogAggregationDataAdapter(IDataAdapterDependencies dependencies, Func<OrganizationServiceContext, IQueryable<Entity>> selectBlogEntities = null, Func<OrganizationServiceContext, IQueryable<Entity>> selectBlogPostEntities = null, string portalName = null) : this(dependencies) { if (selectBlogEntities != null) { SelectBlogEntities = selectBlogEntities; } if (selectBlogPostEntities != null) { SelectBlogPostEntities = selectBlogPostEntities; } } private Func<OrganizationServiceContext, IQueryable<Entity>> _selectBlogEntities; private Func<OrganizationServiceContext, IQueryable<Entity>> _selectBlogPostEntities; protected List<string> ExcludeList; protected IDataAdapterDependencies Dependencies { get; private set; } protected EntityReference Website { get; private set; } protected Func<OrganizationServiceContext, IQueryable<Entity>> SelectBlogEntities { get { if (_selectBlogEntities == null) { var contextLanguageInfo = HttpContext.Current.GetContextLanguageInfo(); if (contextLanguageInfo.IsCrmMultiLanguageEnabled) { // If multi-language is enabled, only select blogs that are language-agnostic or match the current language. _selectBlogEntities = serviceContext => serviceContext.CreateQuery("adx_blog") .Where(blog => blog.GetAttributeValue<EntityReference>("adx_websiteid") == Website && (blog.GetAttributeValue<EntityReference>("adx_websitelanguageid") == null || blog.GetAttributeValue<EntityReference>("adx_websitelanguageid").Id == contextLanguageInfo.ContextLanguage.EntityReference.Id)); } else { _selectBlogEntities = serviceContext => serviceContext.CreateQuery("adx_blog") .Where(blog => blog.GetAttributeValue<EntityReference>("adx_websiteid") == Website); } } return _selectBlogEntities; } private set { _selectBlogEntities = value; } } protected Func<OrganizationServiceContext, IQueryable<Entity>> SelectBlogPostEntities { get { if (_selectBlogPostEntities == null) { _selectBlogPostEntities = serviceContext => serviceContext.GetAllBlogPostsInWebsite(Website.Id); } return _selectBlogPostEntities; } private set { _selectBlogPostEntities = value; } } public virtual IEnumerable<IBlog> SelectBlogs() { return SelectBlogs(0); } public virtual IEnumerable<IBlog> SelectBlogs(int startRowIndex, int maximumRows = -1) { if (startRowIndex < 0) { throw new ArgumentException("Value must be a positive integer.", "startRowIndex"); } if (maximumRows == 0) { return new IBlog[] { }; } var serviceContext = Dependencies.GetServiceContext(); var security = Dependencies.GetSecurityProvider(); var urlProvider = Dependencies.GetUrlProvider(); var query = SelectBlogEntities(serviceContext).ToList().OrderBy(blog => blog.GetAttributeValue<string>("adx_name")); if (maximumRows < 0) { return query.ToArray() .Where(e => security.TryAssert(serviceContext, e, CrmEntityRight.Read)) .Skip(startRowIndex) .Select(e => new Blog(e, urlProvider.GetApplicationPath(serviceContext, e), Dependencies.GetBlogFeedPath(e.Id))) .ToArray(); } var pagedQuery = query; var paginator = new PostFilterPaginator<Entity>( (offset, limit) => pagedQuery.Skip(offset).Take(limit).ToArray(), e => security.TryAssert(serviceContext, e, CrmEntityRight.Read), 2); return paginator.Select(startRowIndex, maximumRows) .Select(e => new Blog(e, urlProvider.GetApplicationPath(serviceContext, e), Dependencies.GetBlogFeedPath(e.Id))).ToArray(); } public virtual int SelectBlogCount() { var serviceContext = Dependencies.GetServiceContext(); return serviceContext.FetchCount("adx_blog", "adx_blogid", addCondition => addCondition("adx_websiteid", "eq", Website.Id.ToString())); } public IBlog Select() { var serviceContext = Dependencies.GetServiceContext(); var security = Dependencies.GetSecurityProvider(); var website = Dependencies.GetWebsite(); var portalOrgService = Dependencies.GetRequestContext().HttpContext.GetOrganizationService(); Entity page; var entity = TryGetPageBySiteMarker(portalOrgService, website, "Blog Home", out page) ? page : TryGetPageBySiteMarker(portalOrgService, website, "Home", out page) ? page : null; if (entity == null || !security.TryAssert(serviceContext, entity, CrmEntityRight.Read)) { return null; } var urlProvider = Dependencies.GetUrlProvider(); var path = urlProvider.GetApplicationPath(serviceContext, entity); return path == null ? null : new BlogAggregation(entity, path, Dependencies.GetBlogAggregationFeedPath()); } public IBlog Select(Guid blogId) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Start: {0}", blogId)); var blog = Select(e => e.GetAttributeValue<Guid>("adx_blogid") == blogId); if (blog == null) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Not Found"); } ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("End: {0}", blogId)); return blog; } public IBlog Select(string blogName) { if (string.IsNullOrEmpty(blogName)) { return null; } ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Start"); var blog = Select(e => e.GetAttributeValue<string>("adx_name") == blogName); if (blog == null) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Not Found"); } ADXTrace.Instance.TraceInfo(TraceCategory.Application, "End"); return blog; } protected virtual IBlog Select(Predicate<Entity> match) { var serviceContext = Dependencies.GetServiceContext(); var website = Dependencies.GetWebsite(); var publishingStateAccessProvider = new PublishingStateAccessProvider(Dependencies.GetRequestContext().HttpContext); // Bulk-load all ad entities into cache. var allEntities = serviceContext.CreateQuery("adx_blog") .Where(e => e.GetAttributeValue<EntityReference>("adx_websiteid") == website) .ToArray(); var entity = allEntities.FirstOrDefault(e => match(e) && IsActive(e) && publishingStateAccessProvider.TryAssert(serviceContext, e)); if (entity == null) { return null; } var securityProvider = Dependencies.GetSecurityProvider(); var urlProvider = Dependencies.GetUrlProvider(); if (!securityProvider.TryAssert(serviceContext, entity, CrmEntityRight.Read)) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Forum={0}: Not Found", entity.Id)); return null; } var blog = new Blog(entity, urlProvider.GetApplicationPath(serviceContext, entity), Dependencies.GetBlogFeedPath(entity.Id)); return blog; } public IEnumerable<IBlogPost> SelectPosts() { return SelectPosts(0); } public virtual IEnumerable<IBlogPost> SelectPosts(int startRowIndex, int maximumRows = -1) { if (startRowIndex < 0) { throw new ArgumentException("Value must be a positive integer.", "startRowIndex"); } if (maximumRows == 0) { return new IBlogPost[] { }; } var serviceContext = Dependencies.GetServiceContext(); var security = Dependencies.GetSecurityProvider(); var urlProvider = Dependencies.GetUrlProvider(); var query = SelectBlogPostEntities(serviceContext); var blogPostFactory = new BlogPostFactory(serviceContext, urlProvider, Website, new WebsiteBlogAggregationArchiveApplicationPathGenerator(Dependencies)); var blogReadPermissionCache = new Dictionary<Guid, bool>(); if (maximumRows < 0) { return blogPostFactory.Create(query.ToArray() .Where(e => TryAssertBlogPostRight(serviceContext, security, e, CrmEntityRight.Read, blogReadPermissionCache)) .Skip(startRowIndex)); } var pagedQuery = query; var paginator = new PostFilterPaginator<Entity>( (offset, limit) => pagedQuery.Skip(offset).Take(limit).ToArray(), e => TryAssertBlogPostRight(serviceContext, security, e, CrmEntityRight.Read, blogReadPermissionCache), 2); return blogPostFactory.Create(paginator.Select(startRowIndex, maximumRows)); } public virtual int SelectPostCount() { var serviceContext = Dependencies.GetServiceContext(); return serviceContext.FetchBlogPostCountForWebsite(Website.Id, addCondition => { }); } public IEnumerable<IBlogArchiveMonth> SelectArchiveMonths() { var serviceContext = Dependencies.GetServiceContext(); var counts = serviceContext.FetchBlogPostCountsGroupedByMonthInWebsite(Website.Id); var archivePathGenerator = new WebsiteBlogAggregationArchiveApplicationPathGenerator(Dependencies); return counts.Select(c => { var month = new DateTime(c.Item1, c.Item2, 1, 0, 0, 0, DateTimeKind.Utc); return new BlogArchiveMonth(month, c.Item3, archivePathGenerator.GetMonthPath(month)); }).OrderByDescending(e => e.Month); } public IEnumerable<IBlogPostWeightedTag> SelectWeightedTags(int weights) { var serviceContext = Dependencies.GetServiceContext(); var infos = serviceContext.FetchBlogPostTagCountsInWebsite(Website.Id) .Select(c => new BlogPostTagInfo(c.Item1, c.Item2)); var tagCloudData = new TagCloudData(weights, TagInfo.TagComparer, infos); var archivePathGenerator = new WebsiteBlogAggregationArchiveApplicationPathGenerator(Dependencies); return tagCloudData.Select(e => new BlogPostWeightedTag(e.Name, archivePathGenerator.GetTagPath(e.Name), e.TaggedItemCount, e.Weight)); } protected virtual bool TryAssertBlogPostRight(OrganizationServiceContext serviceContext, ICrmEntitySecurityProvider securityProvider, Entity blogPost, CrmEntityRight right, IDictionary<Guid, bool> blogPermissionCache) { if (blogPost == null) { throw new ArgumentNullException("blogPost"); } if (blogPost.LogicalName != "adx_blogpost") { throw new ArgumentException(string.Format("Value must have logical name {0}.", blogPost.LogicalName), "blogPost"); } var blogReference = blogPost.GetAttributeValue<EntityReference>("adx_blogid"); if (blogReference == null) { throw new ArgumentException(string.Format("Value must have entity reference attribute {0}.", "adx_blogid"), "blogPost"); } bool cachedResult; if (blogPermissionCache.TryGetValue(blogReference.Id, out cachedResult)) { return cachedResult; } var fetch = new Fetch { Entity = new FetchEntity("adx_blog") { Filters = new[] { new Filter { Conditions = new[] { new Condition("adx_blogid", ConditionOperator.Equal, blogReference.Id), new Condition("statecode", ConditionOperator.Equal, 0) } } } } }; var blog = serviceContext.RetrieveSingle(fetch); var result = securityProvider.TryAssert(serviceContext, blog, right); blogPermissionCache[blogReference.Id] = result; return result; } private static bool TryGetPageBySiteMarker(IOrganizationService portalOrgService, EntityReference website, string siteMarker, out Entity page) { var fetch = new Fetch { Entity = new FetchEntity("adx_webpage") { Filters = new[] { new Filter { Conditions = new[] { new Condition("adx_websiteid", ConditionOperator.Equal, website.Id) } } }, Links = new[] { new Link { Name = "adx_sitemarker", ToAttribute = "adx_webpageid", FromAttribute = "adx_pageid", Filters = new[] { new Filter { Conditions = new[] { new Condition("adx_pageid", ConditionOperator.NotNull), new Condition("adx_name", ConditionOperator.Equal, siteMarker), new Condition("adx_websiteid", ConditionOperator.Equal, website.Id) } } } } } } }; page = portalOrgService.RetrieveSingle(fetch); return page != null; } private static bool IsActive(Entity entity) { if (entity == null) { return false; } var statecode = entity.GetAttributeValue<OptionSetValue>("statecode"); return statecode != null && statecode.Value == 0; } } }
using System; using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics; namespace GitHub_21666 { // CRC32 is a special instruction that has 4-byte opcode but does not use SSE38 or SSE3A encoding, // so the compiler backend needs to specially check its code size. // Test LZCNT as well to ensure that future changes do not impact 3-byte opcode instructions. class GitHub_21666 { const int Pass = 100; const int Fail = 0; static byte byteSF = 1; static ushort ushortSF = 1; static uint uintSF = 1; static ulong ulongSF = 1; readonly static byte[] byteArray = new byte[10]; readonly static ushort[] ushortArray = new ushort[10]; readonly static uint[] uintArray = new uint[10]; readonly static ulong[] ulongArray = new ulong[10]; static int Main(string[] args) { bool sucess = true; byteSF = 0; ushortSF = 0; uintSF = 0; ulongSF = 0; sucess = sucess && TestByteContainment(); sucess = sucess && TestUInt16Containment(); sucess = sucess && TestUInt32Containment(); sucess = sucess && TestUInt64Containment(); return sucess ? Pass : Fail; } static unsafe bool TestByteContainment() { byte value = (byte)0; byte* ptr = &value; if (Sse42.IsSupported) { if (Sse42.Crc32(0xffffffffU, (byte)0) != 0xad82acaeU) { Console.WriteLine("TestByteContainment failed on Crc32"); return false; } if (Sse42.Crc32(0xffffffffU, value) != 0xad82acaeU) { Console.WriteLine("TestByteContainment failed on Crc32"); return false; } if (Sse42.Crc32(0xffffffffU, *ptr) != 0xad82acaeU) { Console.WriteLine("TestByteContainment failed on Crc32"); return false; } if (Sse42.Crc32(0xffffffffU, byteArray[1]) != 0xad82acaeU) { Console.WriteLine("TestByteContainment failed on Crc32"); return false; } if (Sse42.Crc32(0xffffffffU, byteArray[*ptr + 1]) != 0xad82acaeU) { Console.WriteLine("TestByteContainment failed on Crc32"); return false; } if (Sse42.Crc32(0xffffffffU, byteSF) != 0xad82acaeU) { Console.WriteLine("TestByteContainment failed on Crc32"); return false; } } return true; } static unsafe bool TestUInt16Containment() { ushort value = (ushort)0; ushort* ptr = &value; if (Sse42.IsSupported) { if (Sse42.Crc32(0xffffffffU, (ushort)0) != 0xe9e882dU) { Console.WriteLine("TestUInt16Containment failed on Crc32"); return false; } if (Sse42.Crc32(0xffffffffU, value) != 0xe9e882dU) { Console.WriteLine("TestUInt16Containment failed on Crc32"); return false; } if (Sse42.Crc32(0xffffffffU, *ptr) != 0xe9e882dU) { Console.WriteLine("TestUInt16Containment failed on Crc32"); return false; } if (Sse42.Crc32(0xffffffffU, ushortArray[1]) != 0xe9e882dU) { Console.WriteLine("TestUInt16Containment failed on Crc32"); return false; } if (Sse42.Crc32(0xffffffffU, ushortArray[*ptr + 1]) != 0xe9e882dU) { Console.WriteLine("TestUInt16Containment failed on Crc32"); return false; } if (Sse42.Crc32(0xffffffffU, ushortSF) != 0xe9e882dU) { Console.WriteLine("TestUInt16Containment failed on Crc32"); return false; } } return true; } static unsafe bool TestUInt32Containment() { uint value = (uint)0; uint* ptr = &value; if (Lzcnt.IsSupported) { if (Lzcnt.LeadingZeroCount(*ptr) != 32) { Console.WriteLine("TestUInt32Containment failed on LeadingZeroCount"); return false; } if (Lzcnt.LeadingZeroCount(uintArray[2]) != 32) { Console.WriteLine("TestUInt32Containment failed on LeadingZeroCount"); return false; } if (Lzcnt.LeadingZeroCount(uintArray[*ptr + 2]) != 32) { Console.WriteLine("TestUInt32Containment failed on LeadingZeroCount"); return false; } } uint* ptr1 = &value; if (Sse42.IsSupported) { if (Sse42.Crc32(0xffffffffU, (uint)0) != 0xb798b438U) { Console.WriteLine("TestUInt32Containment failed on Crc32"); return false; } if (Sse42.Crc32(0xffffffffU, value) != 0xb798b438U) { Console.WriteLine("TestUInt32Containment failed on Crc32"); return false; } if (Sse42.Crc32(0xffffffffU, *ptr1) != 0xb798b438U) { Console.WriteLine("TestUInt32Containment failed on Crc32"); return false; } if (Sse42.Crc32(0xffffffffU, uintArray[1]) != 0xb798b438U) { Console.WriteLine("TestUInt32Containment failed on Crc32"); return false; } if (Sse42.Crc32(0xffffffffU, uintArray[*ptr + 1]) != 0xb798b438U) { Console.WriteLine("TestUInt32Containment failed on Crc32"); return false; } if (Sse42.Crc32(0xffffffffU, uintSF) != 0xb798b438U) { Console.WriteLine("TestUInt32Containment failed on Crc32"); return false; } } return true; } static unsafe bool TestUInt64Containment() { ulong value = (ulong)0; ulong* ptr = &value; if (Lzcnt.X64.IsSupported) { if (Lzcnt.X64.LeadingZeroCount(*ptr) != 64) { Console.WriteLine("TestUInt64Containment failed on LeadingZeroCount"); return false; } if (Lzcnt.X64.LeadingZeroCount(ulongArray[2]) != 64) { Console.WriteLine("TestUInt64Containment failed on LeadingZeroCount"); return false; } if (Lzcnt.X64.LeadingZeroCount(ulongArray[*ptr + 2]) != 64) { Console.WriteLine("TestUInt64Containment failed on LeadingZeroCount"); return false; } } ulong* ptr1 = &value; if (Sse42.X64.IsSupported) { if (Sse42.X64.Crc32(0xffffffffffffffffUL, 0) != 0x0000000073d74d75UL) { Console.WriteLine("TestUInt64Containment failed on Crc32"); return false; } if (Sse42.X64.Crc32(0xffffffffffffffffUL, value) != 0x0000000073d74d75UL) { Console.WriteLine("TestUInt64Containment failed on Crc32"); return false; } if (Sse42.X64.Crc32(0xffffffffffffffffUL, *ptr1) != 0x0000000073d74d75UL) { Console.WriteLine("TestUInt64Containment failed on Crc32"); return false; } if (Sse42.X64.Crc32(0xffffffffffffffffUL, ulongArray[1]) != 0x0000000073d74d75UL) { Console.WriteLine("TestUInt64Containment failed on Crc32"); return false; } if (Sse42.X64.Crc32(0xffffffffffffffffUL, ulongArray[*ptr + 1]) != 0x0000000073d74d75UL) { Console.WriteLine("TestUInt64Containment failed on Crc32"); return false; } if (Sse42.X64.Crc32(0xffffffffffffffffUL, ulongSF) != 0x0000000073d74d75UL) { Console.WriteLine("TestUInt64Containment failed on Crc32"); return false; } } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Primitives; using Xunit; namespace Microsoft.AspNetCore.WebUtilities { public class QueryHelperTests { [Fact] public void ParseQueryWithUniqueKeysWorks() { var collection = QueryHelpers.ParseQuery("?key1=value1&key2=value2"); Assert.Equal(2, collection.Count); Assert.Equal("value1", collection["key1"].FirstOrDefault()); Assert.Equal("value2", collection["key2"].FirstOrDefault()); } [Fact] public void ParseQueryWithoutQuestionmarkWorks() { var collection = QueryHelpers.ParseQuery("key1=value1&key2=value2"); Assert.Equal(2, collection.Count); Assert.Equal("value1", collection["key1"].FirstOrDefault()); Assert.Equal("value2", collection["key2"].FirstOrDefault()); } [Fact] public void ParseQueryWithDuplicateKeysGroups() { var collection = QueryHelpers.ParseQuery("?key1=valueA&key2=valueB&key1=valueC"); Assert.Equal(2, collection.Count); Assert.Equal(new[] { "valueA", "valueC" }, collection["key1"]); Assert.Equal("valueB", collection["key2"].FirstOrDefault()); } [Fact] public void ParseQueryWithEmptyValuesWorks() { var collection = QueryHelpers.ParseQuery("?key1=&key2="); Assert.Equal(2, collection.Count); Assert.Equal(string.Empty, collection["key1"].FirstOrDefault()); Assert.Equal(string.Empty, collection["key2"].FirstOrDefault()); } [Fact] public void ParseQueryWithEmptyKeyWorks() { var collection = QueryHelpers.ParseQuery("?=value1&="); Assert.Single(collection); Assert.Equal(new[] { "value1", "" }, collection[""]); } [Fact] public void ParseQueryWithEncodedKeyWorks() { var collection = QueryHelpers.ParseQuery("?fields+%5BtodoItems%5D"); Assert.Single(collection); Assert.Equal("", collection["fields [todoItems]"].FirstOrDefault()); } [Fact] public void ParseQueryWithEncodedValueWorks() { var collection = QueryHelpers.ParseQuery("?=fields+%5BtodoItems%5D"); Assert.Single(collection); Assert.Equal("fields [todoItems]", collection[""].FirstOrDefault()); } [Fact] public void ParseQueryWithEncodedKeyEmptyValueWorks() { var collection = QueryHelpers.ParseQuery("?fields+%5BtodoItems%5D="); Assert.Single(collection); Assert.Equal("", collection["fields [todoItems]"].FirstOrDefault()); } [Fact] public void ParseQueryWithEncodedKeyEncodedValueWorks() { var collection = QueryHelpers.ParseQuery("?fields+%5BtodoItems%5D=%5B+1+%5D"); Assert.Single(collection); Assert.Equal("[ 1 ]", collection["fields [todoItems]"].FirstOrDefault()); } [Fact] public void ParseQueryWithEncodedKeyEncodedValuesWorks() { var collection = QueryHelpers.ParseQuery("?fields+%5BtodoItems%5D=%5B+1+%5D&fields+%5BtodoItems%5D=%5B+2+%5D"); Assert.Single(collection); Assert.Equal(new[] { "[ 1 ]", "[ 2 ]" }, collection["fields [todoItems]"]); } [Theory] [InlineData("?")] [InlineData("")] [InlineData(null)] public void ParseEmptyOrNullQueryWorks(string? queryString) { var collection = QueryHelpers.ParseQuery(queryString); Assert.Empty(collection); } [Fact] public void AddQueryStringWithNullValueThrows() { Assert.Throws<ArgumentNullException>("value" ,() => QueryHelpers.AddQueryString("http://contoso.com/", "hello", null!)); } [Theory] [InlineData("http://contoso.com/", "http://contoso.com/?hello=world")] [InlineData("http://contoso.com/someaction", "http://contoso.com/someaction?hello=world")] [InlineData("http://contoso.com/someaction?q=test", "http://contoso.com/someaction?q=test&hello=world")] [InlineData( "http://contoso.com/someaction?q=test#anchor", "http://contoso.com/someaction?q=test&hello=world#anchor")] [InlineData("http://contoso.com/someaction#anchor", "http://contoso.com/someaction?hello=world#anchor")] [InlineData("http://contoso.com/#anchor", "http://contoso.com/?hello=world#anchor")] [InlineData( "http://contoso.com/someaction?q=test#anchor?value", "http://contoso.com/someaction?q=test&hello=world#anchor?value")] [InlineData( "http://contoso.com/someaction#anchor?stuff", "http://contoso.com/someaction?hello=world#anchor?stuff")] [InlineData( "http://contoso.com/someaction?name?something", "http://contoso.com/someaction?name?something&hello=world")] [InlineData( "http://contoso.com/someaction#name#something", "http://contoso.com/someaction?hello=world#name#something")] public void AddQueryStringWithKeyAndValue(string uri, string expectedUri) { var result = QueryHelpers.AddQueryString(uri, "hello", "world"); Assert.Equal(expectedUri, result); } [Theory] [InlineData("http://contoso.com/", "http://contoso.com/?hello=world&some=text&another=")] [InlineData("http://contoso.com/someaction", "http://contoso.com/someaction?hello=world&some=text&another=")] [InlineData("http://contoso.com/someaction?q=1", "http://contoso.com/someaction?q=1&hello=world&some=text&another=")] [InlineData("http://contoso.com/some#action", "http://contoso.com/some?hello=world&some=text&another=#action")] [InlineData("http://contoso.com/some?q=1#action", "http://contoso.com/some?q=1&hello=world&some=text&another=#action")] [InlineData("http://contoso.com/#action", "http://contoso.com/?hello=world&some=text&another=#action")] [InlineData( "http://contoso.com/someaction?q=test#anchor?value", "http://contoso.com/someaction?q=test&hello=world&some=text&another=#anchor?value")] [InlineData( "http://contoso.com/someaction#anchor?stuff", "http://contoso.com/someaction?hello=world&some=text&another=#anchor?stuff")] [InlineData( "http://contoso.com/someaction?name?something", "http://contoso.com/someaction?name?something&hello=world&some=text&another=")] [InlineData( "http://contoso.com/someaction#name#something", "http://contoso.com/someaction?hello=world&some=text&another=#name#something")] public void AddQueryStringWithDictionary(string uri, string expectedUri) { var queryStrings = new Dictionary<string, string?>() { { "hello", "world" }, { "some", "text" }, { "another", string.Empty }, { "invisible", null } }; var result = QueryHelpers.AddQueryString(uri, queryStrings); Assert.Equal(expectedUri, result); } [Theory] [InlineData("http://contoso.com/", "http://contoso.com/?param1=value1&param1=&param1=value3&param2=")] [InlineData("http://contoso.com/someaction", "http://contoso.com/someaction?param1=value1&param1=&param1=value3&param2=")] [InlineData("http://contoso.com/someaction?param2=1", "http://contoso.com/someaction?param2=1&param1=value1&param1=&param1=value3&param2=")] [InlineData("http://contoso.com/some#action", "http://contoso.com/some?param1=value1&param1=&param1=value3&param2=#action")] [InlineData("http://contoso.com/some?param2=1#action", "http://contoso.com/some?param2=1&param1=value1&param1=&param1=value3&param2=#action")] [InlineData("http://contoso.com/#action", "http://contoso.com/?param1=value1&param1=&param1=value3&param2=#action")] [InlineData( "http://contoso.com/someaction?q=test#anchor?value", "http://contoso.com/someaction?q=test&param1=value1&param1=&param1=value3&param2=#anchor?value")] [InlineData( "http://contoso.com/someaction#anchor?stuff", "http://contoso.com/someaction?param1=value1&param1=&param1=value3&param2=#anchor?stuff")] [InlineData( "http://contoso.com/someaction?name?something", "http://contoso.com/someaction?name?something&param1=value1&param1=&param1=value3&param2=")] [InlineData( "http://contoso.com/someaction#name#something", "http://contoso.com/someaction?param1=value1&param1=&param1=value3&param2=#name#something")] public void AddQueryStringWithEnumerableOfKeysAndStringValues(string uri, string expectedUri) { var queryStrings = new Dictionary<string, StringValues>() { { "param1", new StringValues(new [] { "value1", string.Empty, "value3" }) }, { "param2", string.Empty }, { "param3", StringValues.Empty } }; var result = QueryHelpers.AddQueryString(uri, queryStrings); Assert.Equal(expectedUri, result); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable MemberCanBePrivate.Global namespace Apache.Ignite.Core.Tests.Cache.Query { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cache.Query; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Resource; using NUnit.Framework; /// <summary> /// Queries tests. /// </summary> public class CacheQueriesTest { /** Grid count. */ private const int GridCnt = 2; /** Cache name. */ private const string CacheName = "cache"; /** Path to XML configuration. */ private const string CfgPath = "Config\\cache-query.xml"; /** Maximum amount of items in cache. */ private const int MaxItemCnt = 100; /// <summary> /// Fixture setup. /// </summary> [TestFixtureSetUp] public void StartGrids() { for (int i = 0; i < GridCnt; i++) { Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration()) { BinaryConfiguration = new BinaryConfiguration { NameMapper = GetNameMapper() }, SpringConfigUrl = CfgPath, IgniteInstanceName = "grid-" + i }); } } /// <summary> /// Gets the name mapper. /// </summary> protected virtual IBinaryNameMapper GetNameMapper() { return new BinaryBasicNameMapper {IsSimpleName = false}; } /// <summary> /// Fixture teardown. /// </summary> [TestFixtureTearDown] public void StopGrids() { Ignition.StopAll(true); } /// <summary> /// /// </summary> [SetUp] public void BeforeTest() { Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name); } /// <summary> /// /// </summary> [TearDown] public void AfterTest() { var cache = Cache(); for (int i = 0; i < GridCnt; i++) { cache.Clear(); Assert.IsTrue(cache.IsEmpty()); } TestUtils.AssertHandleRegistryIsEmpty(300, Enumerable.Range(0, GridCnt).Select(x => Ignition.GetIgnite("grid-" + x)).ToArray()); Console.WriteLine("Test finished: " + TestContext.CurrentContext.Test.Name); } /// <summary> /// Gets the ignite. /// </summary> private static IIgnite GetIgnite() { return Ignition.GetIgnite("grid-0"); } /// <summary> /// /// </summary> /// <returns></returns> private static ICache<int, QueryPerson> Cache() { return GetIgnite().GetCache<int, QueryPerson>(CacheName); } /// <summary> /// Test arguments validation for SQL queries. /// </summary> [Test] public void TestValidationSql() { // 1. No sql. Assert.Throws<ArgumentException>(() => { Cache().Query(new SqlQuery(typeof(QueryPerson), null)); }); // 2. No type. Assert.Throws<ArgumentException>(() => { Cache().Query(new SqlQuery((string)null, "age >= 50")); }); } /// <summary> /// Test arguments validation for SQL fields queries. /// </summary> [Test] public void TestValidationSqlFields() { // 1. No sql. Assert.Throws<ArgumentException>(() => { Cache().QueryFields(new SqlFieldsQuery(null)); }); } /// <summary> /// Test arguments validation for TEXT queries. /// </summary> [Test] public void TestValidationText() { // 1. No text. Assert.Throws<ArgumentException>(() => { Cache().Query(new TextQuery(typeof(QueryPerson), null)); }); // 2. No type. Assert.Throws<ArgumentException>(() => { Cache().Query(new TextQuery((string)null, "Ivanov")); }); } /// <summary> /// Cursor tests. /// </summary> [Test] [SuppressMessage("ReSharper", "ReturnValueOfPureMethodIsNotUsed")] public void TestCursor() { Cache().Put(1, new QueryPerson("Ivanov", 30)); Cache().Put(1, new QueryPerson("Petrov", 40)); Cache().Put(1, new QueryPerson("Sidorov", 50)); SqlQuery qry = new SqlQuery(typeof(QueryPerson), "age >= 20"); // 1. Test GetAll(). using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(qry)) { cursor.GetAll(); Assert.Throws<InvalidOperationException>(() => { cursor.GetAll(); }); Assert.Throws<InvalidOperationException>(() => { cursor.GetEnumerator(); }); } // 2. Test GetEnumerator. using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(qry)) { cursor.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => { cursor.GetAll(); }); Assert.Throws<InvalidOperationException>(() => { cursor.GetEnumerator(); }); } } /// <summary> /// Test enumerator. /// </summary> [Test] [SuppressMessage("ReSharper", "UnusedVariable")] public void TestEnumerator() { Cache().Put(1, new QueryPerson("Ivanov", 30)); Cache().Put(2, new QueryPerson("Petrov", 40)); Cache().Put(3, new QueryPerson("Sidorov", 50)); Cache().Put(4, new QueryPerson("Unknown", 60)); // 1. Empty result set. using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(new SqlQuery(typeof(QueryPerson), "age = 100"))) { IEnumerator<ICacheEntry<int, QueryPerson>> e = cursor.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => { ICacheEntry<int, QueryPerson> entry = e.Current; }); Assert.IsFalse(e.MoveNext()); Assert.Throws<InvalidOperationException>(() => { ICacheEntry<int, QueryPerson> entry = e.Current; }); Assert.Throws<NotSupportedException>(() => e.Reset()); e.Dispose(); } SqlQuery qry = new SqlQuery(typeof (QueryPerson), "age < 60"); Assert.AreEqual(QueryBase.DefaultPageSize, qry.PageSize); // 2. Page size is bigger than result set. qry.PageSize = 4; CheckEnumeratorQuery(qry); // 3. Page size equal to result set. qry.PageSize = 3; CheckEnumeratorQuery(qry); // 4. Page size if less than result set. qry.PageSize = 2; CheckEnumeratorQuery(qry); } /// <summary> /// Test SQL query arguments passing. /// </summary> [Test] public void TestSqlQueryArguments() { Cache().Put(1, new QueryPerson("Ivanov", 30)); Cache().Put(2, new QueryPerson("Petrov", 40)); Cache().Put(3, new QueryPerson("Sidorov", 50)); // 1. Empty result set. using ( IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(new SqlQuery(typeof(QueryPerson), "age < ?", 50))) { foreach (ICacheEntry<int, QueryPerson> entry in cursor.GetAll()) Assert.IsTrue(entry.Key == 1 || entry.Key == 2); } } /// <summary> /// Test SQL fields query arguments passing. /// </summary> [Test] public void TestSqlFieldsQueryArguments() { Cache().Put(1, new QueryPerson("Ivanov", 30)); Cache().Put(2, new QueryPerson("Petrov", 40)); Cache().Put(3, new QueryPerson("Sidorov", 50)); // 1. Empty result set. using ( IQueryCursor<IList> cursor = Cache().QueryFields( new SqlFieldsQuery("SELECT age FROM QueryPerson WHERE age < ?", 50))) { foreach (IList entry in cursor.GetAll()) Assert.IsTrue((int) entry[0] < 50); } } /// <summary> /// Check query result for enumerator test. /// </summary> /// <param name="qry">QUery.</param> private void CheckEnumeratorQuery(SqlQuery qry) { using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(qry)) { bool first = false; bool second = false; bool third = false; foreach (var entry in cursor) { if (entry.Key == 1) { first = true; Assert.AreEqual("Ivanov", entry.Value.Name); Assert.AreEqual(30, entry.Value.Age); } else if (entry.Key == 2) { second = true; Assert.AreEqual("Petrov", entry.Value.Name); Assert.AreEqual(40, entry.Value.Age); } else if (entry.Key == 3) { third = true; Assert.AreEqual("Sidorov", entry.Value.Name); Assert.AreEqual(50, entry.Value.Age); } else Assert.Fail("Unexpected value: " + entry); } Assert.IsTrue(first && second && third); } } /// <summary> /// Check SQL query. /// </summary> [Test] public void TestSqlQuery([Values(true, false)] bool loc, [Values(true, false)] bool keepBinary, [Values(true, false)] bool distrJoin) { var cache = Cache(); // 1. Populate cache with data, calculating expected count in parallel. var exp = PopulateCache(cache, loc, MaxItemCnt, x => x < 50); // 2. Validate results. var qry = new SqlQuery(typeof(QueryPerson), "age < 50", loc) { EnableDistributedJoins = distrJoin, ReplicatedOnly = false, Timeout = TimeSpan.FromSeconds(3) }; Assert.AreEqual(string.Format("SqlQuery [Sql=age < 50, Arguments=[], Local={0}, " + "PageSize=1024, EnableDistributedJoins={1}, Timeout={2}, " + "ReplicatedOnly=False]", loc, distrJoin, qry.Timeout), qry.ToString()); ValidateQueryResults(cache, qry, exp, keepBinary); } /// <summary> /// Check SQL fields query. /// </summary> [Test] public void TestSqlFieldsQuery([Values(true, false)] bool loc, [Values(true, false)] bool distrJoin, [Values(true, false)] bool enforceJoinOrder, [Values(true, false)] bool lazy) { int cnt = MaxItemCnt; var cache = Cache(); // 1. Populate cache with data, calculating expected count in parallel. var exp = PopulateCache(cache, loc, cnt, x => x < 50); // 2. Validate results. var qry = new SqlFieldsQuery("SELECT name, age FROM QueryPerson WHERE age < 50") { EnableDistributedJoins = distrJoin, EnforceJoinOrder = enforceJoinOrder, Colocated = !distrJoin, ReplicatedOnly = false, Local = loc, Timeout = TimeSpan.FromSeconds(2), Lazy = lazy }; using (IQueryCursor<IList> cursor = cache.QueryFields(qry)) { HashSet<int> exp0 = new HashSet<int>(exp); foreach (var entry in cursor.GetAll()) { Assert.AreEqual(2, entry.Count); Assert.AreEqual(entry[0].ToString(), entry[1].ToString()); exp0.Remove((int)entry[1]); } Assert.AreEqual(0, exp0.Count); } using (IQueryCursor<IList> cursor = cache.QueryFields(qry)) { HashSet<int> exp0 = new HashSet<int>(exp); foreach (var entry in cursor) { Assert.AreEqual(entry[0].ToString(), entry[1].ToString()); exp0.Remove((int)entry[1]); } Assert.AreEqual(0, exp0.Count); } } /// <summary> /// Tests that query configuration propagates from Spring XML correctly. /// </summary> [Test] public void TestQueryConfiguration() { var qe = Cache().GetConfiguration().QueryEntities.Single(); Assert.AreEqual(typeof(QueryPerson).FullName, qe.ValueTypeName); var age = qe.Fields.First(); Assert.AreEqual("age", age.Name); Assert.AreEqual(typeof(int), age.FieldType); Assert.IsFalse(age.IsKeyField); var name = qe.Fields.Last(); Assert.AreEqual("name", name.Name); Assert.AreEqual(typeof(string), name.FieldType); Assert.IsFalse(name.IsKeyField); var textIdx = qe.Indexes.First(); Assert.AreEqual(QueryIndexType.FullText, textIdx.IndexType); Assert.AreEqual("name", textIdx.Fields.Single().Name); Assert.AreEqual(QueryIndex.DefaultInlineSize, textIdx.InlineSize); var sqlIdx = qe.Indexes.Last(); Assert.AreEqual(QueryIndexType.Sorted, sqlIdx.IndexType); Assert.AreEqual("age", sqlIdx.Fields.Single().Name); Assert.AreEqual(2345, sqlIdx.InlineSize); } /// <summary> /// Check text query. /// </summary> [Test] public void TestTextQuery([Values(true, false)] bool loc, [Values(true, false)] bool keepBinary) { var cache = Cache(); // 1. Populate cache with data, calculating expected count in parallel. var exp = PopulateCache(cache, loc, MaxItemCnt, x => x.ToString().StartsWith("1")); // 2. Validate results. var qry = new TextQuery(typeof(QueryPerson), "1*", loc); ValidateQueryResults(cache, qry, exp, keepBinary); } /// <summary> /// Check scan query. /// </summary> [Test] public void TestScanQuery([Values(true, false)] bool loc) { CheckScanQuery<QueryPerson>(loc, false); } /// <summary> /// Check scan query in binary mode. /// </summary> [Test] public void TestScanQueryBinary([Values(true, false)] bool loc) { CheckScanQuery<IBinaryObject>(loc, true); } /// <summary> /// Check scan query with partitions. /// </summary> [Test] public void TestScanQueryPartitions([Values(true, false)] bool loc) { CheckScanQueryPartitions<QueryPerson>(loc, false); } /// <summary> /// Check scan query with partitions in binary mode. /// </summary> [Test] public void TestScanQueryPartitionsBinary([Values(true, false)] bool loc) { CheckScanQueryPartitions<IBinaryObject>(loc, true); } /// <summary> /// Tests that query attempt on non-indexed cache causes an exception. /// </summary> [Test] public void TestIndexingDisabledError() { var cache = GetIgnite().GetOrCreateCache<int, QueryPerson>("nonindexed_cache"); // Text query. var err = Assert.Throws<IgniteException>(() => cache.Query(new TextQuery(typeof(QueryPerson), "1*"))); Assert.AreEqual("Indexing is disabled for cache: nonindexed_cache. " + "Use setIndexedTypes or setTypeMetadata methods on CacheConfiguration to enable.", err.Message); // SQL query. err = Assert.Throws<IgniteException>(() => cache.Query(new SqlQuery(typeof(QueryPerson), "age < 50"))); Assert.AreEqual("Failed to find SQL table for type: QueryPerson", err.Message); } /// <summary> /// Check scan query. /// </summary> /// <param name="loc">Local query flag.</param> /// <param name="keepBinary">Keep binary flag.</param> private static void CheckScanQuery<TV>(bool loc, bool keepBinary) { var cache = Cache(); int cnt = MaxItemCnt; // No predicate var exp = PopulateCache(cache, loc, cnt, x => true); var qry = new ScanQuery<int, TV>(); ValidateQueryResults(cache, qry, exp, keepBinary); // Serializable exp = PopulateCache(cache, loc, cnt, x => x < 50); qry = new ScanQuery<int, TV>(new ScanQueryFilter<TV>()); ValidateQueryResults(cache, qry, exp, keepBinary); // Binarizable exp = PopulateCache(cache, loc, cnt, x => x < 50); qry = new ScanQuery<int, TV>(new BinarizableScanQueryFilter<TV>()); ValidateQueryResults(cache, qry, exp, keepBinary); // Invalid exp = PopulateCache(cache, loc, cnt, x => x < 50); qry = new ScanQuery<int, TV>(new InvalidScanQueryFilter<TV>()); Assert.Throws<BinaryObjectException>(() => ValidateQueryResults(cache, qry, exp, keepBinary)); // Exception exp = PopulateCache(cache, loc, cnt, x => x < 50); qry = new ScanQuery<int, TV>(new ScanQueryFilter<TV> {ThrowErr = true}); var ex = Assert.Throws<IgniteException>(() => ValidateQueryResults(cache, qry, exp, keepBinary)); Assert.AreEqual(ScanQueryFilter<TV>.ErrMessage, ex.Message); } /// <summary> /// Checks scan query with partitions. /// </summary> /// <param name="loc">Local query flag.</param> /// <param name="keepBinary">Keep binary flag.</param> private void CheckScanQueryPartitions<TV>(bool loc, bool keepBinary) { StopGrids(); StartGrids(); var cache = Cache(); int cnt = MaxItemCnt; var aff = cache.Ignite.GetAffinity(CacheName); var exp = PopulateCache(cache, loc, cnt, x => true); // populate outside the loop (slow) for (var part = 0; part < aff.Partitions; part++) { //var exp0 = new HashSet<int>(exp.Where(x => aff.Partition(x) == part)); // filter expected keys var exp0 = new HashSet<int>(); foreach (var x in exp) if (aff.GetPartition(x) == part) exp0.Add(x); var qry = new ScanQuery<int, TV> { Partition = part }; ValidateQueryResults(cache, qry, exp0, keepBinary); } // Partitions with predicate exp = PopulateCache(cache, loc, cnt, x => x < 50); // populate outside the loop (slow) for (var part = 0; part < aff.Partitions; part++) { //var exp0 = new HashSet<int>(exp.Where(x => aff.Partition(x) == part)); // filter expected keys var exp0 = new HashSet<int>(); foreach (var x in exp) if (aff.GetPartition(x) == part) exp0.Add(x); var qry = new ScanQuery<int, TV>(new ScanQueryFilter<TV>()) { Partition = part }; ValidateQueryResults(cache, qry, exp0, keepBinary); } } /// <summary> /// Tests custom schema name. /// </summary> [Test] public void TestCustomSchema() { var doubles = GetIgnite().GetOrCreateCache<int, double>(new CacheConfiguration("doubles", typeof(double))); var strings = GetIgnite().GetOrCreateCache<int, string>(new CacheConfiguration("strings", typeof(string))); doubles[1] = 36.6; strings[1] = "foo"; // Default schema. var res = doubles.QueryFields(new SqlFieldsQuery( "select S._val from double as D join \"strings\".string as S on S._key = D._key")) .Select(x => (string) x[0]) .Single(); Assert.AreEqual("foo", res); // Custom schema. res = doubles.QueryFields(new SqlFieldsQuery( "select S._val from \"doubles\".double as D join string as S on S._key = D._key") { Schema = strings.Name }) .Select(x => (string)x[0]) .Single(); Assert.AreEqual("foo", res); } /// <summary> /// Tests the distributed joins flag. /// </summary> [Test] public void TestDistributedJoins() { var cache = GetIgnite().GetOrCreateCache<int, QueryPerson>( new CacheConfiguration("replicatedCache") { QueryEntities = new[] { new QueryEntity(typeof(int), typeof(QueryPerson)) { Fields = new[] {new QueryField("age", "int")} } } }); const int count = 100; cache.PutAll(Enumerable.Range(0, count).ToDictionary(x => x, x => new QueryPerson("Name" + x, x))); // Test non-distributed join: returns partial results var sql = "select T0.Age from QueryPerson as T0 " + "inner join QueryPerson as T1 on ((? - T1.Age - 1) = T0._key)"; var res = cache.QueryFields(new SqlFieldsQuery(sql, count)).GetAll().Distinct().Count(); Assert.Greater(res, 0); Assert.Less(res, count); // Test distributed join: returns complete results res = cache.QueryFields(new SqlFieldsQuery(sql, count) {EnableDistributedJoins = true}) .GetAll().Distinct().Count(); Assert.AreEqual(count, res); } /// <summary> /// Tests the get configuration. /// </summary> [Test] public void TestGetConfiguration() { var entity = Cache().GetConfiguration().QueryEntities.Single(); var ageField = entity.Fields.Single(x => x.Name == "age"); Assert.AreEqual(typeof(int), ageField.FieldType); Assert.IsFalse(ageField.NotNull); Assert.IsFalse(ageField.IsKeyField); var nameField = entity.Fields.Single(x => x.Name == "name"); Assert.AreEqual(typeof(string), nameField.FieldType); Assert.IsTrue(nameField.NotNull); Assert.IsFalse(nameField.IsKeyField); } /// <summary> /// Tests custom key and value field names. /// </summary> [Test] public void TestCustomKeyValueFieldNames() { // Check select * with default config - does not include _key, _val. var cache = Cache(); cache[1] = new QueryPerson("Joe", 48); var row = cache.QueryFields(new SqlFieldsQuery("select * from QueryPerson")).GetAll()[0]; Assert.AreEqual(2, row.Count); Assert.AreEqual(48, row[0]); Assert.AreEqual("Joe", row[1]); // Check select * with custom names - fields are included. cache = GetIgnite().GetOrCreateCache<int, QueryPerson>( new CacheConfiguration("customKeyVal") { QueryEntities = new[] { new QueryEntity(typeof(int), typeof(QueryPerson)) { Fields = new[] { new QueryField("age", "int"), new QueryField("FullKey", "int"), new QueryField("FullVal", "QueryPerson") }, KeyFieldName = "FullKey", ValueFieldName = "FullVal" } } }); cache[1] = new QueryPerson("John", 33); row = cache.QueryFields(new SqlFieldsQuery("select * from QueryPerson")).GetAll()[0]; Assert.AreEqual(3, row.Count); Assert.AreEqual(33, row[0]); Assert.AreEqual(1, row[1]); var person = (QueryPerson) row[2]; Assert.AreEqual("John", person.Name); // Check explicit select. row = cache.QueryFields(new SqlFieldsQuery("select FullKey from QueryPerson")).GetAll()[0]; Assert.AreEqual(1, row[0]); } /// <summary> /// Tests query timeouts. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestSqlQueryTimeout() { var cache = Cache(); PopulateCache(cache, false, 20000, x => true); var sqlQry = new SqlQuery(typeof(QueryPerson), "WHERE age < 500 AND name like '%1%'") { Timeout = TimeSpan.FromMilliseconds(2) }; // ReSharper disable once ReturnValueOfPureMethodIsNotUsed var ex = Assert.Throws<CacheException>(() => cache.Query(sqlQry).ToArray()); Assert.IsTrue(ex.ToString().Contains("QueryCancelledException: The query was cancelled while executing.")); } /// <summary> /// Tests fields query timeouts. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestSqlFieldsQueryTimeout() { var cache = Cache(); PopulateCache(cache, false, 20000, x => true); var fieldsQry = new SqlFieldsQuery("SELECT * FROM QueryPerson WHERE age < 5000 AND name like '%0%'") { Timeout = TimeSpan.FromMilliseconds(3) }; // ReSharper disable once ReturnValueOfPureMethodIsNotUsed var ex = Assert.Throws<CacheException>(() => cache.QueryFields(fieldsQry).ToArray()); Assert.IsTrue(ex.ToString().Contains("QueryCancelledException: The query was cancelled while executing.")); } /// <summary> /// Validates the query results. /// </summary> /// <param name="cache">Cache.</param> /// <param name="qry">Query.</param> /// <param name="exp">Expected keys.</param> /// <param name="keepBinary">Keep binary flag.</param> private static void ValidateQueryResults(ICache<int, QueryPerson> cache, QueryBase qry, HashSet<int> exp, bool keepBinary) { if (keepBinary) { var cache0 = cache.WithKeepBinary<int, IBinaryObject>(); using (var cursor = cache0.Query(qry)) { HashSet<int> exp0 = new HashSet<int>(exp); var all = new List<ICacheEntry<int, object>>(); foreach (var entry in cursor.GetAll()) { all.Add(entry); Assert.AreEqual(entry.Key.ToString(), entry.Value.GetField<string>("name")); Assert.AreEqual(entry.Key, entry.Value.GetField<int>("age")); exp0.Remove(entry.Key); } AssertMissingExpectedKeys(exp0, cache, all); } using (var cursor = cache0.Query(qry)) { HashSet<int> exp0 = new HashSet<int>(exp); var all = new List<ICacheEntry<int, object>>(); foreach (var entry in cursor) { all.Add(entry); Assert.AreEqual(entry.Key.ToString(), entry.Value.GetField<string>("name")); Assert.AreEqual(entry.Key, entry.Value.GetField<int>("age")); exp0.Remove(entry.Key); } AssertMissingExpectedKeys(exp0, cache, all); } } else { using (var cursor = cache.Query(qry)) { HashSet<int> exp0 = new HashSet<int>(exp); var all = new List<ICacheEntry<int, object>>(); foreach (var entry in cursor.GetAll()) { all.Add(entry); Assert.AreEqual(entry.Key.ToString(), entry.Value.Name); Assert.AreEqual(entry.Key, entry.Value.Age); exp0.Remove(entry.Key); } AssertMissingExpectedKeys(exp0, cache, all); } using (var cursor = cache.Query(qry)) { HashSet<int> exp0 = new HashSet<int>(exp); var all = new List<ICacheEntry<int, object>>(); foreach (var entry in cursor) { all.Add(entry); Assert.AreEqual(entry.Key.ToString(), entry.Value.Name); Assert.AreEqual(entry.Key, entry.Value.Age); exp0.Remove(entry.Key); } AssertMissingExpectedKeys(exp0, cache, all); } } } /// <summary> /// Asserts that all expected entries have been received. /// </summary> private static void AssertMissingExpectedKeys(ICollection<int> exp, ICache<int, QueryPerson> cache, IList<ICacheEntry<int, object>> all) { if (exp.Count == 0) return; var sb = new StringBuilder(); var aff = cache.Ignite.GetAffinity(cache.Name); foreach (var key in exp) { var part = aff.GetPartition(key); sb.AppendFormat( "Query did not return expected key '{0}' (exists: {1}), partition '{2}', partition nodes: ", key, cache.Get(key) != null, part); var partNodes = aff.MapPartitionToPrimaryAndBackups(part); foreach (var node in partNodes) sb.Append(node).Append(" "); sb.AppendLine(";"); } sb.Append("Returned keys: "); foreach (var e in all) sb.Append(e.Key).Append(" "); sb.AppendLine(";"); Assert.Fail(sb.ToString()); } /// <summary> /// Populates the cache with random entries and returns expected results set according to filter. /// </summary> /// <param name="cache">The cache.</param> /// <param name="cnt">Amount of cache entries to create.</param> /// <param name="loc">Local query flag.</param> /// <param name="expectedEntryFilter">The expected entry filter.</param> /// <returns>Expected results set.</returns> private static HashSet<int> PopulateCache(ICache<int, QueryPerson> cache, bool loc, int cnt, Func<int, bool> expectedEntryFilter) { var rand = new Random(); for (var i = 0; i < cnt; i++) { var val = rand.Next(cnt); cache.Put(val, new QueryPerson(val.ToString(), val)); } var entries = loc ? cache.GetLocalEntries(CachePeekMode.Primary) : cache; return new HashSet<int>(entries.Select(x => x.Key).Where(expectedEntryFilter)); } } /// <summary> /// Person. /// </summary> public class QueryPerson { /// <summary> /// Constructor. /// </summary> /// <param name="name">Name.</param> /// <param name="age">Age.</param> public QueryPerson(string name, int age) { Name = name; Age = age % 2000; Birthday = DateTime.UtcNow.AddYears(-Age); } /// <summary> /// Name. /// </summary> public string Name { get; set; } /// <summary> /// Age. /// </summary> public int Age { get; set; } /// <summary> /// Gets or sets the birthday. /// </summary> [QuerySqlField] // Enforce Timestamp serialization public DateTime Birthday { get; set; } } /// <summary> /// Query filter. /// </summary> [Serializable] public class ScanQueryFilter<TV> : ICacheEntryFilter<int, TV> { // Error message public const string ErrMessage = "Error in ScanQueryFilter.Invoke"; // Error flag public bool ThrowErr { get; set; } // Injection test [InstanceResource] public IIgnite Ignite { get; set; } /** <inheritdoc /> */ public bool Invoke(ICacheEntry<int, TV> entry) { Assert.IsNotNull(Ignite); if (ThrowErr) throw new Exception(ErrMessage); return entry.Key < 50; } } /// <summary> /// binary query filter. /// </summary> public class BinarizableScanQueryFilter<TV> : ScanQueryFilter<TV>, IBinarizable { /** <inheritdoc /> */ public void WriteBinary(IBinaryWriter writer) { var w = writer.GetRawWriter(); w.WriteBoolean(ThrowErr); } /** <inheritdoc /> */ public void ReadBinary(IBinaryReader reader) { var r = reader.GetRawReader(); ThrowErr = r.ReadBoolean(); } } /// <summary> /// Filter that can't be serialized. /// </summary> public class InvalidScanQueryFilter<TV> : ScanQueryFilter<TV>, IBinarizable { public void WriteBinary(IBinaryWriter writer) { throw new BinaryObjectException("Expected"); } public void ReadBinary(IBinaryReader reader) { throw new BinaryObjectException("Expected"); } } }
// ----------------------------------------------------------------------- // <copyright file="ManagementList.Generated.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // <auto-generated> // This code was generated by a tool. DO NOT EDIT // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> // ----------------------------------------------------------------------- #region StyleCop Suppression - generated code using System; using System.ComponentModel; using System.Windows; using System.Windows.Automation.Peers; using System.Windows.Controls; using System.Windows.Input; namespace Microsoft.Management.UI.Internal { /// <summary> /// Interaction logic for ManagementList. /// </summary> [TemplatePart(Name="PART_ViewManager", Type=typeof(ListOrganizer))] [TemplatePart(Name="PART_ViewSaver", Type=typeof(PickerBase))] [Localizability(LocalizationCategory.None)] partial class ManagementList { // // Fields // private ListOrganizer viewManager; private PickerBase viewSaver; // // ViewsChanged RoutedEvent // /// <summary> /// Identifies the ViewsChanged RoutedEvent. /// </summary> public static readonly RoutedEvent ViewsChangedEvent = EventManager.RegisterRoutedEvent("ViewsChanged",RoutingStrategy.Bubble,typeof(RoutedEventHandler),typeof(ManagementList)); /// <summary> /// Occurs when any of this instance's views change. /// </summary> public event RoutedEventHandler ViewsChanged { add { AddHandler(ViewsChangedEvent,value); } remove { RemoveHandler(ViewsChangedEvent,value); } } // // ClearFilter routed command // /// <summary> /// Informs the ManagementList that it should clear the filter that is applied. /// </summary> public static readonly RoutedCommand ClearFilterCommand = new RoutedCommand("ClearFilter",typeof(ManagementList)); static private void ClearFilterCommand_CommandCanExecute(object sender, CanExecuteRoutedEventArgs e) { ManagementList obj = (ManagementList) sender; obj.OnClearFilterCanExecute( e ); } static private void ClearFilterCommand_CommandExecuted(object sender, ExecutedRoutedEventArgs e) { ManagementList obj = (ManagementList) sender; obj.OnClearFilterExecuted( e ); } /// <summary> /// Called to determine if ClearFilter can execute. /// </summary> protected virtual void OnClearFilterCanExecute(CanExecuteRoutedEventArgs e) { OnClearFilterCanExecuteImplementation(e); } partial void OnClearFilterCanExecuteImplementation(CanExecuteRoutedEventArgs e); /// <summary> /// Called when ClearFilter executes. /// </summary> /// <remarks> /// Informs the ManagementList that it should clear the filter that is applied. /// </remarks> protected virtual void OnClearFilterExecuted(ExecutedRoutedEventArgs e) { OnClearFilterExecutedImplementation(e); } partial void OnClearFilterExecutedImplementation(ExecutedRoutedEventArgs e); // // SaveView routed command // /// <summary> /// Informs the PickerBase that it should close the dropdown. /// </summary> public static readonly RoutedCommand SaveViewCommand = new RoutedCommand("SaveView",typeof(ManagementList)); static private void SaveViewCommand_CommandCanExecute(object sender, CanExecuteRoutedEventArgs e) { ManagementList obj = (ManagementList) sender; obj.OnSaveViewCanExecute( e ); } static private void SaveViewCommand_CommandExecuted(object sender, ExecutedRoutedEventArgs e) { ManagementList obj = (ManagementList) sender; obj.OnSaveViewExecuted( e ); } /// <summary> /// Called to determine if SaveView can execute. /// </summary> protected virtual void OnSaveViewCanExecute(CanExecuteRoutedEventArgs e) { OnSaveViewCanExecuteImplementation(e); } partial void OnSaveViewCanExecuteImplementation(CanExecuteRoutedEventArgs e); /// <summary> /// Called when SaveView executes. /// </summary> /// <remarks> /// Informs the PickerBase that it should close the dropdown. /// </remarks> protected virtual void OnSaveViewExecuted(ExecutedRoutedEventArgs e) { OnSaveViewExecutedImplementation(e); } partial void OnSaveViewExecutedImplementation(ExecutedRoutedEventArgs e); // // StartFilter routed command // /// <summary> /// Informs the ManagementList that it should apply the filter. /// </summary> public static readonly RoutedCommand StartFilterCommand = new RoutedCommand("StartFilter",typeof(ManagementList)); static private void StartFilterCommand_CommandCanExecute(object sender, CanExecuteRoutedEventArgs e) { ManagementList obj = (ManagementList) sender; obj.OnStartFilterCanExecute( e ); } static private void StartFilterCommand_CommandExecuted(object sender, ExecutedRoutedEventArgs e) { ManagementList obj = (ManagementList) sender; obj.OnStartFilterExecuted( e ); } /// <summary> /// Called to determine if StartFilter can execute. /// </summary> protected virtual void OnStartFilterCanExecute(CanExecuteRoutedEventArgs e) { OnStartFilterCanExecuteImplementation(e); } partial void OnStartFilterCanExecuteImplementation(CanExecuteRoutedEventArgs e); /// <summary> /// Called when StartFilter executes. /// </summary> /// <remarks> /// Informs the ManagementList that it should apply the filter. /// </remarks> protected virtual void OnStartFilterExecuted(ExecutedRoutedEventArgs e) { OnStartFilterExecutedImplementation(e); } partial void OnStartFilterExecutedImplementation(ExecutedRoutedEventArgs e); // // StopFilter routed command // /// <summary> /// Informs the ManagementList that it should stop filtering that is in progress. /// </summary> public static readonly RoutedCommand StopFilterCommand = new RoutedCommand("StopFilter",typeof(ManagementList)); static private void StopFilterCommand_CommandCanExecute(object sender, CanExecuteRoutedEventArgs e) { ManagementList obj = (ManagementList) sender; obj.OnStopFilterCanExecute( e ); } static private void StopFilterCommand_CommandExecuted(object sender, ExecutedRoutedEventArgs e) { ManagementList obj = (ManagementList) sender; obj.OnStopFilterExecuted( e ); } /// <summary> /// Called to determine if StopFilter can execute. /// </summary> protected virtual void OnStopFilterCanExecute(CanExecuteRoutedEventArgs e) { OnStopFilterCanExecuteImplementation(e); } partial void OnStopFilterCanExecuteImplementation(CanExecuteRoutedEventArgs e); /// <summary> /// Called when StopFilter executes. /// </summary> /// <remarks> /// Informs the ManagementList that it should stop filtering that is in progress. /// </remarks> protected virtual void OnStopFilterExecuted(ExecutedRoutedEventArgs e) { OnStopFilterExecutedImplementation(e); } partial void OnStopFilterExecutedImplementation(ExecutedRoutedEventArgs e); // // AddFilterRulePicker dependency property // /// <summary> /// Identifies the AddFilterRulePicker dependency property key. /// </summary> private static readonly DependencyPropertyKey AddFilterRulePickerPropertyKey = DependencyProperty.RegisterReadOnly( "AddFilterRulePicker", typeof(AddFilterRulePicker), typeof(ManagementList), new PropertyMetadata( null, AddFilterRulePickerProperty_PropertyChanged) ); /// <summary> /// Identifies the AddFilterRulePicker dependency property. /// </summary> public static readonly DependencyProperty AddFilterRulePickerProperty = AddFilterRulePickerPropertyKey.DependencyProperty; /// <summary> /// Gets the filter rule picker. /// </summary> [Bindable(true)] [Category("Common Properties")] [Description("Gets the filter rule picker.")] [Localizability(LocalizationCategory.None)] public AddFilterRulePicker AddFilterRulePicker { get { return (AddFilterRulePicker) GetValue(AddFilterRulePickerProperty); } private set { SetValue(AddFilterRulePickerPropertyKey,value); } } static private void AddFilterRulePickerProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { ManagementList obj = (ManagementList) o; obj.OnAddFilterRulePickerChanged( new PropertyChangedEventArgs<AddFilterRulePicker>((AddFilterRulePicker)e.OldValue, (AddFilterRulePicker)e.NewValue) ); } /// <summary> /// Occurs when AddFilterRulePicker property changes. /// </summary> public event EventHandler<PropertyChangedEventArgs<AddFilterRulePicker>> AddFilterRulePickerChanged; /// <summary> /// Called when AddFilterRulePicker property changes. /// </summary> protected virtual void OnAddFilterRulePickerChanged(PropertyChangedEventArgs<AddFilterRulePicker> e) { OnAddFilterRulePickerChangedImplementation(e); RaisePropertyChangedEvent(AddFilterRulePickerChanged, e); } partial void OnAddFilterRulePickerChangedImplementation(PropertyChangedEventArgs<AddFilterRulePicker> e); // // CurrentView dependency property // /// <summary> /// Identifies the CurrentView dependency property key. /// </summary> private static readonly DependencyPropertyKey CurrentViewPropertyKey = DependencyProperty.RegisterReadOnly( "CurrentView", typeof(StateDescriptor<ManagementList>), typeof(ManagementList), new PropertyMetadata( null, CurrentViewProperty_PropertyChanged) ); /// <summary> /// Identifies the CurrentView dependency property. /// </summary> public static readonly DependencyProperty CurrentViewProperty = CurrentViewPropertyKey.DependencyProperty; /// <summary> /// Gets or sets current view. /// </summary> [Bindable(true)] [Category("Common Properties")] [Description("Gets or sets current view.")] [Localizability(LocalizationCategory.None)] public StateDescriptor<ManagementList> CurrentView { get { return (StateDescriptor<ManagementList>) GetValue(CurrentViewProperty); } private set { SetValue(CurrentViewPropertyKey,value); } } static private void CurrentViewProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { ManagementList obj = (ManagementList) o; obj.OnCurrentViewChanged( new PropertyChangedEventArgs<StateDescriptor<ManagementList>>((StateDescriptor<ManagementList>)e.OldValue, (StateDescriptor<ManagementList>)e.NewValue) ); } /// <summary> /// Occurs when CurrentView property changes. /// </summary> public event EventHandler<PropertyChangedEventArgs<StateDescriptor<ManagementList>>> CurrentViewChanged; /// <summary> /// Called when CurrentView property changes. /// </summary> protected virtual void OnCurrentViewChanged(PropertyChangedEventArgs<StateDescriptor<ManagementList>> e) { OnCurrentViewChangedImplementation(e); RaisePropertyChangedEvent(CurrentViewChanged, e); } partial void OnCurrentViewChangedImplementation(PropertyChangedEventArgs<StateDescriptor<ManagementList>> e); // // Evaluator dependency property // /// <summary> /// Identifies the Evaluator dependency property. /// </summary> public static readonly DependencyProperty EvaluatorProperty = DependencyProperty.Register( "Evaluator", typeof(ItemsControlFilterEvaluator), typeof(ManagementList), new PropertyMetadata( null, EvaluatorProperty_PropertyChanged) ); /// <summary> /// Gets or sets the FilterEvaluator. /// </summary> [Bindable(true)] [Category("Common Properties")] [Description("Gets or sets the FilterEvaluator.")] [Localizability(LocalizationCategory.None)] public ItemsControlFilterEvaluator Evaluator { get { return (ItemsControlFilterEvaluator) GetValue(EvaluatorProperty); } set { SetValue(EvaluatorProperty,value); } } static private void EvaluatorProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { ManagementList obj = (ManagementList) o; obj.OnEvaluatorChanged( new PropertyChangedEventArgs<ItemsControlFilterEvaluator>((ItemsControlFilterEvaluator)e.OldValue, (ItemsControlFilterEvaluator)e.NewValue) ); } /// <summary> /// Occurs when Evaluator property changes. /// </summary> public event EventHandler<PropertyChangedEventArgs<ItemsControlFilterEvaluator>> EvaluatorChanged; /// <summary> /// Called when Evaluator property changes. /// </summary> protected virtual void OnEvaluatorChanged(PropertyChangedEventArgs<ItemsControlFilterEvaluator> e) { OnEvaluatorChangedImplementation(e); RaisePropertyChangedEvent(EvaluatorChanged, e); } partial void OnEvaluatorChangedImplementation(PropertyChangedEventArgs<ItemsControlFilterEvaluator> e); // // FilterRulePanel dependency property // /// <summary> /// Identifies the FilterRulePanel dependency property key. /// </summary> private static readonly DependencyPropertyKey FilterRulePanelPropertyKey = DependencyProperty.RegisterReadOnly( "FilterRulePanel", typeof(FilterRulePanel), typeof(ManagementList), new PropertyMetadata( null, FilterRulePanelProperty_PropertyChanged) ); /// <summary> /// Identifies the FilterRulePanel dependency property. /// </summary> public static readonly DependencyProperty FilterRulePanelProperty = FilterRulePanelPropertyKey.DependencyProperty; /// <summary> /// Gets the filter rule panel. /// </summary> [Bindable(true)] [Category("Common Properties")] [Description("Gets the filter rule panel.")] [Localizability(LocalizationCategory.None)] public FilterRulePanel FilterRulePanel { get { return (FilterRulePanel) GetValue(FilterRulePanelProperty); } private set { SetValue(FilterRulePanelPropertyKey,value); } } static private void FilterRulePanelProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { ManagementList obj = (ManagementList) o; obj.OnFilterRulePanelChanged( new PropertyChangedEventArgs<FilterRulePanel>((FilterRulePanel)e.OldValue, (FilterRulePanel)e.NewValue) ); } /// <summary> /// Occurs when FilterRulePanel property changes. /// </summary> public event EventHandler<PropertyChangedEventArgs<FilterRulePanel>> FilterRulePanelChanged; /// <summary> /// Called when FilterRulePanel property changes. /// </summary> protected virtual void OnFilterRulePanelChanged(PropertyChangedEventArgs<FilterRulePanel> e) { OnFilterRulePanelChangedImplementation(e); RaisePropertyChangedEvent(FilterRulePanelChanged, e); } partial void OnFilterRulePanelChangedImplementation(PropertyChangedEventArgs<FilterRulePanel> e); // // IsFilterShown dependency property // /// <summary> /// Identifies the IsFilterShown dependency property. /// </summary> public static readonly DependencyProperty IsFilterShownProperty = DependencyProperty.Register( "IsFilterShown", typeof(bool), typeof(ManagementList), new PropertyMetadata( BooleanBoxes.TrueBox, IsFilterShownProperty_PropertyChanged) ); /// <summary> /// Gets or sets a value indicating whether the filter is shown. /// </summary> [Bindable(true)] [Category("Common Properties")] [Description("Gets or sets a value indicating whether the filter is shown.")] [Localizability(LocalizationCategory.None)] public bool IsFilterShown { get { return (bool) GetValue(IsFilterShownProperty); } set { SetValue(IsFilterShownProperty,BooleanBoxes.Box(value)); } } static private void IsFilterShownProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { ManagementList obj = (ManagementList) o; obj.OnIsFilterShownChanged( new PropertyChangedEventArgs<bool>((bool)e.OldValue, (bool)e.NewValue) ); } /// <summary> /// Occurs when IsFilterShown property changes. /// </summary> public event EventHandler<PropertyChangedEventArgs<bool>> IsFilterShownChanged; /// <summary> /// Called when IsFilterShown property changes. /// </summary> protected virtual void OnIsFilterShownChanged(PropertyChangedEventArgs<bool> e) { OnIsFilterShownChangedImplementation(e); RaisePropertyChangedEvent(IsFilterShownChanged, e); } partial void OnIsFilterShownChangedImplementation(PropertyChangedEventArgs<bool> e); // // IsLoadingItems dependency property // /// <summary> /// Identifies the IsLoadingItems dependency property. /// </summary> public static readonly DependencyProperty IsLoadingItemsProperty = DependencyProperty.Register( "IsLoadingItems", typeof(bool), typeof(ManagementList), new PropertyMetadata( BooleanBoxes.FalseBox, IsLoadingItemsProperty_PropertyChanged) ); /// <summary> /// Gets or sets a value indicating whether items are loading. /// </summary> [Bindable(true)] [Category("Common Properties")] [Description("Gets or sets a value indicating whether items are loading.")] [Localizability(LocalizationCategory.None)] public bool IsLoadingItems { get { return (bool) GetValue(IsLoadingItemsProperty); } set { SetValue(IsLoadingItemsProperty,BooleanBoxes.Box(value)); } } static private void IsLoadingItemsProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { ManagementList obj = (ManagementList) o; obj.OnIsLoadingItemsChanged( new PropertyChangedEventArgs<bool>((bool)e.OldValue, (bool)e.NewValue) ); } /// <summary> /// Occurs when IsLoadingItems property changes. /// </summary> public event EventHandler<PropertyChangedEventArgs<bool>> IsLoadingItemsChanged; /// <summary> /// Called when IsLoadingItems property changes. /// </summary> protected virtual void OnIsLoadingItemsChanged(PropertyChangedEventArgs<bool> e) { OnIsLoadingItemsChangedImplementation(e); RaisePropertyChangedEvent(IsLoadingItemsChanged, e); } partial void OnIsLoadingItemsChangedImplementation(PropertyChangedEventArgs<bool> e); // // IsSearchShown dependency property // /// <summary> /// Identifies the IsSearchShown dependency property. /// </summary> public static readonly DependencyProperty IsSearchShownProperty = DependencyProperty.Register( "IsSearchShown", typeof(bool), typeof(ManagementList), new PropertyMetadata( BooleanBoxes.TrueBox, IsSearchShownProperty_PropertyChanged) ); /// <summary> /// Gets or sets a value indicating whether the search box is shown. /// </summary> [Bindable(true)] [Category("Common Properties")] [Description("Gets or sets a value indicating whether the search box is shown.")] [Localizability(LocalizationCategory.None)] public bool IsSearchShown { get { return (bool) GetValue(IsSearchShownProperty); } set { SetValue(IsSearchShownProperty,BooleanBoxes.Box(value)); } } static private void IsSearchShownProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { ManagementList obj = (ManagementList) o; obj.OnIsSearchShownChanged( new PropertyChangedEventArgs<bool>((bool)e.OldValue, (bool)e.NewValue) ); } /// <summary> /// Occurs when IsSearchShown property changes. /// </summary> public event EventHandler<PropertyChangedEventArgs<bool>> IsSearchShownChanged; /// <summary> /// Called when IsSearchShown property changes. /// </summary> protected virtual void OnIsSearchShownChanged(PropertyChangedEventArgs<bool> e) { OnIsSearchShownChangedImplementation(e); RaisePropertyChangedEvent(IsSearchShownChanged, e); } partial void OnIsSearchShownChangedImplementation(PropertyChangedEventArgs<bool> e); // // List dependency property // /// <summary> /// Identifies the List dependency property key. /// </summary> private static readonly DependencyPropertyKey ListPropertyKey = DependencyProperty.RegisterReadOnly( "List", typeof(InnerList), typeof(ManagementList), new PropertyMetadata( null, ListProperty_PropertyChanged) ); /// <summary> /// Identifies the List dependency property. /// </summary> public static readonly DependencyProperty ListProperty = ListPropertyKey.DependencyProperty; /// <summary> /// Gets the list. /// </summary> [Bindable(true)] [Category("Common Properties")] [Description("Gets the list.")] [Localizability(LocalizationCategory.None)] public InnerList List { get { return (InnerList) GetValue(ListProperty); } private set { SetValue(ListPropertyKey,value); } } static private void ListProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { ManagementList obj = (ManagementList) o; obj.OnListChanged( new PropertyChangedEventArgs<InnerList>((InnerList)e.OldValue, (InnerList)e.NewValue) ); } /// <summary> /// Occurs when List property changes. /// </summary> public event EventHandler<PropertyChangedEventArgs<InnerList>> ListChanged; /// <summary> /// Called when List property changes. /// </summary> protected virtual void OnListChanged(PropertyChangedEventArgs<InnerList> e) { OnListChangedImplementation(e); RaisePropertyChangedEvent(ListChanged, e); } partial void OnListChangedImplementation(PropertyChangedEventArgs<InnerList> e); // // SearchBox dependency property // /// <summary> /// Identifies the SearchBox dependency property key. /// </summary> private static readonly DependencyPropertyKey SearchBoxPropertyKey = DependencyProperty.RegisterReadOnly( "SearchBox", typeof(SearchBox), typeof(ManagementList), new PropertyMetadata( null, SearchBoxProperty_PropertyChanged) ); /// <summary> /// Identifies the SearchBox dependency property. /// </summary> public static readonly DependencyProperty SearchBoxProperty = SearchBoxPropertyKey.DependencyProperty; /// <summary> /// Gets the search box. /// </summary> [Bindable(true)] [Category("Common Properties")] [Description("Gets the search box.")] [Localizability(LocalizationCategory.None)] public SearchBox SearchBox { get { return (SearchBox) GetValue(SearchBoxProperty); } private set { SetValue(SearchBoxPropertyKey,value); } } static private void SearchBoxProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { ManagementList obj = (ManagementList) o; obj.OnSearchBoxChanged( new PropertyChangedEventArgs<SearchBox>((SearchBox)e.OldValue, (SearchBox)e.NewValue) ); } /// <summary> /// Occurs when SearchBox property changes. /// </summary> public event EventHandler<PropertyChangedEventArgs<SearchBox>> SearchBoxChanged; /// <summary> /// Called when SearchBox property changes. /// </summary> protected virtual void OnSearchBoxChanged(PropertyChangedEventArgs<SearchBox> e) { OnSearchBoxChangedImplementation(e); RaisePropertyChangedEvent(SearchBoxChanged, e); } partial void OnSearchBoxChangedImplementation(PropertyChangedEventArgs<SearchBox> e); // // ViewManagerUserActionState dependency property // /// <summary> /// Identifies the ViewManagerUserActionState dependency property. /// </summary> public static readonly DependencyProperty ViewManagerUserActionStateProperty = DependencyProperty.Register( "ViewManagerUserActionState", typeof(UserActionState), typeof(ManagementList), new PropertyMetadata( UserActionState.Enabled, ViewManagerUserActionStateProperty_PropertyChanged) ); /// <summary> /// Gets or sets the user interaction state of the view manager. /// </summary> [Bindable(true)] [Category("Common Properties")] [Description("Gets or sets the user interaction state of the view manager.")] [Localizability(LocalizationCategory.None)] public UserActionState ViewManagerUserActionState { get { return (UserActionState) GetValue(ViewManagerUserActionStateProperty); } set { SetValue(ViewManagerUserActionStateProperty,value); } } static private void ViewManagerUserActionStateProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { ManagementList obj = (ManagementList) o; obj.OnViewManagerUserActionStateChanged( new PropertyChangedEventArgs<UserActionState>((UserActionState)e.OldValue, (UserActionState)e.NewValue) ); } /// <summary> /// Occurs when ViewManagerUserActionState property changes. /// </summary> public event EventHandler<PropertyChangedEventArgs<UserActionState>> ViewManagerUserActionStateChanged; /// <summary> /// Called when ViewManagerUserActionState property changes. /// </summary> protected virtual void OnViewManagerUserActionStateChanged(PropertyChangedEventArgs<UserActionState> e) { OnViewManagerUserActionStateChangedImplementation(e); RaisePropertyChangedEvent(ViewManagerUserActionStateChanged, e); } partial void OnViewManagerUserActionStateChangedImplementation(PropertyChangedEventArgs<UserActionState> e); // // ViewSaverUserActionState dependency property // /// <summary> /// Identifies the ViewSaverUserActionState dependency property. /// </summary> public static readonly DependencyProperty ViewSaverUserActionStateProperty = DependencyProperty.Register( "ViewSaverUserActionState", typeof(UserActionState), typeof(ManagementList), new PropertyMetadata( UserActionState.Enabled, ViewSaverUserActionStateProperty_PropertyChanged) ); /// <summary> /// Gets or sets the user interaction state of the view saver. /// </summary> [Bindable(true)] [Category("Common Properties")] [Description("Gets or sets the user interaction state of the view saver.")] [Localizability(LocalizationCategory.None)] public UserActionState ViewSaverUserActionState { get { return (UserActionState) GetValue(ViewSaverUserActionStateProperty); } set { SetValue(ViewSaverUserActionStateProperty,value); } } static private void ViewSaverUserActionStateProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { ManagementList obj = (ManagementList) o; obj.OnViewSaverUserActionStateChanged( new PropertyChangedEventArgs<UserActionState>((UserActionState)e.OldValue, (UserActionState)e.NewValue) ); } /// <summary> /// Occurs when ViewSaverUserActionState property changes. /// </summary> public event EventHandler<PropertyChangedEventArgs<UserActionState>> ViewSaverUserActionStateChanged; /// <summary> /// Called when ViewSaverUserActionState property changes. /// </summary> protected virtual void OnViewSaverUserActionStateChanged(PropertyChangedEventArgs<UserActionState> e) { OnViewSaverUserActionStateChangedImplementation(e); RaisePropertyChangedEvent(ViewSaverUserActionStateChanged, e); } partial void OnViewSaverUserActionStateChangedImplementation(PropertyChangedEventArgs<UserActionState> e); /// <summary> /// Called when a property changes. /// </summary> private void RaisePropertyChangedEvent<T>(EventHandler<PropertyChangedEventArgs<T>> eh, PropertyChangedEventArgs<T> e) { if(eh != null) { eh(this,e); } } // // OnApplyTemplate // /// <summary> /// Called when ApplyTemplate is called. /// </summary> public override void OnApplyTemplate() { PreOnApplyTemplate(); base.OnApplyTemplate(); this.viewManager = WpfHelp.GetTemplateChild<ListOrganizer>(this,"PART_ViewManager"); this.viewSaver = WpfHelp.GetTemplateChild<PickerBase>(this,"PART_ViewSaver"); PostOnApplyTemplate(); } partial void PreOnApplyTemplate(); partial void PostOnApplyTemplate(); // // Static constructor // /// <summary> /// Called when the type is initialized. /// </summary> static ManagementList() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ManagementList), new FrameworkPropertyMetadata(typeof(ManagementList))); CommandManager.RegisterClassCommandBinding( typeof(ManagementList), new CommandBinding( ManagementList.ClearFilterCommand, ClearFilterCommand_CommandExecuted, ClearFilterCommand_CommandCanExecute )); CommandManager.RegisterClassCommandBinding( typeof(ManagementList), new CommandBinding( ManagementList.SaveViewCommand, SaveViewCommand_CommandExecuted, SaveViewCommand_CommandCanExecute )); CommandManager.RegisterClassCommandBinding( typeof(ManagementList), new CommandBinding( ManagementList.StartFilterCommand, StartFilterCommand_CommandExecuted, StartFilterCommand_CommandCanExecute )); CommandManager.RegisterClassCommandBinding( typeof(ManagementList), new CommandBinding( ManagementList.StopFilterCommand, StopFilterCommand_CommandExecuted, StopFilterCommand_CommandCanExecute )); StaticConstructorImplementation(); } static partial void StaticConstructorImplementation(); // // CreateAutomationPeer // /// <summary> /// Create an instance of the AutomationPeer. /// </summary> /// <returns> /// An instance of the AutomationPeer. /// </returns> protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer() { return new ExtendedFrameworkElementAutomationPeer(this,AutomationControlType.Pane); } } } #endregion
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines { /// <summary> /// CA1707: Identifiers should not contain underscores /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class IdentifiersShouldNotContainUnderscoresAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA1707"; private static readonly IImmutableSet<string> s_GlobalAsaxSpecialMethodNames = ImmutableHashSet.Create( "Application_AuthenticateRequest", "Application_BeginRequest", "Application_End", "Application_EndRequest", "Application_Error", "Application_Init", "Application_Start", "Session_End", "Session_Start"); private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresTitle), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_localizableMessageAssembly = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageAssembly), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_localizableMessageNamespace = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageNamespace), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_localizableMessageType = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageType), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_localizableMessageMember = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageMember), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_localizableMessageTypeTypeParameter = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageTypeTypeParameter), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_localizableMessageMethodTypeParameter = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageMethodTypeParameter), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_localizableMessageMemberParameter = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageMemberParameter), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_localizableMessageDelegateParameter = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresMessageDelegateParameter), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotContainUnderscoresDescription), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); internal static DiagnosticDescriptor AssemblyRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageAssembly, DiagnosticCategory.Naming, RuleLevel.IdeHidden_BulkConfigurable, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static DiagnosticDescriptor NamespaceRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageNamespace, DiagnosticCategory.Naming, RuleLevel.IdeHidden_BulkConfigurable, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static DiagnosticDescriptor TypeRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageType, DiagnosticCategory.Naming, RuleLevel.IdeHidden_BulkConfigurable, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static DiagnosticDescriptor MemberRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageMember, DiagnosticCategory.Naming, RuleLevel.IdeHidden_BulkConfigurable, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static DiagnosticDescriptor TypeTypeParameterRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageTypeTypeParameter, DiagnosticCategory.Naming, RuleLevel.IdeHidden_BulkConfigurable, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static DiagnosticDescriptor MethodTypeParameterRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageMethodTypeParameter, DiagnosticCategory.Naming, RuleLevel.IdeHidden_BulkConfigurable, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static DiagnosticDescriptor MemberParameterRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageMemberParameter, DiagnosticCategory.Naming, RuleLevel.IdeHidden_BulkConfigurable, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static DiagnosticDescriptor DelegateParameterRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageDelegateParameter, DiagnosticCategory.Naming, RuleLevel.IdeHidden_BulkConfigurable, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(AssemblyRule, NamespaceRule, TypeRule, MemberRule, TypeTypeParameterRule, MethodTypeParameterRule, MemberParameterRule, DelegateParameterRule); public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.RegisterSymbolAction(symbolAnalysisContext => { var symbol = symbolAnalysisContext.Symbol; // FxCop compat: only analyze externally visible symbols by default // Note all the descriptors/rules for this analyzer have the same ID and category and hence // will always have identical configured visibility. if (!symbolAnalysisContext.Options.MatchesConfiguredVisibility(AssemblyRule, symbol, symbolAnalysisContext.Compilation, symbolAnalysisContext.CancellationToken)) { return; } switch (symbol.Kind) { case SymbolKind.Namespace: { if (ContainsUnderScore(symbol.Name)) { symbolAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(NamespaceRule, symbol.ToDisplayString())); } return; } case SymbolKind.NamedType: { var namedType = (INamedTypeSymbol)symbol; AnalyzeTypeParameters(symbolAnalysisContext, namedType.TypeParameters); if (namedType.TypeKind == TypeKind.Delegate && namedType.DelegateInvokeMethod != null) { AnalyzeParameters(symbolAnalysisContext, namedType.DelegateInvokeMethod.Parameters); } if (!ContainsUnderScore(symbol.Name)) { return; } symbolAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(TypeRule, symbol.ToDisplayString())); return; } case SymbolKind.Field: { var fieldSymbol = (IFieldSymbol)symbol; if (ContainsUnderScore(symbol.Name) && (fieldSymbol.IsConst || (fieldSymbol.IsStatic && fieldSymbol.IsReadOnly))) { symbolAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(MemberRule, symbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat))); return; } return; } default: { if (symbol is IMethodSymbol methodSymbol) { if (methodSymbol.IsOperator()) { // Do not flag for operators. return; } if (methodSymbol.MethodKind == MethodKind.Conversion) { // Do not flag for conversion methods generated for operators. return; } AnalyzeParameters(symbolAnalysisContext, methodSymbol.Parameters); AnalyzeTypeParameters(symbolAnalysisContext, methodSymbol.TypeParameters); if (s_GlobalAsaxSpecialMethodNames.Contains(methodSymbol.Name) && methodSymbol.ContainingType.Inherits(symbolAnalysisContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemWebHttpApplication))) { // Do not flag the convention based web methods. return; } } if (symbol is IPropertySymbol propertySymbol) { AnalyzeParameters(symbolAnalysisContext, propertySymbol.Parameters); } if (!ContainsUnderScore(symbol.Name) || IsInvalidSymbol(symbol, symbolAnalysisContext)) { return; } symbolAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(MemberRule, symbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat))); return; } } }, SymbolKind.Namespace, // Namespace SymbolKind.NamedType, //Type SymbolKind.Method, SymbolKind.Property, SymbolKind.Field, SymbolKind.Event // Members ); context.RegisterCompilationAction(compilationAnalysisContext => { var compilation = compilationAnalysisContext.Compilation; if (ContainsUnderScore(compilation.AssemblyName)) { compilationAnalysisContext.ReportDiagnostic(compilation.Assembly.CreateDiagnostic(AssemblyRule, compilation.AssemblyName)); } }); } private static bool IsInvalidSymbol(ISymbol symbol, SymbolAnalysisContext context) { // Note all the descriptors/rules for this analyzer have the same ID and category and hence // will always have identical configured visibility. var matchesConfiguration = context.Options.MatchesConfiguredVisibility(AssemblyRule, symbol, context.Compilation, context.CancellationToken); return (!(matchesConfiguration && !symbol.IsOverride)) || symbol.IsAccessorMethod() || symbol.IsImplementationOfAnyInterfaceMember(); } private static void AnalyzeParameters(SymbolAnalysisContext symbolAnalysisContext, IEnumerable<IParameterSymbol> parameters) { foreach (var parameter in parameters) { if (ContainsUnderScore(parameter.Name) && !parameter.IsSymbolWithSpecialDiscardName()) { var containingType = parameter.ContainingType; // Parameter in Delegate if (containingType.TypeKind == TypeKind.Delegate) { if (containingType.IsPublic()) { symbolAnalysisContext.ReportDiagnostic(parameter.CreateDiagnostic(DelegateParameterRule, containingType.ToDisplayString(), parameter.Name)); } } else if (!IsInvalidSymbol(parameter.ContainingSymbol, symbolAnalysisContext)) { symbolAnalysisContext.ReportDiagnostic(parameter.CreateDiagnostic(MemberParameterRule, parameter.ContainingSymbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat), parameter.Name)); } } } } private static void AnalyzeTypeParameters(SymbolAnalysisContext symbolAnalysisContext, IEnumerable<ITypeParameterSymbol> typeParameters) { foreach (var typeParameter in typeParameters) { if (ContainsUnderScore(typeParameter.Name)) { var containingSymbol = typeParameter.ContainingSymbol; if (containingSymbol.Kind == SymbolKind.NamedType) { if (containingSymbol.IsPublic()) { symbolAnalysisContext.ReportDiagnostic(typeParameter.CreateDiagnostic(TypeTypeParameterRule, containingSymbol.ToDisplayString(), typeParameter.Name)); } } else if (containingSymbol.Kind == SymbolKind.Method && !IsInvalidSymbol(containingSymbol, symbolAnalysisContext)) { symbolAnalysisContext.ReportDiagnostic(typeParameter.CreateDiagnostic(MethodTypeParameterRule, containingSymbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat), typeParameter.Name)); } } } } private static bool ContainsUnderScore(string identifier) { return identifier.IndexOf('_') != -1; } } }
// // Mono.System.Xml.Schema.XmlSchemaAll.cs // // Author: // Dwivedi, Ajay kumar Adwiv@Yahoo.com // Atsushi Enomoto ginga@kit.hi-ho.ne.jp // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using Mono.System.Xml; using Mono.System.Xml.Serialization; namespace Mono.System.Xml.Schema { /// <summary> /// Summary description for XmlSchemaAll. /// </summary> public class XmlSchemaAll : XmlSchemaGroupBase { private XmlSchema schema; private XmlSchemaObjectCollection items; const string xmlname = "all"; private bool emptiable; public XmlSchemaAll() { items = new XmlSchemaObjectCollection(); } [XmlElement("element",typeof(XmlSchemaElement))] public override XmlSchemaObjectCollection Items { get{ return items; } } internal bool Emptiable { get { return emptiable; } } internal override void SetParent (XmlSchemaObject parent) { base.SetParent (parent); foreach (XmlSchemaObject obj in Items) obj.SetParent (this); } /// <remarks> /// 1. MaxOccurs must be one. (default is also one) /// 2. MinOccurs must be zero or one. /// </remarks> internal override int Compile(ValidationEventHandler h, XmlSchema schema) { // If this is already compiled this time, simply skip. if (CompilationId == schema.CompilationId) return 0; this.schema = schema; if(MaxOccurs != Decimal.One) error(h,"maxOccurs must be 1"); if(MinOccurs != Decimal.One && MinOccurs != Decimal.Zero) error(h,"minOccurs must be 0 or 1"); XmlSchemaUtil.CompileID(Id, this, schema.IDCollection, h); CompileOccurence (h, schema); foreach(XmlSchemaObject obj in Items) { XmlSchemaElement elem = obj as XmlSchemaElement; if(elem != null) { if(elem.ValidatedMaxOccurs != Decimal.One && elem.ValidatedMaxOccurs != Decimal.Zero) { elem.error (h,"The {max occurs} of all the elements of 'all' must be 0 or 1. "); } errorCount += elem.Compile(h, schema); } else { error(h,"XmlSchemaAll can only contain Items of type Element"); } } this.CompilationId = schema.CompilationId; return errorCount; } internal override XmlSchemaParticle GetOptimizedParticle (bool isTop) { if (OptimizedParticle != null) return OptimizedParticle; if (Items.Count == 0 || ValidatedMaxOccurs == 0) { OptimizedParticle = XmlSchemaParticle.Empty; return OptimizedParticle; } else if (Items.Count == 1) { if (ValidatedMinOccurs == 1 && ValidatedMaxOccurs == 1) { XmlSchemaSequence seq = new XmlSchemaSequence (); this.CopyInfo (seq); XmlSchemaParticle p = (XmlSchemaParticle) Items [0]; p = p.GetOptimizedParticle (false); if (p == XmlSchemaParticle.Empty) OptimizedParticle = p; else { seq.Items.Add (p); seq.CompiledItems.Add (p); seq.Compile (null, schema); OptimizedParticle = seq; } return OptimizedParticle; } } XmlSchemaAll all = new XmlSchemaAll (); CopyInfo (all); CopyOptimizedItems (all); OptimizedParticle = all; all.ComputeEmptiable (); return OptimizedParticle; } internal override int Validate(ValidationEventHandler h, XmlSchema schema) { if (IsValidated (schema.CompilationId)) return errorCount; // 3.8.6 All Group Limited :: 1. // Beware that this section was corrected: E1-26 of http://www.w3.org/2001/05/xmlschema-errata#Errata1 if (!this.parentIsGroupDefinition && ValidatedMaxOccurs != 1) error (h, "-all- group is limited to be content of a model group, or that of a complex type with maxOccurs to be 1."); CompiledItems.Clear (); foreach (XmlSchemaParticle obj in Items) { errorCount += obj.Validate (h, schema); if (obj.ValidatedMaxOccurs != 0 && obj.ValidatedMaxOccurs != 1) error (h, "MaxOccurs of a particle inside -all- compositor must be either 0 or 1."); CompiledItems.Add (obj); } ComputeEmptiable (); ValidationId = schema.ValidationId; return errorCount; } private void ComputeEmptiable () { emptiable = true; for (int i = 0; i < Items.Count; i++) { if (((XmlSchemaParticle) Items [i]).ValidatedMinOccurs > 0) { emptiable = false; break; } } } internal override bool ValidateDerivationByRestriction (XmlSchemaParticle baseParticle, ValidationEventHandler h, XmlSchema schema, bool raiseError) { XmlSchemaAny any = baseParticle as XmlSchemaAny; XmlSchemaAll derivedAll = baseParticle as XmlSchemaAll; if (any != null) { // NSRecurseCheckCardinality return ValidateNSRecurseCheckCardinality (any, h, schema, raiseError); } else if (derivedAll != null) { // Recurse if (!ValidateOccurenceRangeOK (derivedAll, h, schema, raiseError)) return false; return ValidateRecurse (derivedAll, h, schema, raiseError); } else { if (raiseError) error (h, "Invalid -all- particle derivation was found."); return false; } } internal override decimal GetMinEffectiveTotalRange () { return GetMinEffectiveTotalRangeAllAndSequence (); } internal override void ValidateUniqueParticleAttribution (XmlSchemaObjectTable qnames, ArrayList nsNames, ValidationEventHandler h, XmlSchema schema) { foreach (XmlSchemaElement el in this.Items) el.ValidateUniqueParticleAttribution (qnames, nsNames, h, schema); } internal override void ValidateUniqueTypeAttribution (XmlSchemaObjectTable labels, ValidationEventHandler h, XmlSchema schema) { foreach (XmlSchemaElement el in this.Items) el.ValidateUniqueTypeAttribution (labels, h, schema); } //<all // id = ID // maxOccurs = 1 : 1 // minOccurs = (0 | 1) : 1 // {any attributes with non-schema namespace . . .}> // Content: (annotation?, element*) //</all> internal static XmlSchemaAll Read(XmlSchemaReader reader, ValidationEventHandler h) { XmlSchemaAll all = new XmlSchemaAll(); reader.MoveToElement(); if(reader.NamespaceURI != XmlSchema.Namespace || reader.LocalName != xmlname) { error(h,"Should not happen :1: XmlSchemaAll.Read, name="+reader.Name,null); reader.SkipToEnd(); return null; } all.LineNumber = reader.LineNumber; all.LinePosition = reader.LinePosition; all.SourceUri = reader.BaseURI; //Read Attributes while(reader.MoveToNextAttribute()) { if(reader.Name == "id") { all.Id = reader.Value; } else if(reader.Name == "maxOccurs") { try { all.MaxOccursString = reader.Value; } catch(Exception e) { error(h,reader.Value + " is an invalid value for maxOccurs",e); } } else if(reader.Name == "minOccurs") { try { all.MinOccursString = reader.Value; } catch(Exception e) { error(h,reader.Value + " is an invalid value for minOccurs",e); } } else if((reader.NamespaceURI == "" && reader.Name != "xmlns") || reader.NamespaceURI == XmlSchema.Namespace) { error(h,reader.Name + " is not a valid attribute for all",null); } else { XmlSchemaUtil.ReadUnhandledAttribute(reader,all); } } reader.MoveToElement(); if(reader.IsEmptyElement) return all; //Content: (annotation?, element*) int level = 1; while(reader.ReadNextElement()) { if(reader.NodeType == XmlNodeType.EndElement) { if(reader.LocalName != xmlname) error(h,"Should not happen :2: XmlSchemaAll.Read, name="+reader.Name,null); break; } if(level <= 1 && reader.LocalName == "annotation") { level = 2; //Only one annotation XmlSchemaAnnotation annotation = XmlSchemaAnnotation.Read(reader,h); if(annotation != null) all.Annotation = annotation; continue; } if(level <=2 && reader.LocalName == "element") { level = 2; XmlSchemaElement element = XmlSchemaElement.Read(reader,h); if(element != null) all.items.Add(element); continue; } reader.RaiseInvalidElementError(); } return all; } } }
// 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. /*============================================================ ** ** ** ** Purpose: This class will encapsulate an uint and ** provide an Object representation of it. ** ** ===========================================================*/ using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace System { [Serializable] [CLSCompliant(false)] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct UInt32 : IComparable, IConvertible, IFormattable, IComparable<UInt32>, IEquatable<UInt32> { private uint m_value; // Do not rename (binary serialization) public const uint MaxValue = (uint)0xffffffff; public const uint MinValue = 0U; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type UInt32, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is UInt32) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. uint i = (uint)value; if (m_value < i) return -1; if (m_value > i) return 1; return 0; } throw new ArgumentException(SR.Arg_MustBeUInt32); } public int CompareTo(UInt32 value) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. if (m_value < value) return -1; if (m_value > value) return 1; return 0; } public override bool Equals(Object obj) { if (!(obj is UInt32)) { return false; } return m_value == ((UInt32)obj).m_value; } [NonVersionable] public bool Equals(UInt32 obj) { return m_value == obj; } // The absolute value of the int contained. public override int GetHashCode() { return ((int)m_value); } // The base 10 representation of the number with no extra padding. public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatUInt32(m_value, null, NumberFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatUInt32(m_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatUInt32(m_value, format, NumberFormatInfo.CurrentInfo); } public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatUInt32(m_value, format, NumberFormatInfo.GetInstance(provider)); } [CLSCompliant(false)] public static uint Parse(String s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseUInt32(s.AsSpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } [CLSCompliant(false)] public static uint Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseUInt32(s.AsSpan(), style, NumberFormatInfo.CurrentInfo); } [CLSCompliant(false)] public static uint Parse(String s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseUInt32(s.AsSpan(), NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } [CLSCompliant(false)] public static uint Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseUInt32(s.AsSpan(), style, NumberFormatInfo.GetInstance(provider)); } [CLSCompliant(false)] public static uint Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.ParseUInt32(s, style, NumberFormatInfo.GetInstance(provider)); } [CLSCompliant(false)] public static bool TryParse(String s, out UInt32 result) { if (s == null) { result = 0; return false; } return Number.TryParseUInt32(s.AsSpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } [CLSCompliant(false)] public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt32 result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return Number.TryParseUInt32(s.AsSpan(), style, NumberFormatInfo.GetInstance(provider), out result); } [CLSCompliant(false)] public static bool TryParse(ReadOnlySpan<char> s, out UInt32 result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.TryParseUInt32(s, style, NumberFormatInfo.GetInstance(provider), out result); } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.UInt32; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(m_value); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return m_value; } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "UInt32", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections.Generic; using System.Reflection; using System.Threading; namespace OpenSim.Region.CoreModules.Avatar.Groups { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "GroupsModule")] public class GroupsModule : ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private ThreadedClasses.RwLockedDictionary<UUID, GroupMembershipData> m_GroupMap = new ThreadedClasses.RwLockedDictionary<UUID, GroupMembershipData>(); private ThreadedClasses.RwLockedDictionary<UUID, IClientAPI> m_ClientMap = new ThreadedClasses.RwLockedDictionary<UUID, IClientAPI>(); private UUID opensimulatorGroupID = new UUID("00000000-68f9-1111-024e-222222111123"); private ThreadedClasses.RwLockedList<Scene> m_SceneList = new ThreadedClasses.RwLockedList<Scene>(); private static GroupMembershipData osGroup = new GroupMembershipData(); private bool m_Enabled = false; #region ISharedRegionModule Members public void Initialise(IConfigSource config) { IConfig groupsConfig = config.Configs["Groups"]; if (groupsConfig == null) { m_log.Info("[GROUPS]: No configuration found. Using defaults"); } else { m_Enabled = groupsConfig.GetBoolean("Enabled", false); if (!m_Enabled) { m_log.Info("[GROUPS]: Groups disabled in configuration"); return; } if (groupsConfig.GetString("Module", "Default") != "Default") { m_Enabled = false; return; } } osGroup.GroupID = opensimulatorGroupID; osGroup.GroupName = "OpenSimulator Testing"; osGroup.GroupPowers = (uint)(GroupPowers.AllowLandmark | GroupPowers.AllowSetHome); m_GroupMap[opensimulatorGroupID] = osGroup; } public void AddRegion(Scene scene) { if (!m_Enabled) return; m_SceneList.Add(scene); scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnClientClosed += OnClientClosed; // scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; } public void RemoveRegion(Scene scene) { if (!m_Enabled) return; m_SceneList.Remove(scene); scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnClientClosed -= OnClientClosed; } public void RegionLoaded(Scene scene) { } public void PostInitialise() { } public void Close() { if (!m_Enabled) return; // m_log.Debug("[GROUPS]: Shutting down group module."); m_ClientMap.Clear(); m_GroupMap.Clear(); } public string Name { get { return "GroupsModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion private void OnNewClient(IClientAPI client) { // Subscribe to instant messages // client.OnInstantMessage += OnInstantMessage; client.OnAgentDataUpdateRequest += OnAgentDataUpdateRequest; client.OnUUIDGroupNameRequest += HandleUUIDGroupNameRequest; m_ClientMap[client.AgentId] = client; GroupMembershipData[] updateGroups = new GroupMembershipData[1]; updateGroups[0] = osGroup; client.SendGroupMembership(updateGroups); } private void OnAgentDataUpdateRequest(IClientAPI remoteClient, UUID AgentID, UUID SessionID) { UUID ActiveGroupID; string ActiveGroupName; ulong ActiveGroupPowers; string firstname = remoteClient.FirstName; string lastname = remoteClient.LastName; string ActiveGroupTitle = "I IZ N0T"; ActiveGroupID = osGroup.GroupID; ActiveGroupName = osGroup.GroupName; ActiveGroupPowers = osGroup.GroupPowers; remoteClient.SendAgentDataUpdate(AgentID, ActiveGroupID, firstname, lastname, ActiveGroupPowers, ActiveGroupName, ActiveGroupTitle); } // private void OnInstantMessage(IClientAPI client, GridInstantMessage im) // { // } // private void OnGridInstantMessage(GridInstantMessage msg) // { // // Trigger the above event handler // OnInstantMessage(null, msg); // } private void HandleUUIDGroupNameRequest(UUID id,IClientAPI remote_client) { string groupnamereply = "Unknown"; UUID groupUUID = UUID.Zero; GroupMembershipData grp; if(m_GroupMap.TryGetValue(id, out grp)) { groupnamereply = grp.GroupName; groupUUID = grp.GroupID; } remote_client.SendGroupNameReply(groupUUID, groupnamereply); } private void OnClientClosed(UUID agentID, Scene scene) { m_ClientMap.Remove(agentID); } } }
#region MIT License /* * Copyright (c) 2005-2008 Jonathan Mark Porter. http://physics2d.googlepages.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. */ #endregion #if UseDouble using Scalar = System.Double; #else using Scalar = System.Single; #endif using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using AdvanceMath; using AdvanceMath.Geometry2D; using Physics2DDotNet; using Physics2DDotNet.Joints; using Physics2DDotNet.PhysicsLogics; using Physics2DDotNet.Collections; using Tao.OpenGl; namespace Graphics2DDotNet { public class Graphic : Pendable<Scene>, IDuplicateable<Graphic> { public event EventHandler<CollectionEventArgs<Graphic>> ChildrenAdded { add { children.ItemsAdded += value; } remove { children.ItemsAdded -= value; } } public event EventHandler<CollectionEventArgs<Graphic>> ChildrenRemoved { add { children.ItemsRemoved += value; } remove { children.ItemsRemoved -= value; } } object syncRoot; PendableCollection<Scene, Graphic> children; List<Graphic> preChildren = new List<Graphic>(); Scalar[] matrixArray; IDrawable drawable; IAnimation animation; IDrawableState drawableState; List<IDrawProperty> drawProperties; bool isVisible; Graphic pendingGraphicParent; Graphic graphicParent; bool hasChildren; private bool doAnimation; bool isLifetimeOwner; public Graphic(IDrawable drawable, Matrix2x3 matrix, Lifespan lifetime) : base(lifetime) { if (drawable == null) { throw new ArgumentNullException("drawable"); } this.drawProperties = new List<IDrawProperty>(); this.drawable = drawable; this.drawableState = drawable.CreateState(); this.isVisible = true; this.matrixArray = new Scalar[16]; Matrix2x3.Copy2DToOpenGlMatrix(ref matrix, this.matrixArray); this.syncRoot = new object(); this.preChildren = new List<Graphic>(); this.isLifetimeOwner = true; } protected Graphic(Graphic copy) : base(copy) { this.drawProperties = new List<IDrawProperty>(copy.drawProperties); this.drawable = copy.drawable; this.drawableState = drawable.CreateState(); this.matrixArray = (Scalar[])copy.matrixArray.Clone(); this.isVisible = copy.isVisible; this.syncRoot = new object(); this.preChildren = new List<Graphic>(copy.preChildren); this.isLifetimeOwner = copy.isLifetimeOwner; } public ReadOnlyThreadSafeCollection<Graphic> Children { get { return new ReadOnlyThreadSafeCollection<Graphic>(Parent.rwLock, children.Items); } } public bool IsLifetimeOwner { get { return isLifetimeOwner; } set { isLifetimeOwner = value; } } public Graphic GraphicParent { get { return graphicParent; } } public bool IsVisible { get { return isVisible; } set { isVisible = value; } } public Matrix2x3 Matrix { get { Matrix2x3 result; Matrix2x3.Copy2DFromOpenGlMatrix(matrixArray, out result); return result; } set { Matrix2x3.Copy2DToOpenGlMatrix(ref value, matrixArray); } } public List<IDrawProperty> DrawProperties { get { return drawProperties; } } public Scalar[] MatrixArray { get { return matrixArray; } } public IDrawableState DrawableState { get { return drawableState; } set { drawableState = value; } } public IDrawable Drawable { get { return drawable; } set { if (value == null) { throw new ArgumentNullException("value"); } this.drawable = value; this.drawableState = value.CreateState(); if (Parent != null && drawableState != null) { drawableState.OnPending(this); } } } public IAnimation Animation { get { return animation; } set { animation = value; } } private void PreDraw(DrawInfo drawInfo) { ApplyProperties(); doAnimation = false; if (animation != null) { if (animation.LifeTime.IsExpired) { animation = null; } else { doAnimation = true; animation.Apply(this, drawInfo); animation.LifeTime.Update(drawInfo.Dt, drawInfo.DrawCount); } } } private void PostDraw(DrawInfo drawInfo) { if (doAnimation) { animation.Remove(this, drawInfo); } RemoveProperties(); } private void DrawWithChildren(DrawInfo drawInfo) { children.RemoveExpired(); lock (syncRoot) { children.AddPending(); } children.CheckZOrder(); hasChildren = children.Items.Count > 0; PreDraw(drawInfo); int index = 0; List<Graphic> children2 = children.Items; for (; index < children2.Count && children2[index].ZOrder < this.ZOrder; ++index) { Gl.glPushMatrix(); children2[index].Draw(drawInfo); Gl.glPopMatrix(); } drawable.Draw(drawInfo, drawableState); for (; index < children2.Count; ++index) { Gl.glPushMatrix(); children2[index].Draw(drawInfo); Gl.glPopMatrix(); } PostDraw(drawInfo); } private void DrawWithoutChildren(DrawInfo drawInfo) { PreDraw(drawInfo); drawable.Draw(drawInfo, drawableState); PostDraw(drawInfo); } public virtual void Draw(DrawInfo drawInfo) { UpdateTime(drawInfo); if (graphicParent == null) { GlHelper.GlLoadMatrix(matrixArray); } else { GlHelper.GlMultMatrix(matrixArray); } if (hasChildren) { DrawWithChildren(drawInfo); } else { DrawWithoutChildren(drawInfo); } } private void ApplyProperties() { for (int index = 0; index < drawProperties.Count; ++index) { drawProperties[index].Apply(); } } private void RemoveProperties() { for (int index = 0; index < drawProperties.Count; ++index) { drawProperties[index].Remove(); } } protected void UpdateTime(DrawInfo drawInfo) { if (isLifetimeOwner) { this.Lifetime.Update(drawInfo.Dt, drawInfo.DrawCount); } } public virtual Graphic Duplicate() { return new Graphic(this); } public object Clone() { return Duplicate(); } public void AddChild(Graphic item) { hasChildren = true; lock (syncRoot) { if (children == null) { preChildren.Add(item); } else { children.Add(item); item.graphicParent = this; } } } public void AddChildRange(ICollection<Graphic> collection) { hasChildren = true; lock (syncRoot) { if (children == null) { preChildren.AddRange(collection); } else { foreach (Graphic item in collection) { item.pendingGraphicParent = this; } children.AddRange(collection); } } } protected override void OnPending(EventArgs e) { this.graphicParent = pendingGraphicParent; if (drawableState != null) { drawableState.OnPending(this); } base.OnPending(e); } protected override void OnAdded(EventArgs e) { lock (syncRoot) { this.children = new PendableCollection<Scene, Graphic>(Parent, this); foreach (Graphic item in preChildren) { item.pendingGraphicParent = this; } this.children.AddRange(preChildren); preChildren.Clear(); } base.OnAdded(e); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Buffers; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.WebUtilities; using Moq; using Xunit; namespace Microsoft.AspNetCore.Mvc.Formatters.Xml { public class XmlDataContractSerializerInputFormatterTest { [DataContract(Name = "DummyClass", Namespace = "")] public class DummyClass { [DataMember] public int SampleInt { get; set; } } [DataContract(Name = "SomeDummyClass", Namespace = "")] public class SomeDummyClass : DummyClass { [DataMember] public string SampleString { get; set; } } [DataContract(Name = "TestLevelOne", Namespace = "")] public class TestLevelOne { [DataMember] public int SampleInt { get; set; } [DataMember] public string sampleString; public DateTime SampleDate { get; set; } } [DataContract(Name = "TestLevelTwo", Namespace = "")] public class TestLevelTwo { [DataMember] public string SampleString { get; set; } [DataMember] public TestLevelOne TestOne { get; set; } } [Theory] [InlineData("application/xml", true)] [InlineData("application/*", false)] [InlineData("*/*", false)] [InlineData("text/xml", true)] [InlineData("text/*", false)] [InlineData("text/json", false)] [InlineData("application/json", false)] [InlineData("application/some.entity+xml", true)] [InlineData("application/some.entity+xml;v=2", true)] [InlineData("application/some.entity+json", false)] [InlineData("application/some.entity+*", false)] [InlineData("text/some.entity+json", false)] [InlineData("", false)] [InlineData(null, false)] [InlineData("invalid", false)] public void CanRead_ReturnsTrueForAnySupportedContentType(string requestContentType, bool expectedCanRead) { // Arrange var formatter = new XmlDataContractSerializerInputFormatter(new MvcOptions()); var contentBytes = Encoding.UTF8.GetBytes("content"); var modelState = new ModelStateDictionary(); var httpContext = GetHttpContext(contentBytes, contentType: requestContentType); var provider = new EmptyModelMetadataProvider(); var metadata = provider.GetMetadataForType(typeof(string)); var formatterContext = new InputFormatterContext( httpContext, modelName: string.Empty, modelState: modelState, metadata: metadata, readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader); // Act var result = formatter.CanRead(formatterContext); // Assert Assert.Equal(expectedCanRead, result); } [Fact] public void XmlDataContractSerializer_CachesSerializerForType() { // Arrange var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<DummyClass><SampleInt>10</SampleInt></DummyClass>"; var formatter = new TestXmlDataContractSerializerInputFormatter(); var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(DummyClass)); // Act formatter.CanRead(context); formatter.CanRead(context); // Assert Assert.Equal(1, formatter.createSerializerCalledCount); } [Fact] public void HasProperSupportedMediaTypes() { // Arrange & Act var formatter = new XmlDataContractSerializerInputFormatter(new MvcOptions()); // Assert Assert.Contains("application/xml", formatter.SupportedMediaTypes .Select(content => content.ToString())); Assert.Contains("text/xml", formatter.SupportedMediaTypes .Select(content => content.ToString())); } [Fact] public void HasProperSupportedEncodings() { // Arrange & Act var formatter = new XmlDataContractSerializerInputFormatter(new MvcOptions()); // Assert Assert.Contains(formatter.SupportedEncodings, i => i.WebName == "utf-8"); Assert.Contains(formatter.SupportedEncodings, i => i.WebName == "utf-16"); } [Fact] public async Task BuffersRequestBody_ByDefault() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString></TestLevelOne>"; var formatter = new XmlDataContractSerializerInputFormatter(new MvcOptions()); var contentBytes = Encoding.UTF8.GetBytes(input); var httpContext = new DefaultHttpContext(); httpContext.Features.Set<IHttpResponseFeature>(new TestResponseFeature()); httpContext.Request.Body = new NonSeekableReadStream(contentBytes, allowSyncReads: true); httpContext.Request.ContentType = "application/json"; var context = GetInputFormatterContext(httpContext, typeof(TestLevelOne)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<TestLevelOne>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.sampleString); } [Fact] public async Task ReadAsync_DoesNotDisposeBufferedStreamIfItDidNotCreateIt() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString></TestLevelOne>"; var formatter = new XmlDataContractSerializerInputFormatter(new MvcOptions()); var contentBytes = Encoding.UTF8.GetBytes(input); var httpContext = new DefaultHttpContext(); var testBufferedReadStream = new VerifyDisposeFileBufferingReadStream(new MemoryStream(contentBytes), 1024); httpContext.Request.Body = testBufferedReadStream; var context = GetInputFormatterContext(httpContext, typeof(TestLevelOne)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<TestLevelOne>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.sampleString); Assert.False(testBufferedReadStream.Disposed); } [Fact] public async Task SuppressInputFormatterBufferingSetToTrue_DoesNotBufferRequestBody() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString></TestLevelOne>"; var formatter = new XmlDataContractSerializerInputFormatter(new MvcOptions { SuppressInputFormatterBuffering = true }); var contentBytes = Encoding.UTF8.GetBytes(input); var httpContext = new DefaultHttpContext(); httpContext.Features.Set<IHttpResponseFeature>(new TestResponseFeature()); httpContext.Request.Body = new NonSeekableReadStream(contentBytes); httpContext.Request.ContentType = "application/xml"; var context = GetInputFormatterContext(httpContext, typeof(TestLevelOne)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<TestLevelOne>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.sampleString); // Reading again should fail as buffering request body is disabled await Assert.ThrowsAsync<XmlException>(() => formatter.ReadAsync(context)); } [Fact] public async Task BuffersRequestBody_ByDefaultUsingMvcOptions() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString></TestLevelOne>"; var formatter = new XmlDataContractSerializerInputFormatter(new MvcOptions()); var contentBytes = Encoding.UTF8.GetBytes(input); var httpContext = new DefaultHttpContext(); httpContext.Features.Set<IHttpResponseFeature>(new TestResponseFeature()); httpContext.Request.Body = new NonSeekableReadStream(contentBytes, allowSyncReads: false); httpContext.Request.ContentType = "application/json"; var context = GetInputFormatterContext(httpContext, typeof(TestLevelOne)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<TestLevelOne>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.sampleString); } [Fact] public async Task SuppressInputFormatterBufferingSetToTrue_DoesNotBufferRequestBody_UsingMvcOptions() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString></TestLevelOne>"; var formatter = new XmlDataContractSerializerInputFormatter( new MvcOptions() { SuppressInputFormatterBuffering = true }); var contentBytes = Encoding.UTF8.GetBytes(input); var httpContext = new DefaultHttpContext(); httpContext.Features.Set<IHttpResponseFeature>(new TestResponseFeature()); httpContext.Request.Body = new NonSeekableReadStream(contentBytes); httpContext.Request.ContentType = "application/xml"; var context = GetInputFormatterContext(httpContext, typeof(TestLevelOne)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<TestLevelOne>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.sampleString); } [Fact] public async Task ReadAsync_ReadsSimpleTypes() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString></TestLevelOne>"; var formatter = new XmlDataContractSerializerInputFormatter(new MvcOptions()); var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(TestLevelOne)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<TestLevelOne>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.sampleString); } [Fact] public async Task SuppressInputFormatterBufferingSetToTrue_UsingMutatedOptions() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString></TestLevelOne>"; var mvcOptions = new MvcOptions() { SuppressInputFormatterBuffering = false }; var formatter = new XmlDataContractSerializerInputFormatter(mvcOptions); var contentBytes = Encoding.UTF8.GetBytes(input); var httpContext = new DefaultHttpContext(); httpContext.Features.Set<IHttpResponseFeature>(new TestResponseFeature()); httpContext.Request.Body = new NonSeekableReadStream(contentBytes); httpContext.Request.ContentType = "application/xml"; var context = GetInputFormatterContext(httpContext, typeof(TestLevelOne)); // Act // Mutate options after passing into the constructor to make sure that the value type is not store in the constructor mvcOptions.SuppressInputFormatterBuffering = true; var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<TestLevelOne>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.sampleString); // Reading again should fail as buffering request body is disabled await Assert.ThrowsAsync<XmlException>(() => formatter.ReadAsync(context)); } [Fact] public async Task ReadAsync_ReadsComplexTypes() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var expectedLevelTwoString = "102"; var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelTwo><SampleString>" + expectedLevelTwoString + "</SampleString>" + "<TestOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString></TestOne></TestLevelTwo>"; var formatter = new XmlDataContractSerializerInputFormatter(new MvcOptions()); var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<TestLevelTwo>(result.Model); Assert.Equal(expectedLevelTwoString, model.SampleString); Assert.Equal(expectedInt, model.TestOne.SampleInt); Assert.Equal(expectedString, model.TestOne.sampleString); } [Fact] public async Task ReadAsync_ReadsWhenMaxDepthIsModified() { // Arrange var expectedInt = 10; var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<DummyClass><SampleInt>" + expectedInt + "</SampleInt></DummyClass>"; var formatter = new XmlDataContractSerializerInputFormatter(new MvcOptions()); formatter.MaxDepth = 10; var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(DummyClass)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<DummyClass>(result.Model); Assert.Equal(expectedInt, model.SampleInt); } [Fact] public async Task ReadAsync_ThrowsOnExceededMaxDepth() { // Arrange var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelTwo><SampleString>test</SampleString>" + "<TestOne><SampleInt>10</SampleInt><sampleString>test</sampleString></TestOne></TestLevelTwo>"; var formatter = new XmlDataContractSerializerInputFormatter(new MvcOptions()); formatter.MaxDepth = 1; var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo)); // Act & Assert await Assert.ThrowsAsync<InputFormatterException>(async () => await formatter.ReadAsync(context)); } [Fact] public async Task ReadAsync_ThrowsWhenReaderQuotasAreChanged() { // Arrange var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelTwo><SampleString>test</SampleString><TestOne><SampleInt>10</SampleInt>" + "<sampleString>test</sampleString></TestOne></TestLevelTwo>"; var formatter = new XmlDataContractSerializerInputFormatter(new MvcOptions()); formatter.XmlDictionaryReaderQuotas.MaxStringContentLength = 2; var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo)); // Act & Assert await Assert.ThrowsAsync<InputFormatterException>(async () => await formatter.ReadAsync(context)); } [Fact] public void SetMaxDepth_ThrowsWhenMaxDepthIsBelowOne() { // Arrange var formatter = new XmlDataContractSerializerInputFormatter(new MvcOptions()); // Act & Assert Assert.Throws<ArgumentException>(() => formatter.MaxDepth = 0); } [Fact] public async Task ReadAsync_VerifyStreamIsOpenAfterRead() { // Arrange var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<DummyClass><SampleInt>10</SampleInt></DummyClass>"; var formatter = new XmlDataContractSerializerInputFormatter(new MvcOptions()); var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(DummyClass)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); Assert.NotNull(result.Model); Assert.True(context.HttpContext.Request.Body.CanRead); } [Fact] public async Task ReadAsync_FallsbackToUTF8_WhenCharSet_NotInContentType() { // Arrange var expectedException = typeof(XmlException); var inpStart = Encoding.Unicode.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-16\"?>" + "<DummyClass><SampleInt>"); byte[] inp = { 192, 193 }; var inpEnd = Encoding.Unicode.GetBytes("</SampleInt></DummyClass>"); var contentBytes = new byte[inpStart.Length + inp.Length + inpEnd.Length]; Buffer.BlockCopy(inpStart, 0, contentBytes, 0, inpStart.Length); Buffer.BlockCopy(inp, 0, contentBytes, inpStart.Length, inp.Length); Buffer.BlockCopy(inpEnd, 0, contentBytes, inpStart.Length + inp.Length, inpEnd.Length); var formatter = new XmlDataContractSerializerInputFormatter(new MvcOptions()); var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo)); // Act var ex = await Assert.ThrowsAsync(expectedException, () => formatter.ReadAsync(context)); Assert.Contains("utf-8", ex.Message); Assert.Contains("utf-16LE", ex.Message); } [Fact] public async Task ReadAsync_UsesContentTypeCharSet_ToReadStream() { // Arrange var expectedException = typeof(XmlException); var inputBytes = Encoding.UTF8.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<DummyClass><SampleInt>1000</SampleInt></DummyClass>"); var formatter = new XmlDataContractSerializerInputFormatter(new MvcOptions()); var modelState = new ModelStateDictionary(); var httpContext = GetHttpContext(inputBytes, contentType: "application/xml; charset=utf-16"); var provider = new EmptyModelMetadataProvider(); var metadata = provider.GetMetadataForType(typeof(TestLevelOne)); var context = new InputFormatterContext( httpContext, modelName: string.Empty, modelState: modelState, metadata: metadata, readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader); // Act var ex = await Assert.ThrowsAsync(expectedException, () => formatter.ReadAsync(context)); Assert.Contains("utf-16LE", ex.Message); Assert.Contains("utf-8", ex.Message); } [Fact] public async Task ReadAsync_IgnoresBOMCharacters() { // Arrange var sampleString = "Test"; var sampleStringBytes = Encoding.UTF8.GetBytes(sampleString); var inputStart = Encoding.UTF8.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + Environment.NewLine + "<TestLevelTwo><SampleString>" + sampleString); byte[] bom = { 0xef, 0xbb, 0xbf }; var inputEnd = Encoding.UTF8.GetBytes("</SampleString></TestLevelTwo>"); var expectedBytes = new byte[sampleString.Length + bom.Length]; var contentBytes = new byte[inputStart.Length + bom.Length + inputEnd.Length]; Buffer.BlockCopy(inputStart, 0, contentBytes, 0, inputStart.Length); Buffer.BlockCopy(bom, 0, contentBytes, inputStart.Length, bom.Length); Buffer.BlockCopy(inputEnd, 0, contentBytes, inputStart.Length + bom.Length, inputEnd.Length); var formatter = new XmlDataContractSerializerInputFormatter(new MvcOptions()); var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<TestLevelTwo>(result.Model); Buffer.BlockCopy(sampleStringBytes, 0, expectedBytes, 0, sampleStringBytes.Length); Buffer.BlockCopy(bom, 0, expectedBytes, sampleStringBytes.Length, bom.Length); Assert.Equal(expectedBytes, Encoding.UTF8.GetBytes(model.SampleString)); } [Fact] public async Task ReadAsync_AcceptsUTF16Characters() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var input = "<?xml version=\"1.0\" encoding=\"UTF-16\"?>" + "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString></TestLevelOne>"; var formatter = new XmlDataContractSerializerInputFormatter(new MvcOptions()); var contentBytes = Encoding.Unicode.GetBytes(input); var modelState = new ModelStateDictionary(); var httpContext = GetHttpContext(contentBytes, contentType: "application/xml; charset=utf-16"); var provider = new EmptyModelMetadataProvider(); var metadata = provider.GetMetadataForType(typeof(TestLevelOne)); var context = new InputFormatterContext( httpContext, modelName: string.Empty, modelState: modelState, metadata: metadata, readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<TestLevelOne>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.sampleString); } [Fact] public async Task ReadAsync_ThrowsWhenNotConfiguredWithRootName() { // Arrange var SubstituteRootName = "SomeOtherClass"; var SubstituteRootNamespace = "http://tempuri.org"; var input = string.Format( CultureInfo.InvariantCulture, "<{0} xmlns=\"{1}\"><SampleInt xmlns=\"\">1</SampleInt></{0}>", SubstituteRootName, SubstituteRootNamespace); var formatter = new XmlDataContractSerializerInputFormatter(new MvcOptions()); var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(DummyClass)); // Act & Assert await Assert.ThrowsAsync<InputFormatterException>(async () => await formatter.ReadAsync(context)); } [Fact] public async Task ReadAsync_ReadsWhenConfiguredWithRootName() { // Arrange var expectedInt = 10; var SubstituteRootName = "SomeOtherClass"; var SubstituteRootNamespace = "http://tempuri.org"; var input = string.Format( CultureInfo.InvariantCulture, "<{0} xmlns=\"{1}\"><SampleInt xmlns=\"\">{2}</SampleInt></{0}>", SubstituteRootName, SubstituteRootNamespace, expectedInt); var dictionary = new XmlDictionary(); var settings = new DataContractSerializerSettings { RootName = dictionary.Add(SubstituteRootName), RootNamespace = dictionary.Add(SubstituteRootNamespace) }; var formatter = new XmlDataContractSerializerInputFormatter(new MvcOptions()) { SerializerSettings = settings }; var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(DummyClass)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<DummyClass>(result.Model); Assert.Equal(expectedInt, model.SampleInt); } [Fact] public async Task ReadAsync_ThrowsWhenNotConfiguredWithKnownTypes() { // Arrange var KnownTypeName = "SomeDummyClass"; var InstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance"; var input = string.Format( CultureInfo.InvariantCulture, "<DummyClass i:type=\"{0}\" xmlns:i=\"{1}\"><SampleInt>1</SampleInt>" + "<SampleString>Some text</SampleString></DummyClass>", KnownTypeName, InstanceNamespace); var formatter = new XmlDataContractSerializerInputFormatter(new MvcOptions()); var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(DummyClass)); // Act & Assert await Assert.ThrowsAsync<InputFormatterException>(async () => await formatter.ReadAsync(context)); } [Fact] public async Task ReadAsync_ReadsWhenConfiguredWithKnownTypes() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var KnownTypeName = "SomeDummyClass"; var InstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance"; var input = string.Format( CultureInfo.InvariantCulture, "<DummyClass i:type=\"{0}\" xmlns:i=\"{1}\"><SampleInt>{2}</SampleInt>" + "<SampleString>{3}</SampleString></DummyClass>", KnownTypeName, InstanceNamespace, expectedInt, expectedString); var settings = new DataContractSerializerSettings { KnownTypes = new[] { typeof(SomeDummyClass) } }; var formatter = new XmlDataContractSerializerInputFormatter(new MvcOptions()) { SerializerSettings = settings }; var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(DummyClass)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<SomeDummyClass>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.SampleString); } private InputFormatterContext GetInputFormatterContext(byte[] contentBytes, Type modelType) { var httpContext = GetHttpContext(contentBytes); return GetInputFormatterContext(httpContext, modelType); } private InputFormatterContext GetInputFormatterContext(HttpContext httpContext, Type modelType) { var provider = new EmptyModelMetadataProvider(); var metadata = provider.GetMetadataForType(modelType); return new InputFormatterContext( httpContext, modelName: string.Empty, modelState: new ModelStateDictionary(), metadata: metadata, readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader); } private static HttpContext GetHttpContext( byte[] contentBytes, string contentType = "application/xml") { var request = new Mock<HttpRequest>(); var headers = new Mock<IHeaderDictionary>(); request.SetupGet(r => r.Headers).Returns(headers.Object); request.SetupGet(f => f.Body).Returns(new MemoryStream(contentBytes)); request.SetupGet(f => f.ContentType).Returns(contentType); var httpContext = new Mock<HttpContext>(); httpContext.SetupGet(c => c.Request).Returns(request.Object); httpContext.SetupGet(c => c.Request).Returns(request.Object); return httpContext.Object; } private class TestXmlDataContractSerializerInputFormatter : XmlDataContractSerializerInputFormatter { public int createSerializerCalledCount = 0; public TestXmlDataContractSerializerInputFormatter() : base(new MvcOptions()) { } protected override DataContractSerializer CreateSerializer(Type type) { createSerializerCalledCount++; return base.CreateSerializer(type); } } private class TestResponseFeature : HttpResponseFeature { public override void OnCompleted(Func<object, Task> callback, object state) { // do not do anything } } private class VerifyDisposeFileBufferingReadStream : FileBufferingReadStream { public bool Disposed { get; private set; } public VerifyDisposeFileBufferingReadStream(Stream inner, int memoryThreshold) : base(inner, memoryThreshold) { } protected override void Dispose(bool disposing) { Disposed = true; base.Dispose(disposing); } public override ValueTask DisposeAsync() { Disposed = true; return base.DisposeAsync(); } } } }
// // WindowTests.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2013 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 NUnit.Framework; using Xwt.Drawing; namespace Xwt { public class WindowTests: XwtTest { [Test] public void DefaultSize () { using (var win = new Window ()) { win.Padding = 0; var test = new VariableSizeBox (200); win.Content = test; ShowWindow (win); Assert.AreEqual (200, win.Size.Width); Assert.AreEqual (100, win.Size.Height); Assert.AreEqual (200, test.ScreenBounds.Width); Assert.AreEqual (100, test.ScreenBounds.Height); } } [Test] public void FlexibleContentGrowMakesWindowNotGrow () { using (var win = new Window ()) { win.Padding = 0; var test = new VariableSizeBox (200); win.Content = test; ShowWindow (win); Assert.AreEqual (200, win.Size.Width); Assert.AreEqual (100, win.Size.Height); test.Size = 300; // The preferred size grows, but the widget honors the constraint given // by the window (the initial size of the window), so it doesn't make // the window grow WaitForEvents (); Assert.AreEqual (200, win.Size.Width); Assert.AreEqual (100, win.Size.Height); Assert.AreEqual (200, test.ScreenBounds.Width); Assert.AreEqual (100, test.ScreenBounds.Height); } } [Test] public void FixedContentGrowMakesWindowGrow () { using (var win = new Window ()) { win.Padding = 0; var test = new VariableSizeBox (200); test.ForceSize = true; win.Content = test; ShowWindow (win); Assert.AreEqual (200, win.Size.Width); Assert.AreEqual (100, win.Size.Height); test.Size = 300; // The preferred size grows, and it is bigger that the constraint provided // by the window (the initial size of the window), so the window grows to adapt WaitForEvents (); Assert.AreEqual (300, win.Size.Width); Assert.AreEqual (150, win.Size.Height); Assert.AreEqual (300, test.ScreenBounds.Width); Assert.AreEqual (150, test.ScreenBounds.Height); } } [Test] public void ContentWidthGrows () { using (var win = new Window ()) { win.Padding = 0; var test = new VariableSizeBox (200); win.Content = test; ShowWindow (win); Assert.AreEqual (200, win.Size.Width); Assert.AreEqual (100, win.Size.Height); win.Width = 300; WaitForEvents (); Assert.AreEqual (300, win.Size.Width); Assert.AreEqual (150, win.Size.Height); Assert.AreEqual (300, test.ScreenBounds.Width); Assert.AreEqual (150, test.ScreenBounds.Height); } } [Test] public void FixedWidth () { using (var win = new Window ()) { win.Padding = 0; var test = new VariableSizeBox (200); win.Content = test; win.Width = 300; ShowWindow (win); WaitForEvents (); Assert.AreEqual (300, win.Size.Width); Assert.AreEqual (150, win.Size.Height); Assert.AreEqual (300, test.ScreenBounds.Width); Assert.AreEqual (150, test.ScreenBounds.Height); } } [Test] public void DefaultSizeWithMinContentSize () { using (var win = new Window ()) { win.Padding = 0; SquareBox test = new SquareBox (); test.MinWidth = 200; test.MinHeight = 200; win.Content = test; ShowWindow (win); Assert.AreEqual (200, win.Size.Width); Assert.AreEqual (200, win.Size.Height); Assert.AreEqual (200, test.ScreenBounds.Width); Assert.AreEqual (200, test.ScreenBounds.Height); } } [Test] public void ContentMargin () { using (var win = new Window ()) { win.Padding = 0; SquareBox test = new SquareBox (); test.MinWidth = 200; test.MinHeight = 200; test.Margin = 5; win.Content = test; ShowWindow (win); Assert.AreEqual (210, win.Size.Width); Assert.AreEqual (210, win.Size.Height); Assert.AreEqual (200, test.ScreenBounds.Width); Assert.AreEqual (200, test.ScreenBounds.Height); } } [Test] public void ContentMarginChange () { // The size of the window grows if a specific size has not been set using (var win = new Window ()) { win.Padding = 0; SquareBox test = new SquareBox (); test.MinWidth = 200; test.MinHeight = 200; test.Margin = 5; win.Content = test; ShowWindow (win); Assert.AreEqual (210, win.Size.Width); Assert.AreEqual (210, win.Size.Height); Assert.AreEqual (200, test.ScreenBounds.Width); Assert.AreEqual (200, test.ScreenBounds.Height); test.Margin = 10; WaitForEvents (); Assert.AreEqual (220, win.Size.Width); Assert.AreEqual (220, win.Size.Height); Assert.AreEqual (200, test.ScreenBounds.Width); Assert.AreEqual (200, test.ScreenBounds.Height); } } [Test] public void Close () { using (var win = new Window ()) { ShowWindow (win); bool closing = false, closed = false; win.CloseRequested += delegate(object sender, CloseRequestedEventArgs args) { Assert.IsTrue (args.AllowClose); closing = true; }; win.Closed += (sender, e) => closed = true; win.Close (); Assert.IsTrue (closing, "CloseRequested event not fired"); Assert.IsTrue (closed, "Window not closed"); } } [Test] public void CloseCancel () { bool closed = false; using (var win = new Window ()) { ShowWindow (win); win.CloseRequested += delegate(object sender, CloseRequestedEventArgs args) { args.AllowClose = false; }; win.Closed += (sender, e) => closed = true; win.Close (); Assert.IsFalse (closed, "Window should not be closed"); } Assert.IsFalse (closed, "Window should not be closed"); } } public class SquareBox: Canvas { double size; public SquareBox (double size = 10) { this.size = size; } protected override Size OnGetPreferredSize (SizeConstraint widthConstraint, SizeConstraint heightConstraint) { return new Size (size, size); } protected override void OnDraw (Context ctx, Rectangle dirtyRect) { ctx.Rectangle (dirtyRect); ctx.SetColor (Colors.Red); ctx.Fill (); } } class VariableSizeBox: Canvas { double size; bool forceSize; public VariableSizeBox (double size) { this.size = size; } public new double Size { get { return size; } set { size = value; OnPreferredSizeChanged (); } } public bool ForceSize { get { return forceSize; } set { forceSize = value; OnPreferredSizeChanged (); } } // The height of this widget is always half of the width protected override Size OnGetPreferredSize (SizeConstraint widthConstraint, SizeConstraint heightConstraint) { if (widthConstraint.IsConstrained) { var w = forceSize ? Math.Max (size, widthConstraint.AvailableSize) : widthConstraint.AvailableSize; return new Size (w, w / 2); } else if (heightConstraint.IsConstrained) { var h = forceSize ? Math.Max (size / 2, widthConstraint.AvailableSize) : widthConstraint.AvailableSize; return new Size (h * 2, h); } return new Size (size, size / 2); } protected override void OnDraw (Context ctx, Rectangle dirtyRect) { ctx.Rectangle (dirtyRect); ctx.SetColor (Colors.Red); ctx.Fill (); } } }